text:
Q: Publishing message from Lambda function to AWS IoT is not working with aws-sdk I'm trying to publish a message from a lambda function to my AWS IoT Thing, by using the aws-sdk which should use HTTP by default instead of MQTT to publish a message.
Then the Function gets invoked no error message is logged to cloudwatch unfortunately which makes it even harder to debug.
Steps I took:

*

*created a Policy for the message

*created a small React frontend to read messages and test it with IoT test client.

*wrote lambda and passed the Thing url as env var like this: "https://xxxxxdi.eu-central-1.amazonaws.com"

The Lambda function has also a attached Policy which should grant it to write to AWS IoT.
{
      "arn": null,
      "document": {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Action": "iot:Publish",
            "Resource": "arn:aws:iot:eu-central-1:*:*:topic/PairCreated",
            "Effect": "Allow"
          }
        ]
      },
      "id": null,
      "name": "PublishMessage",
      "type": "inline"
    }

Here is the code of the lambda function. The credentials for the object of type IotData are looking ok
import wrap from '@dazn/lambda-powertools-pattern-basic'
import Log from '@dazn/lambda-powertools-logger'
import { IotData } from 'aws-sdk'

export const handler = wrap(async (event: any = {}, context: any)  => {
  Log.info('event', event)
  const iotData = new IotData({endpoint: process.env.IOT_ENDPOINT, region: 'eu-central-1', logger: new Log})

  const params: IotData.PublishRequest = {
    topic: process.env.IOT_THING_NAME || '',
    payload: JSON.stringify(event),
    qos: 0,
    retain: false
  }
  Log.debug('params', { params })

  iotData.publish(params, (err, res) => {
    if (err) {
      Log.error("Error publishing to IOT", { err })
      return context.fail(err)
    };

    Log.info('res', res)
    return context.succeed();
  });
})

The version I'm using: "aws-sdk": "^2.1053.0"
What am I missing?

A: I found out why the message was not sent.
The callback inside of iotData.publish was not executed correctly because the lambda function was terminated before it could be executed. Here are my changes to the code.
await iotData.publish(params, (err, res) => {
    if (err) {
      Log.error("Error publishing to IOT", { err })
      return context.fail(err)
    };

    return context.succeed(res);
  }).promise()

This returns a Promise we can await so the callback gets executed


text:
Q: Return rows which have the same values in two columns, but different values in another I have a table that looks like this:
       id  |           name           |      address       | code
-----------+--------------------------+--------------------+----------
       101 | joe smith                | 1 long road        | SC1
       102 | joe smith                | 6 long road        | SC1
       103 | amy hughes               | 5 hillside lane    | SC5
       104 | amy hughes               | 5 hillside lane    | SC5

I want to return the rows that are duplications based on name and code but have different address fields.
I had something like this originally (which looked for duplications across the name, address and code columns:
SELECT name, address, code, count(*)
FROM table_name
GROUP BY 1,2,3
HAVING count(*) >1;

Is there a way I can expand on the above to only return rows that have the same name and code but different address fields?
In my example data above, I would only want to return:
       id  |           name           |      address       | code
-----------+--------------------------+--------------------+----------
       101 | joe smith                | 1 long road        | SC1
       102 | joe smith                | 6 long road        | SC1

A: Remove address from the select list and GROUP BY and use count(DISTINCT):
SELECT name, code, count(DISTINCT address)
FROM table_name
GROUP BY name, code
HAVING count(DISTINCT address) > 1;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Volume of a solid. There's a solid which is a result of revolution of a rhombus by the axis which is paralell to the shorter diagonal and goes through the end-point of a longer diagonal. Longer diagonal is $\frac2{\sqrt{3}}$, sides are 2 and the angle between diagonals and sides is $60^{\circ}$.
Calculate its volume.
I thought of using Pappus-Guldin theorem - area of rhombus multiplied by the perimeter of circle with radius made of longer diagonal. Is this a proper or I should divide it to cones?
P.S: Sorry for my english, I've never written anything related to math in this language until now.

A: According to the Pappus-Guldin (second) theorem the volume would be equal to the area of the rhombus times the distance travelled by its centroid which is obviously located at the intersection of the diagonals. Thus half of the larger diagonal must be taken as the radius.


text:
Q: Invalid use of group function (MySQL)
why did it happen? I don't understand "where" is wrong.

A: You are using AVG function without grouping. You either use GROUP BY and include AVG in SELECT or in your case, use:
SELECT StudentID
FROM Scores
WHERE score >= (SELECT AVG(score) FROM Scores);


text:
Q: how to validate a record in table before saving in ruby on rails I am new to Ruby on Rails
I have a scenario in which I have a form which has some fields. One of the field values I need to validate against a table which has the data .
I want to restrict the user from saving any data unless the field is validated with the table records.
Initially I added the code in controller to validate that but I have other fields which I need to validate as empty so it did not work .
Also I want the the validation error to be part of other errors.
I tried the below code in the model file
before_create :validate_company_id

def validate_company_id
    cp = Company.find_by_company_id(self.company)
    if @cp != nil
       return
     else
        self.status ||= "Invalid"
     end
end

But its not validating , could you help me how I can validate it .
regards
Surjan

A: instead of using before_create. You can tell the model to use a custom method for validation as follows
validate :validate_company_id

def validate_company_id
    cp = Company.find_by_company_id(self.company)
    if cp.nil?
      errors.add(:company, 'Invalid Company ID')
    end
end

A: The guys answered correctly, but provided the other way for solution. You could ask yourself: "Why doesn't my code get executed?"
First of all, you have errors in your code - @cp is undefined. Also, I don't know what are you trying to achieve with self.status ||= "Invalid".
You also don't have to use self when you're calling an attribute, but you do have to call it when you're assignig a new attribute value. So self.company is unnecessary, you can just use company.
I've also noticed you have the company_id attribute in your companies table. That's not neccessary, common convention is using just an id instead. If you don't want to alter your table you can set the id field on your model like so:
class Company < ActiveRecord::Base
  set_primary_key :company_id

  # ... the rest of your model code ...
end

After that you can use Company.find instead of Company.find_by_company_id.
Okay, let's say you have the following code after the fixes:
before_create :validate_company_id

def validate_company_id
    cp = Company.find(company)
    if cp != nil
       return
     else
        self.status ||= "Invalid"
     end
end

First of all I would like to use ternary operator here
before_create :validate_company_id

def validate_company_id
    Company.find(company) ? return : self.status ||= "Invalid"
end

Isn't this cleaner? It does the exact same thing.
Now about that self.status of yours. If you would like to invalidate the object in ActiveModel you have to set some values in errors hash. You're in misconception if you think that a model with the status attribute of "Invalid" is invalid. It's still perfectly valid model in Rails.
So how do you invalidate?
You put some values into errors hash. You can also specify a message and the attribute you're validation error refers to.
So let's do it on your model
before_create :validate_company_id

def validate_company_id
    Company.find(company) ? return : errors.add(:company,"Invalid Company ID")
end

Now if you try to save your model with invalid company_id it will still pass and get saved to the DB. Why is that?
It's because of the ActiveModels lifecycle. Your method gets called too late.
Here are all the callback methods you can use
Creating
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save

Updating
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save

Destroying
before_destroy
around_destroy
after_destroy

Notice how your method gets called long after the validation cycle. So you should not use before_create, but after_validation or before_validation callbacks instead.
And here we are with the working validation method of your model.
after_validation :validate_company_id

def validate_company_id
    Company.find(company) ? return : errors.add(:company,"Invalid Company ID")
end

A: Inside you model, you can add custom validations as below:

validate :validate_company_id

def validate_company_id
  Your validations
  Add error messages can be added as below
  errors.add(:company, "is invalid")
end


text:
Q: CIGaussianBlur image size I want to blur my view, and I use this code:
//Get a UIImage from the UIView
NSLog(@"blur capture");
UIGraphicsBeginImageContext(BlurContrainerView.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//Blur the UIImage
CIImage *imageToBlur = [CIImage imageWithCGImage:viewImage.CGImage];
CIFilter *gaussianBlurFilter = [CIFilter filterWithName: @"CIGaussianBlur"];
[gaussianBlurFilter setValue:imageToBlur forKey: @"inputImage"];
[gaussianBlurFilter setValue:[NSNumber numberWithFloat: 5] forKey: @"inputRadius"]; //change number to increase/decrease blur
CIImage *resultImage = [gaussianBlurFilter valueForKey: @"outputImage"];

//create UIImage from filtered image
blurredImage = [[UIImage alloc] initWithCIImage:resultImage];

//Place the UIImage in a UIImageView
UIImageView *newView = [[UIImageView alloc] initWithFrame:self.view.bounds];
newView.image = blurredImage;

NSLog(@"%f,%f",newView.frame.size.width,newView.frame.size.height);
//insert blur UIImageView below transparent view inside the blur image container
[BlurContrainerView insertSubview:newView belowSubview:transparentView];

And it blurs the view, but not all of it. How can I blur all of the View?

A: The issue isn't that it's not blurring all of the image, but rather that the blur is extending the boundary of the image, making the image larger, and it's not lining up properly as a result.
To keep the image the same size, after the line:
CIImage *resultImage    = [gaussianBlurFilter valueForKey: @"outputImage"];

You can grab the CGRect for a rectangle the size of the original image in the center of this resultImage:
// note, adjust rect because blur changed size of image

CGRect rect             = [resultImage extent];
rect.origin.x          += (rect.size.width  - viewImage.size.width ) / 2;
rect.origin.y          += (rect.size.height - viewImage.size.height) / 2;
rect.size               = viewImage.size;

And then use CIContext to grab that portion of the image:
CIContext *context      = [CIContext contextWithOptions:nil];
CGImageRef cgimg        = [context createCGImage:resultImage fromRect:rect];
UIImage   *blurredImage = [UIImage imageWithCGImage:cgimg];
CGImageRelease(cgimg);

Alternatively, for iOS 7, if you go to the iOS UIImageEffects sample code and download iOS_UIImageEffects.zip, you can then grab the UIImage+ImageEffects category. Anyway, that provides a few new methods:
- (UIImage *)applyLightEffect;
- (UIImage *)applyExtraLightEffect;
- (UIImage *)applyDarkEffect;
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage;

So, to blur and image and lightening it (giving that "frosted glass" effect) you can then do:
UIImage *newImage = [image applyLightEffect];

Interestingly, Apple's code does not employ CIFilter, but rather calls vImageBoxConvolve_ARGB8888 of the vImage high-performance image processing framework. This technique is illustrated in WWDC 2013 video Implementing Engaging UI on iOS.

A: A faster solution is to avoid CGImageRef altogether and perform all transformations at CIImage lazy level.
So, instead of your unfitting:
// create UIImage from filtered image (but size is wrong)
blurredImage = [[UIImage alloc] initWithCIImage:resultImage];

A nice solution is to write:
Objective-C
// cropping rect because blur changed size of image
CIImage *croppedImage = [resultImage imageByCroppingToRect:imageToBlur.extent];
// create UIImage from filtered cropped image
blurredImage = [[UIImage alloc] initWithCIImage:croppedImage];

Swift 3
// cropping rect because blur changed size of image
let croppedImage = resultImage.cropping(to: imageToBlur.extent)
// create UIImage from filtered cropped image
let blurredImage = UIImage(ciImage: croppedImage)

Swift 4
// cropping rect because blur changed size of image
let croppedImage = resultImage.cropped(to: imageToBlur.extent)
// create UIImage from filtered cropped image
let blurredImage = UIImage(ciImage: croppedImage)

A: Looks like the blur filter is giving you back an image that's bigger than the one you started with, which makes sense since pixels at the edges are getting blurred out past them. The easiest solution would probably be to make newView use a contentMode of UIViewContentModeCenter so it doesn't try to squash the blurred image down; you could also crop blurredImage by drawing it in the center of a new context of the appropriate size, but you don't really need to.


text:
Q: error - karate.mapWithKey is not a function How do I handle below Karate error?

javascript evaluation failed: karate.mapWithKey(list, 'name'), TypeError: karate.mapWithKey is not a function in  at line number 1

def list = [ 'Bob', 'Wild', 'Nyan' ]
def data = karate.mapWithKey(list, 'name')
match data == [{ name: 'Bob' }, { name: 'Wild' }, { name: 'Nyan' }]

A: You are probably on an old version of Karate. Upgrade.
If you are still stuck, follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue


text:
Q: trigger compilation error - statement ignored, missing value keyword, I have the following code which produces a few compiler errors. I've followed several examples online to use these declare and the FROM DUAL concepts, but can't ID the problem. Thanks!
Error1: SQL statement Ignored (referencing line 9 - "DECLARE")
Error2: missing VALUE keyword (referencing line 15 - "FROM DUAL;")

---delete or replace trigger------------------------------

CREATE OR REPLACE TRIGGER videoAuditDeleteTrigger

BEFORE DELETE OR UPDATE
    ON video
    FOR EACH ROW

DECLARE
    v_username VARCHAR2(20);

BEGIN

SELECT USER INTO v_username
FROM DUAL;

INSERT INTO videoAudit
    (videoID
    ,title
    ,releaseDate
    ,category
    ,username
    ,datetimestamp);

VALUES
    (:OLD.videoID
    ,:OLD.title
    ,:OLD.releaseDate
    ,:OLD.category
    ,v_username
    ,SYSDATE);

END;
/

A: Try this, you used extra semicolon in insert statement
CREATE OR REPLACE TRIGGER videoAuditDeleteTrigger

BEFORE DELETE OR UPDATE ON video FOR EACH ROW

DECLARE v_username VARCHAR2(20);

BEGIN

SELECT USER INTO v_username FROM DUAL;

INSERT INTO videoAudit (videoID ,title ,releaseDate ,category ,username ,datetimestamp)
VALUES (:OLD.videoID ,:OLD.title ,:OLD.releaseDate ,:OLD.category ,v_username ,SYSDATE);

END;


text:
Q: Where is Android bug tracker? (other than Android Google Code project) For working around a problem on Android I've reached to this diff. The bug id (Bug 2936741) is not available on Google Code bug tracker of Android, so where is the Android Bug tracker that this diff indicating to?

A: Android bugs with very high numbers are probably in Google's internal bug tracking system. usually if it's a publicly-reported AOSP bug, we'll paste the actual link to that bug tracker (because the internal systems will automatically link to the internal bug tracker, we only need to give the number for those).


text:
Q: SQL: create table with composite referencing primary key, and foreign key So I have the following ER diagram:

So Subthing is a generalization. Stuff is either made out of Metal or Wood, it can't be just a Subthing. Here's the create code:
CREATE TABLE Thing (
    ThingID INTEGER PRIMARY KEY NOT NULL
);

CREATE TABLE Subthing (
    consists_of INTEGER REFERENCES Thing(ThingID),
    SubthingID INTEGER NOT NULL,
    PRIMARY KEY (SubthingID, consists_of)
);

CREATE TABLE Wood (
    Wstuff VARCHAR(40) NOT NULL,
    consists_of INTEGER NOT NULL,
    SubthingID INTEGER NOT NULL,
    FOREIGN KEY (SubthingID, consists_of) REFERENCES Subthing(SubthingID, consists_of),
    PRIMARY KEY (SubthingID, consists_of)
);

CREATE TABLE Dust (
    DustID INTEGER PRIMARY KEY NOT NULL
);

CREATE TABLE Metal (
    Mstuff VARCHAR(40) NOT NULL,
    consists_of INTEGER NOT NULL,
    SubthingID INTEGER NOT NULL,
    requires INTEGER NOT NULL REFERENCES Dust(DustID),
    FOREIGN KEY (SubthingID, consists_of) REFERENCES Subthing(SubthingID, consists_of),
    PRIMARY KEY (SubthingID, consists_of)
);

What I want is for Metal to, at the same time, have a primary key which references (SubthingID, consists_of) and a foreign key with requires, referencing DustID. I can't declare it as a foreign key after the fact since (SubthingID, consists_of) is already a foreign key.
How could you solve this, other than making requires into a table?

A: Never mind, I was too stupid.
CREATE TABLE Metal (
    Mstuff VARCHAR(40) NOT NULL,
    consists_of INTEGER NOT NULL,
    SubthingID INTEGER NOT NULL,
    requires INTEGER NOT NULL,
    FOREIGN KEY (requires) REFERENCES Dust(DustID),
    FOREIGN KEY (SubthingID, consists_of) REFERENCES Subthing(SubthingID,     consists_of),
    PRIMARY KEY (SubthingID, consists_of)
);

Works just fine.


text:
Q: Throwing errors/response outside exports.handler I've just started using AWS Lambda/Node.JS/API Gateway with API Lambda Proxy integration, and I'm struggling with something that should be simple. Handling error from outside exports.handler.
I've developed all my code, it's all working fine, however, I'm struggling to handle errors. I'm using async/await, no callback.
Basically, my code looks like something like this:
exports.handler = async (event, context) => {
  const sampleVar = await sampleFunction();

  const response = {
    statusCode: 200,
    body: JSON.stringify(sampleVar),
    isBase64Encoded: false
  };
  return response;
}

Great, right? My problem is that all my "real code" is being developed outside the exports.handler in different functions, something like:
async function sampleFunction() {
  const test = 123;
  return anotherFunction(test);
}

async function anotherFunction() {
  const test2 = 'blablabla';
  return test2;
}

Now, let's suppose that an error happens on my sampleFunction and I need to throw the error right away. I could just go throw { statusCode: 400, etc, etc };, however, if I throw the error, I get a "500 Internal Server Error" as my response, no matter what. I can only proper break my code if I handle the error from within my exports.handler function. In that case, I could go return { statusCode: 400, etc, etc }; or context.fail(), etc, and everything would be alright.
My question is: is there any way to "break" my code and send a proper response from outside my exports.handler? Or maybe externally call my exports.handler to return a specific response?

A: so, i would write this in the comments, but the markup is a bit poor. I would do something like the below:
exports.handler = async (event, context) => {
  return await sampleFunction().then(craftOk).catch(craftErr);
}

function craftOk(res) {
  return {
    statusCode: 200,
    body: JSON.stringify(res),
    isBase64Encoded: false
  };
}

function craftBad(err) {
  return {
    statusCode: 400,
    body: err.message,
    isBase64Encoded: false
  }
}

for fun, I wrote a test script to validate return from catch on async/await...maybe it will help
function test(toggle) {
    return (toggle) ? Promise.resolve("yay") : Promise.reject(new Error("boo"))
}

async function main1() {
    let res =  await test(true).then( res => {
        return {
            statusCode: 200,
            body: res,
            isBase64Encoded: false
        }
    })
    .catch(err => {
        return {
            statusCode: 400,
            body: err.message,
            isBase64Encoded: false
        }
    })
    return res
}

async function main2() {
    let res =  await test(false).then( res => {
        return {
            statusCode: 200,
            body: res,
            isBase64Encoded: false
        }
    })
    .catch(err => {
        return {
            statusCode: 400,
            body: err.message,
            isBase64Encoded: false
        }
    })
    return res
}

main1().then(console.log)
main2().then(console.log)


text:
Q: SQL - filter table from another table I have two table.
EX_A:
Select TAB1,TAB2,max(TAB3),TAB4,TAB5,TAB6
FROM TEST
where TAB1 = 'BLACK' or TAB1 = 'RED' or TAB1 = 'YELLOW'
group by TAB1,TAB2,TAB4,TAB5,TAB6
-----------------------------------------------------
EX_B:
select TAB2A, max(TAB2B)
from TEST2
where TAB2A = 'BLACK' or TAB2A = 'RED' or TAB2A = 'YELLOW'
group by TAB2A

This table is also select from other tables.
But in order to provide data, so I use CREATE TABLE here.
CREATE TABLE TEST (
TAB1 VARCHAR(50),
TAB2 VARCHAR(50),
TAB3 VARCHAR(50),
TAB4 VARCHAR(50),
TAB5 VARCHAR(50),
TAB6 VARCHAR(50)
);

INSERT INTO TEST
VALUES ('BLACK', '2.4', '20201019', '20000', '102','UA'),
('BLACK', '2.4', '20201019', '10000', '102','UA'),
('BLACK', '1.8', '20201019', '50000', '103','UD'),
('BLACK', '1.8', '20201019', '25000', '103','UD'),
('RED', '9.6', '20201015', '1000', '102','UA'),
('RED', '5.2', '20201020', '5000', '104','UD'),
('RED', '5.2', '20201020', '1000', '104','UD'),
('YELLOW', '7.5', '20201012', '5000', '102','UA');
---------------------------------------------------
CREATE TABLE TEST2 (
TAB2A VARCHAR(50),
TAB2B VARCHAR(50)
);

INSERT INTO TEST2
VALUES ('BLACK', '20201019'),
('RED', '20201020'),
('YELLOW', '20201012');

Like this

I hope to find the largest TAB3 based on TAB1 and output this result.

I try to use EX_B as Subquery to filter out EX_A.
I keep getting errors and I don't know where is the problem.
Select TAB1,TAB2,max(TAB3),TAB4,TAB5,TAB6
FROM TEST T1
where T1.TAB1 IN
(select TAB2A, max(TAB2B)
from TEST2 T2
where (TAB2A = 'BLACK' or TAB2A = 'RED' or TAB2A = 'YELLOW') and T2.TAB2A = T1.TAB1
group by TAB2A)
group by TAB1,TAB2,TAB4,TAB5,TAB6;

What should I do to complete my task
Thank you

A: This gives the output you have shown, (as per here), but I'm not sure your data set demonstrates your problem sufficiently. According to what you've provided, you are doing an equijoin on the values in table TEST2 column, so I'm not clear where the need for MAX comes in. So if this answer is not correct, please update your question to provide additional data that demonstrates the issue.
SELECT a.* FROM test a
JOIN test2 b ON a.tab1 = b.tab2a and a.tab3 = b.tab2b

EDIT: If you want dates (I presume they're dates!) in table TEST (tab3) that are equal or greater than the dates (tab2b) in table TEST2, then just change a.tab3 = b.tab2b to a.tab3 >= b.tab2b


text:
Q: Given string how do I replace certain words with multiple words in an array? Let's say I have a sentence and an array of words:
let sentence = 'My * is * years old.';
let words = ['dog', 3];

//expected result => My dog is 9 years old.

How would I replace each asterisk (*) with the appropriate word in the given array?
But let's also say that there's case where there are more asterisks than elements in the array:
let sentence = 'The soldiers marched *, *, *, *.';
let words = ['left', 'right'];

//expected result => The soldiers marched left, right, left, right.

Is using regex the only way to solve this or is there a vanilla JS solution?

A: You could take a replacement function with an additional value for the starting index, which has a default value of zero.
For keeping the index in a valid range, you could take the remainder operator % with the length of the array.

const
    replace = (string, array, i = 0) =>
        string.replace(/\*/g, _=> array[i++ % array.length]);

console.log(replace('My * is * years old.', ['dog', 3]));
console.log(replace('The soldiers marched *, *, *, *.', ['left', 'right']));

A:

let sentence = 'My * is * years old.';
let words = ['dog', 3];
let count =0;
while (sentence.indexOf('*') > -1) {
    sentence = sentence.replace('*', words[count++]);
    if (count >= words.length) count = 0;
}
console.log(sentence);

shows: "My dog is 3 years old."

A: If you really dislike regular expressions you could do this:
words = ["left", "right"];
"The soldiers marched *, *, *, *.".split("*").map(function (x, i) {
  return i === 0 ? x : words[(i + 1) % words.length] + x;
}).join("");

Trace of execution:
init  | "The soldiers marched *, *, *, *."
split | ["The soldiers marched ", ", ", ", ", ", ", "."]
i = 0 | ["The soldiers marched ", ", ", ", ", ", ", "."]
i = 1 | ["The soldiers marched ", "left, ", ", ", ", ", "."]
i = 2 | ["The soldiers marched ", "left, ", "right, ", ", ", "."]
i = 3 | ["The soldiers marched ", "left, ", "right, ", "left, ", "."]
i = 4 | ["The soldiers marched ", "left, ", "right, ", "left, ", "right."]
join  | "The soldiers marched left, right, left, right."

A: Another regexp free option:
s = "The soldiers marched *, *, *, *.";
f = Function("words", "var i = 0; return \"" + s.split("*").join(
  "\" + words[(i++) % words.length] + \""
) + "\";");

> | f(["L", "R"])
< | "The soldiers marched L, R, L, R."
> | f(["L", "R"].reverse())
< | "The soldiers marched R, L, R, L."
> | f(["L", "R", "R"])
< | "The soldiers marched L, R, R, L."

Beware of malicious code though:
s = "The soldiers marched *, *, *, *.";
s = "\", console.log(\"VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!\"), \"" + s;
f = Function("words", "var i = 0; return \"" + s.split("*").join(
  "\" + words[(i++) % words.length] + \""
) + "\";");

> | f(["L", "R"])
  | VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!
< | "The soldiers marched L, R, L, R."

You should always sanitize the input:
s = "The soldiers marched *, *, *, *.";
s = "\", alert(\"VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!\"), \"" + s;
s = s.split("\"").join("\\\""); // potentially not sufficient!
f = Function("words", "var i = 0; return \"" + s.split("*").join(
  "\" + words[(i++) % words.length] + \""
) + "\";");

> | f(["L", "R"])
< | "", alert("VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!"), "The soldiers marched L, R, L, R."

But I would not venture that it's bullet proof :-|

A: One character after the other:

input = "The soldiers marched *, *, *, *.";
words = ["left", "right"];
output= ""
for (i = 0, j = 0; i < input.length; i++) {
  output += input[i] !== "*" ? input[i] : (
    words[(j++) % words.length]
  );
}
console.log(output)

As you can see, there are multiple alternatives to regular expressions. Anyway, what you really need to understand is the remainder operator (%):
0 % 2 = 0 | 0 -> 0
1 % 2 = 1 | 1 -> 1
2 % 2 = 0 | 2 -> 0
3 % 2 = 1 | 3 -> 1
4 % 2 = 0 | 4 -> 0

0, 1, 0, 1, 0, 1, ... Got it? The result never reaches the right operand. This is especially useful when you need to iterate over the same array more than once:

abc = ["A", "B", "C"]
for (i = 0; i < 2 * abc.length; i++) {
  // j will never reach abc.length
  j = i % abc.length; // 0, 1, 2, 0, ...
  console.log(i, j, abc[j]);
}


text:
Q: How to know build date for C# Class libraries I'm doing C# Winform application. I have several class libraries. each library is also project. Usally, I used below code to know the build date of my application. However, I want to know build date for each class library. any help...
 DateTime buildDate = new
        FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
 MessageBox.Show(string.Format("Build Date : {0}", buildDate), "Version Info");

A: UPDATED
What about this?
System.IO.FileInfo fileInfo = new System.IO.FileInfo(Assembly.GetExecutingAssembly().Location);
DateTime lastModified = fileInfo.LastWriteTime;

Or you could try something as explained in the answer here:
ASP.NET - show application build date/info at the bottom of the screen

A: To get list of all assemblies in process use (AppDomain.CurrentDomain)[http://msdn.microsoft.com/en-us/library/system.appdomain.currentdomain.aspx] and then AppDomain.GetAssemblies.
With the list use your code (new FileInfo(assembly.Location).LastWriteTime; or better yet get Version via AssemblyName.Version by using sample from that article:
  Console.WriteLine("The version of the currently executing assembly is: {0}",
        Assembly.GetExecutingAssembly().GetName().Version);

  Console.WriteLine("The version of mscorlib.dll is: {0}",
        typeof(String).Assembly.GetName().Version);


text:
Q: How to reinstall OS X after changing hard drive? I have problem with my MacBook Pro. The hard drive was broken, and I installed new one.Totaly empty, without EFI and everything.
I can not install OS X on it.
I only able to launch "Internet recovery" (holding option key during startup). So it is possible to run Disk Utility and Terminal. When I try to install system from this recovery, I have error;
I also unable to boot from flash-drive, pressing C key. But, I can mount flash drive from Internet Recovery and try to start setup. I have another error "This copy of the Install OS X Mountain Lion can't be verified. It may have been corrupted or tampered during downloading". I tried to use different versions, but error is the same.
What can I do to start my mac?

A: I found in internet just "InstallESD.dmg" image, and with this file I repaired computer.
Very easy :)
Thanks for everyone!


text:
Q: Definition of independent random variables In Terrence Tao's notes,he made the following definition

Definition 16: A collection $(X_i)_{i \in A}$ of random variables $X_i$ is said to be jointly independent if satisfies one of the following

*

*the distribution $(X_i)_{i \in A}$ is the product of distributions of the $X_i$.

*$$ P( \bigwedge_{i \in B} (X_i \in S_i) ) = \prod_{i \in B} P(X_i \in S_i).$$
  for all finite sets $B \subseteq A$, and measurable set $S_i$ of $R_i$.

I don't understand definition 1. What is it written out explicitly? No where does he defines the distribution of $(X_i)_{i \in A}$. Suppose we regard $(X_i)_i : \Omega \rightarrow \prod R_i$. I guess definition 1 is :

Definition' $X_i$ are independent iff for all measurable $S \subseteq \prod R_i$,
  $$ P((X_i)_i \in S ) = \prod P\Big((X_i) \in \pi_i(S)\Big). $$

This results in two questions.

*

*I don't know how this makes sense as the product on RHS is infinite.

*How would this be equivalent to the second formulation (note $S$ is not a product set here ).


text:
Q: How to deal with objects waiting for fetch in Typescript I'm moving from javascript to typescript, and this is an error that I encounter multiple times:
In a component, I'm awaiting a fetch to return an object, and until that time, the component returns null. If the object is there, I will render some properties of the object:
const Component = () => {
  const [user, setUser] = useState(null)

  useEffect(() => {
    getUser().then(setUser)
  }, [getUser])

  if (!user) return null

  return (

{`Username: ${user.userName}`}

{`Email: ${user.email}`}

  )
}

Typescript then throws an error Object is possibly 'null'.  TS2531
For a more general case, this question already has an answer here:
How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?
However, assuring that the object is never null doesn't feel right. I mean, I could initialise the object;
const [user, setUser] = useState({ userName: 'UNKNOWN', email: 'UNKNOWN' })

but that clearly doesn't seem to be the best solution to me either.
I'm disappointed that typescript doesn't recognise that the user can never be null when it reaches the JSX. But this is probably because I'm thinking way to naively about this.
Remains the question - how do I deal with this typical scenario in a typescript component?

A: Issue here is that you don't tell to TypeScript, what type can have the user state. To fix it, just define a type for User and specify in the useState:
type User = {
  userName: string;
  email: string;
};

const [user, setUser] = React.useState<User | null>(null);


text:
Q: Trouble with type matching and IO in a recursive function I'm experiencing some problems and can't find their reason. I am currently using the most recent version of GHCi portable - but to face the truth: It is my first time using Haskell, so as usual the problem is probably the user and not so much the system...
Problems that arise include:

*

*I am not completely sure I got the difference between let x = 0 and x <- 0 right. I understand that let is to be used with pure functions, <- with side effects (IO)? Someone please explain that to me once again.

*I have mismatchings between types, namely String and (String,[Char]) (and sometimes others...). The compiler tells me that String was expected, although I clearly defined the function as (String,String). What's going on? Did I somewhere make a mistake with the pattern matching?

*The recursion does not work as expected (i.e. doesn't work at all apparently). If someone could help me with that, I would be very grateful.

Here's what I want to do:
I am trying to write a little program that implements a finite state machine accepting a word. That means it takes a set of states, one of which is the start state, a list of accepting states, and a number of transition rules. (The alphabets which represent the possible input and states are somewhat implicit.) I don't want to go into too much detail about FSMs here.
However, this is how I figured a way to define such a FSM could look:
"a(b+|c+)"
"start"
["b","c"]
[
("start",   [('a',"a"),                         ('_',"reject")]),
("a",       [           ('b',"b"),  ('c',"c"),  ('_',"reject")]),
("b",       [           ('b',"b"),              ('_',"reject")]),
("c",       [                       ('c',"c"),  ('_',"reject")]),
("reject",  [                                   ('_',"reject")])
]

In the first line, we have short description of what the FSM is supposed to accept (in form of a regex in this case). It is only used to display it once.
The second line defines the start state, the third line a list of accepting states.
All following lines together are the transition rules. In this example, if we are in state "start" and read an input 'a', the next state is "a", if we read anything else, it is "reject". (I am aware that I have not yet implemented the '_' meaning an else and the program will crash if an input is read for which no transition is defined.)
So here comes the program:
module FSM where

import System.IO

main :: IO ()
main = do
    putStr "Enter file name: "
    fileName <- getLine
    (description, startState, acceptingStates, stateTransitions) <- (readDef fileName)
    putStrLn ("FSM description: " ++ description)
    putStr "Enter FSM input: "
    input <- getLine
    let input = reverse input
    putStrLn "----------------"
    let (finalState, oldStates) = changeState input startState stateTransitions
    putStrLn (oldStates ++ finalState)
    checkAcception finalState acceptingStates

--reads the specified .fsm file and returns
--  the description of the FSM (first line),
--  the start state (second line),
--  the list of accepting states (third line),
--  and the list of tuples containing all states and transitions (remaining lines)
readDef :: String -> IO (String, String, [String], [(String, [(Char,String)])])
readDef fileName = do
    contents <- readFile (fileName ++ ".fsm")
    let lineList = lines contents
    let description = read (head lineList)
    let startState = read (lineList !! 1)
    let acceptingStates = read (lineList !! 2)
    let stateTransitions = read (filter (/='\t') (concat (drop 3 lineList)))
    return (description, startState, acceptingStates, stateTransitions)

--recursive function that takes the input, start state, and state transitions
--and computes the new state by a call to itself with the old state and a part of the input
changeState :: String -> String -> [(String, [(Char,String)])] -> (String, String)

changeState startState [] _ = (startState, "")

changeState startState (x:xs) stateTransitions = do
    let (currentState, oldStates) = changeState xs startState stateTransitions
    let newState = findKey x (findKey currentState stateTransitions)
    let oldStates = (oldStates ++ currentState ++ " -(" ++ [x] ++ ")-> ")
    return (newState, oldStates)

--helper function to find a key in a list of tuples and return the corresponding value
--(because we are not using the map notation in the .fsm file)
findKey :: (Eq k) => k -> [(k,v)] -> v
findKey key xs = snd . head . filter (\(k,v) -> key == k) $ xs

--checks for a given state whether or not it is in the list of accepting states
checkAcception :: String -> [String] -> IO ()
checkAcception finalState acceptingStates = do
    let accept = any (==finalState) acceptingStates
    if accept
        then putStrLn "Input accepted!!"
        else putStrLn "Input rejected!!"

The idea is to have the user choose a file from which the definition is loaded (readDef, works like a charm). He is then prompted to enter some input the FSM works on.
The recursive changeState then does the actual work (doesn't work as well...).
Finally, the sequence of states and transitions is displayed and it is checked whether the final state is an accepting state (checkAcceptance).

Now, don't try to optimize what I have written. I know, the way the definition is modeled can be improved and many of the lines I wrote can be written far shorter using some high order Haskell foo. But please just help me with the issues listed above (and of course help me make it work).
Thanks a lot in advance.
One last thing: I'm trying some Haskell for a seminar at my university, so if someone from the Software Architecture Group googled my code and reads this: Hi :)

A: You can get things to compile by just changing the second clause of the changeState function to:
changeState startState (x:xs) stateTransitions =
    let (currentState, oldStates) = changeState xs startState stateTransitions
        newState = findKey x (findKey currentState stateTransitions)
        oldStates2 = (oldStates ++ currentState ++ " -(" ++ [x] ++ ")-> ")
    in (newState, oldStates2)

We've 1) removed the do, 2) combined the let clauses and 3) renamed the second occurrence of the oldState variable to oldState2. In Haskell we don't redefine variables - we just create a variable with a new name. Complete code is available here: http://lpaste.net/118404
When you write:
(new, old) = changeState ...

you are saying that changeState is a pure function. If you define changeState with do ... return (...) you are saying it is a monadic computation and when you call it you need to use the arrow <- in a do block:
(new, old) <- changeState ...

Since changeState is a pure function (doesn't need to do IO) you might as well keep it as a pure function, so there is no reason to use do and return.

A: The problem is that do notation and the return function don't do what you think they do. In Haskell: return doesn't signify that a function should end (even though it's most commonly seen at the end of functions); it just means that the argument should be wrapped in a Monad. Because the type of your function with all arguments applied is (String,String) the compiler thought you were trying to use something like this: (won't actually compile without GHC extensions, and will throw exceptions if used because I used undefined)
instance Monad ((,) String) where
  (>>=) = undefined :: (String,a) -> (a -> (String,b)) -> (String,b)
  return = undefined :: a -> (String,a)

But the compiler already knew that (String,String) -> (String,String) doesn't match a -> (String,a) so it didn't get as far as checking whether or not the instance exists.
Fixing this problem revealed another one: you define oldStates twice in the same function, which doesn't work in Haskell unless the two definitions are in different scopes.
This is your function modified to compile properly, but I haven't tested it.
changeState :: String -> String -> [(String, [(Char,String)])] -> (String, String)

changeState startState [] _ = (startState, "")

changeState startState (x:xs) stateTransitions = let
    (currentState, oldStates) = changeState xs startState stateTransitions
    newState = findKey x (findKey currentState stateTransitions)
    oldStates' = (oldStates ++ currentState ++ " -(" ++ [x] ++ ")-> ")
    in (newState, oldStates')


text:
Q: Local polynomial form of holomorphic functions It is well-known that a germ of a holomorphic function of $n\geq 2$ variables, with at most an isolated singularity (i.e. the singularity of the analytic variety defined by the zero locus of the function), is locally conjugate (by right composition with a local biholomorphism) to a polynomial (in fact, a finite jet of the function).
This statement is not true anymore when $n\geq 3$ if the singularity is not isolated, although I can't find a reference containning examples of germs not locally conjugate to polynomials. Yet if I remember correctly, it is true when $n=2$.
Also I would be interested in knowing what happens in the meromorphic case, which I believe is still open.
I would be grateful for any pointer in the litterature towards such results!
PS: I hope this question is not a duplicate. I couldn't possibly browse through all the search results for requests  like «polynomial holomorphic function», and was unable to think about sharper keywords…

A: The following example of non-algebraic germ is due to Whitney, see
H. Whitney: Local properties of analytic varieties, Differential and Combinatorial Topology 205–244, Princeton University Press (1965).
Take the germ of singularity in $\mathbb{C}^3$ given by $f(x,y,z)=0$, where $$f=xy(x+y)(x- zy)(x-e^zy).$$
The set $\{f=0\} \cap \{z= \lambda \}$ is given by five distinct lines through the origin.
If $f$ would be conjugate to a polynomial, the cross-ratios of any four of these lines would depend algebraically on $\lambda$. But this is impossible, because we have $\lambda$ and $e^{\lambda}$.
So this germ is not conjugate to a polynomial (or algebraic) germ.


text:
Q: Should I reset the sequence to MAX(id) or MAX(id)+1 after a data import? As stated in the title, should I reset a PG sequence to MAX(id) or to MAX(id)+1 after a data import?
-- is what SELECT MAX(id) FROM my_table or
-- SELECT MAX(id)+1 FROM my_table

ALTER SEQUENCE my_table_id_seq RESTART WITH what;

If I pick a table and do SELECT MAX(id) FROM my_table, I get x, then I look into the sequence last_value and it shows x=MAX(id) and NOT MAX(id)+1
So to me it locally means that PG keeps track (and should be reset to) the last value i.e. MAX(id) and not to MAX(id)+1

A: The docs at https://www.postgresql.org/docs/current/sql-altersequence.html say

The […] clause RESTART WITH restart changes the current value of the sequence. This is similar to calling the setval function with is_called = false: the specified value will be returned by the next call of nextval.

So you'll need COALESCE((SELECT MAX(id) FROM my_table), 0) + 1, or the next nextval() call will return a value that already exists in your table.


text:
Q: How do I read a fedora partition from windows? Windows recognizes and gives my fedora partition a drive letter, but it shows it as blank. Is there a way to get windows to read ext3 filesystem?  Its a Fedora 10 partition.

A: I'd take a look at EXT2 IFS for Windows.
Several things to keep in mind with this.

*

*Ext3 is backwards compatible with Ext2, it just doesn't write to the journal

*NTFS is case insensitive, this may screw with you depending on what you are moving

*Some filenames that are valid in Ext2/3 are invalid in NTFS/VFAT like : and $

*Special files will be inaccessible, sockets, soft links, block devices

*permissions are not maintained

*Will not work with LVM volumes

It will let you read and write to it though ;)

A: See the answers to my similar question on ServerFault.com:

*

*What Windows ext3 driver should I use?
Summary of the best answer I got (and other answers were later deleted, I assume by their authors):  Use ntfs-3g to access the NTFS filesystem from Linux.  You will have a much smaller chance of filesystem corruption doing it this way than using any of the existing ext2/3 drivers from Windows.

A: I know that you want to mount your Fedora partition but from experience I have found that the best way to share a partition with Windows is to format as NTFS and use ntfs-3g to access it in Linux.
I tried using the ext2 Windows app mentioned by JensenDied a couple of years ago and ended up having problems accessing data on the USB drive that it was being used with.


text:
Q: Building a notification from a modal in React Navigation I am attempting to build a notification service I can use within React Navigation; how far I have gotten in this:

Now this is a modal, that the card element has been hidden and then the view style has been filled into only 15% at the top of the element, and the element will react if you click out of the white area of the notification.
Here is the code for the NotificationModal:
import React from 'react';
import { View, TouchableHighlight,TouchableWithoutFeedback } from 'react-native';
import { Text } from 'react-native-elements';

export default class NotificationModal extends React.Component {

    static navigationOptions = ({ navigation }) => {
        const title = navigation.getParam('title','No item found...');
        return {
            title: title
        };
    };

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log(this.props);
    }

    render() {
        const { navigation } = this.props;
        let title = navigation.getParam('title', '');
        return (
            <TouchableWithoutFeedback>
                <View style={{ flex: 1 ,flexDirection: 'column', justifyContent: 'flex-start'}}>
                    <View style={{ height: "15%" ,width: '100%', backgroundColor:"#fff", justifyContent:"center"}}>
                        <Text style={{fontSize:25}}>{title}xd</Text>
                    </View>
                    <TouchableHighlight onPress={() => { this.props.navigation.goBack(); }} style={{backgroundColor: "rgba(0,0,0,0)"}}>
                        <View style={{ height: "85%" ,width: '100%', backgroundColor: "rgba(0,0,0,0)", justifyContent:"center"}}>
                            <View>
                            </View>
                        </View>
                    </TouchableHighlight>
                </View>
            </TouchableWithoutFeedback>
        );
    }
}

At at my root navigation stack it looks like this:
export default RootStack = createStackNavigator(
    {
        Main: {
            screen: MainStack,
        },
        QuickStockModal: {
            screen: StockModal,
        },
        NotificationModal: {
            screen: NotificationModal,
        }
    },
    {
        mode: 'modal',
        headerMode: 'none',
        cardStyle:{
            backgroundColor:"transparent",
            opacity:0.99
        }
    }
);

Finally I call this pseudo notification modal like any other navigation instance:
this.props.navigation.navigate('NotificationModal', {
            title: 'test'
        });

Problems with this

*

*It wont just act as a quick update, it will overtake the touch area, I just wish to let the user know things like 'search results empty' or 'barcode invalid' etc, without hijacking the touch. (But being able to touch buttons of the notification within the white area thats visible)

*When you press the outside area to dismiss it, the 'dismiss area' turns dark as it disappears, this looks bad, I am hoping to change the animation to simply push up instead of down and hopefully avoid this

*this is a messy way to do notifications but other manners will complicate my current app design too much (Using Redux for instance, will be alot of work for simply trying to add in-app notifications)

*In-app notification libs arent customizable enough and also dont even work properly sadly


text:
Q: How to clear/ reset a JFrame Me and my friend have decided to work on a card game which cycles between 3 screens (Player1HandScreen, Player2HandScreen and FightScreen).
Once Player1 has chosen their card from Player1HandScreen, Player1HandScreen leads to Player2HandScreen where Player2 does the same. then Player2HandScreen leads to FightScreen where the two cards are compared and one player is declared the winner of that round.
The problem we are having is that once the round ends we want to clear Player1HandScreen as well as the Player2HandScreen once refreshing our parameters we are having trouble updating the GUI successfully.
We have have tried to use removeAll(), but we can't get it to repaint() or validate().
We have also looked into super.paintComponents(g) and updateUI() but both have left us with crushed hopes and dreams.

A: if you remove any JComponent(s) from Container (only once on the end), is needed tell to Container for,
removeAll()//or remove(JComponent)
revalidate();
repaint();

A: Try to clear you Jpanel using:
paper.clearRect(0, 0, (int)panel.getSize().getWidth(), (int)panel.getSize().getHeight

where paper is something like: Graphics paper = panel.getGraphics();


text:
Q: Проблема с работой google tag manager http://pokritijametallov.ru/
Существует проект на котором появилась проблема подключения GTM.
(ранее с ним(GTM) не работал.)
При попытке подключить данный модуль 3-мя способами:
1.https://github.com/nuxt-community/gtm-module
(в данном случае пробовал 2 разные версии плагина.)
2.(Этот способ реализован на текущей версии проекта.)

3.

Получаю после деплоя один и тот же баг:
Заключается он в том что GTM отслеживает страницы только при первом посещении ресурса или же после перезагрузки страницы в браузере(с обновлением кэша).
При переходе на остальные страницы отслеживание не работает.
Первое что приходит на ум - это причина в `nuxt-link`-ах, по которым собственно происходит переход на остальные страницы.
В фаербаге в сети так же можно увидеть, что никакой загрузки GTM не происходит после переходов по внутренним линкам.

Вопрос:
В чем может быть проблема и как ее решить?

A: Надо в настройки добавить правильный eventName который настраивается в аналитике, в моем случае это:
gtm: {pageViewEventName: 'page_view',},


text:
Q: Section not created in program-release version C++ I am storing some variables inside custom section in my program. During debugging session I can check it is created and that it contains the necessary data. But in release mode, it disappears!
Note: I am also creating an executable section which strangely is created in both version. The CPU platform seems to make no difference.
Why doesn't the "data" segment appear in the release version?
This is a short snapshot:
// Defnitions used for better code segmentation
#define store_variable(x) __declspec(allocate(x))  //for data segment
#define store_code(seg) __declspec(code_seg(seg))  //for execution segment

#pragma section(".eqwrt", read)     //weird name because I thought there would be collision
store_variable(".eqwrt") UCHAR  USER_DATA[SIZE];
store_variable(".eqwrt") USHORT Version = 1;

store_code(".wsect") bool sendError();

The program (it's a dll) is compiled with a fixed base address and with /MT flag.
Release version x64. Only one segment appears-the executable one:

Debug version x64. Both segments show up:

A: Try to disable Link-time optimizatizon scheme from the project's settings.
To do that go to: Configuration Properties General Whole Program Optimisation and set to No Whole Program Optimisation.
Most likely it has something to do with the optimisations performed during linking.
More details you can get from here : What's C++ optimization & Whole program optimization in visual studio


text:
Q: error running cpan the first time I'm wondering if anyone can help me. I installed CPAN.pm via command line and then tried installing a module via CPAN. But I encountered an error:
Can't call method "http" on unblessed reference at /usr/lib/perl5/5.10.0/CPAN/FirstTime.pm line 1866.

A: This error can be resolved by entering the username and password fields in the proxy that cpan uses.
1] First Install cpan by
sudo yum install perl-CPAN

2] Then run the following command
cpan

It asks for setting basics, then select "NO" option for automatically picking then keep pressing enter till you are asked for "Automatically connect to internet", press no.
3] Then you will be asked for mirror details keep selecting from the list that it provided.
4] Then set the proxy username and password fields
5] Installation will then be complete and it will take you to cpan> prompt like below
cpan>

6] In the prompt enter
install Bundle::LWP

A: Firstly I'm surprised that CPAN isn't already installed as it has been part of the standard Perl distribution since Perl 5.004 was released fifteen years ago.
Secondly I'm surprised that you're still using Fedora 11. That version has been unsupported since June 2010.
Thirdly, I'm surprised that you want to use CPAN.pm as CPANPLUS and cpanminus are both far better interfaces to CPAN.
But given all of those surprises, if you want CPAN on your system, the best approach is probably to use the one that the Fedora project have pre-built for you.
$ sudo yum install perl-CPAN

There will be a number of CPAN modules available pre-build from Fedora. You can see them all using:
$ yum list available perl-\*

You'll find even more available for recent versions of Fedora.
You can almost certainly get CPANPLUS by installing perl-CPANPLUS. I doubt whether cpanminus is available for such an old version of Fedora.

A: I just had the same issue while installing Perlbrew.
After doing some debugging, I found out that this error happens because the CPAN logic could not find a mirror candidate. Of course, this could be improved in the CPAN::Mirrors or CPAN::FirstTime by just checking the results returned by the related functions.
Since those are not checked (and thus assumed that always returns some value) I got this meaningless error. But I must say I didn't checked further to see why no value is being returned after all.
You can safely avoid this error by simply selection No as answer for the automatic configuration. Of course, you will need to reply for each one of the configuration directives.
I got this while installing perl 5.16.3 thru perlbrew.

A: I had the same error, and did not have root privileges.  The problem lay with there being two versions of cpan installed:

*

*/usr/bin/cpan

*/usr/local/bin/cpan

When I specified the former, things began to work.

A: replace Config.pm with fixed vertion
wget http://search.cpan.org/CPAN/authors/id/A/AN/ANDK/CPAN-2.16.tar.gz
tar -zxvf CPAN-2.16.tar.gz
sudo mkdir  /usr/share/perl5/CPAN/ -p
sudo cp ./CPAN-2.16/lib/CPAN/FirstTime.pm /usr/share/perl5/CPAN/FirstTime.pm

source


text:
Q: Is there a way to change command-line output before saving to a file? I'm writing a program that uses the "tracert" command to find traceroutes for IP addresses, which I'll then use to do some things with.
How I had planned to do this is, is by dumping the output for all IP addresses into a text file by appending with >>output.txt and then reading it in with Python or something and turn it into something usable.
My issue with this is that tracert also shows in its output some things that are of no use to me, such as the first line that says where it's tracing to and what the maximum number of hops is, or the last line that only says: "Trace complete".
The thing is that I'm going to be tracing 3500+ IP addresses, and that number is only going to grow, so that is a whole lot of text that I'm printing in a file that is absolutely useless.
That's why my question is: Is there any way that I can modify the output of the command before saving it, in a batch file?
The command I'm running:
tracert -h 30 -w 500 XX.XXX.XXX.XX >>cmd_output.txt

The output it gives:
Tracing route to XYZ.net
[XX.XXX.XXX.XX]
over a maximum of 30 hops:

  1    41 ms    18 ms     2 ms  text.net [XXX.XXX.XXX.X]
  2     2 ms     1 ms     1 ms  text.net [XX.XXX.XXX.XXX]
  3     1 ms     1 ms     1 ms  text.net [XX.XXX.XXX.XXX]
  4     5 ms     5 ms     5 ms  text.net [XXX.XX.XX.XXX]
  5     5 ms     5 ms     5 ms  text.net [XXX.XX.XX.X]
  6    25 ms    25 ms    25 ms  XYZ.net [XX.XXX.XXX.XX]

Trace complete.

A: Maybe the following helps, I believe you can you use it and adjust it to your own use: Batch - Parsing the output of Tracert

A: The exact formula to skip the N first lines from one command's output is:
for /f "skip=N tokens=*" %a in ('<command>') do @echo %a

In your case:
for /f "skip=4 tokens=*" %a in ('tracert -h 30 -w 500 XX.XXX.XXX.XX ') do @echo %a >> cmd_output.txt

A: Using your replies and some more searching, I have come up with this solution:
@echo off
rem token 1 is hop-number
rem token 6,7 or 8 may be IP, depending on whether 2 or less requests dont receive a response.
for /f "tokens=1,6,7,8 delims=* " %%a in ('tracert -d -h 30 -w 350 8.8.8.8^|findstr /bc:" " ') do (
  echo %%a, %%b, %%c, %%d
  )>>ips.txt
endlocal

This yields the following response:
1, <1, ms, 192.168.1.240
2, 1, ms, 195.114.237.65
3, 1, ms, 94.247.72.33
4, <1, ms, 82.150.154.129
5, 1, ms, 217.170.0.244
6, 2, ms, 193.239.117.142
7, 2, ms, 108.170.241.140
8, 2, ms, 216.239.41.49
9, 5, ms, 74.125.37.130
10, 209.85.243.253, ,
11, 5, ms, 108.170.237.135
12, , ,
13, 5, ms, 8.8.8.8

In each line, before the first comma is always the hop-number. Then the IP address may be after the first, second or third comma. Since tracert sends three requests per hop one, two or three of those requests can fail.
If a request fails, the result is "*", instead of "X ms" and because I'm delimiting with spaces, if I would always take the 8th token, it might not contain the IP address, or anything for that matter.
This code will always contain the IP address, but will still contain some superfluous data if fewer then two requests failed, because then token 6 and or 7 will contain some part of "X ms".
In the response, you'll see all requests were successful, except for hop 10, where two requests failed and hop 12, where three requests failed and thus tracert failed to return an IP address.
If anyone has any bright ideas on how to remove these last bits of superfluous data, it would be appreciated. Otherwise this is a perfectly workable output for me. So thanks for your help! :)

A: @echo off
setlocal enabledelayedexpansion
for /f "tokens=1,*" %%a in ('tracert -d -h 30 -w 350 8.8.8.8 ^|findstr /bc:" "') do (
  for %%c in (%%b) do set ip=%%c
  set ip=!ip:[=!
  set ip=!ip:]=!
  echo !ip!|findstr "[0-9]" >nul || set "ip=-"
  echo %%a, !ip!
)

the second for (%%c) gets the very last word of the line (which is either an IP address or an IP address in brackets or the last word of "Request timed out." (out. in English Windows versions). The rest of the lines is just to beautify the result (removing brackets, replacing anything that has no number (is no IP address) with a -
Maybe you want to replace the two echo ... lines with just:
  echo !ip!|findstr "[0-9]" >nul && echo %%a, !ip!

This wouldn't output lines without an IP address.
For the && and || thingy, see SS64
For the !variable! syntax see delayed expansion


text:
Q: MobX decorating a class causes function to throw TypeError I have two data classes (business logic that I didn't write), that I'm trying to use in a store. I have fixed issues in that store by decorating them. They are defined to be:
// data classes; // these would be in separate file.
class PayRate {
  /**
   * @param {number} storeId The store id of the pay rate. (-1 for all)
   * @param {number} empId The id of the employee. (-1 for all)
   * @param {number} taskId The id of the task. (-1 for all)
   * @param {Date} effectiveDate The date the payrate goes in effect.
   * @param {number} rate The rate of pay.
   */
  constructor(storeId, empId, taskId, effectiveDate, rate) {
    this.StoreId = storeId || -1;
    this.EmpId = empId || -1;
    this.TaskId = taskId || -1;
    this.EffectiveDate = effectiveDate ? new Date(effectiveDate) : new Date();
    this.Rate = rate || 0.00;
    this.OriginalObject = $.extend(true, {}, this);
  }

  /**
   * Gets a readable version of the effective date.
   * @returns {string} A -m/dd/yyyy representation of the effective date.
   */
  GetReadableDate() {
    return this.EffectiveDate.toLocaleDateString("en-US");
  }
  /**
   * Gets a one line description of the pay rate.
   * @returns {string} A string in the form of (date) - payrate.
   */
  GetDescription() {
    return `(${this.GetReadableDate()}) - $${this.Rate.toFixed(2)}`;
  }
  /**
   * Gets a one line description of the pay rate.
   * Does the exact same as GetDescription(), but is overload of Object.prototype.toString, which allows for stringification of Objects
   * @returns {string} A string in the form of (date) - payrate.
   */
  toString() {
    return `(${this.GetReadableDate()}) - $${this.Rate.toFixed(2)}`;
  }
  /**
   * Tells whether a pay rate was changed or not.
   * @returns {boolean} A boolean saying whether or not the pay rate was changed.
   */
  IsChanged() {
    if (this.EffectiveDate.getTime() !== this.OriginalObject.EffectiveDate.getTime()) {
      return true;
    }
    if (this.Rate != this.OriginalObject.Rate) {
      return true;
    }
    if (this._deleted) {
      return true;
    }
    return false;
  }
  /**
   * Reverts the changes back to the original.
   */
  RevertChanges() {
    $.extend(true, this, this.OriginalObject);
  }
}

mobx.decorate(PayRate, {
  StoreId : mobx.observable,
  EmpId : mobx.observable,
  TaskId : mobx.observable,
  EffectiveDate : mobx.observable,
  Rate : mobx.observable,
})

class TaskObject {
  /**
   * @param {Task} task The task that is being kept track of.
   * @param {PermissionLink[]} permissionLinks A list of permission links that are being kept track of.
   * @param {PayRate[]} payrates A list of pay rates that are being kept track of.
   */
  constructor(task, permissionLinks = [], payrates = []) {
    this.Model = $.extend(true, {}, task);
    this.Model.Type = 25;
    this.PermissionLinks = $.extend(true, [], permissionLinks);
    this.Payrates = $.extend(true, [], payrates);
    this.OriginalObject = $.extend(true, {}, this);
  }
  /**
   * Gives the dirty status of the task object.
   * @returns {boolean} Tells whether or not the TaskObject has been changed.
   */
  IsChanged() {
    if (this.Model.Id == -1) {
      return true;
    }
    if (this.Model.Name != this.OriginalObject.Model.Name) {
      return true;
    }
    if (this.Model.GroupName != this.OriginalObject.Model.GroupName) {
      return true;
    }
    if (this.Model.DescStr != this.OriginalObject.Model.DescStr) {
      return true;
    }
    if (this.Model.IsActive != this.OriginalObject.Model.IsActive) {
      return true;
    }
    if (this.PermissionLinks.length != this.OriginalObject.PermissionLinks.length) {
      return true;
    }
    for (let i = 0; i < this.PermissionLinks.length; i++) {
      const element = this.PermissionLinks[i];
      const compElement = this.OriginalObject.PermissionLinks[i];
      if (JSON.stringify(element) !== JSON.stringify(compElement)) {
        return true;
      }
    }
    for (let i = 0; i < this.Payrates.length; i++) {
      const payrate = this.Payrates[i];
      if (payrate.IsChanged()) {
        return true;
      }
    }
    return false
  }
  /**
   * Reverts the changes that are on the task object.
   * @returns {TaskObject} The TaskObject with its changes discarded.
   */
  RevertChanges() {
    this.Model = $.extend(true, {}, this.OriginalObject.Model);
    this.PermissionLinks = $.extend(true, [], this.OriginalObject.PermissionLinks);
    for (let i = 0; i < this.Payrates.length; i++) {
      this.Payrates[i].RevertChanges()
    }
    return this;
  }

  /**
   * This is here for debugging purposes (i.e. with data stores that use it) and may be overwritten with business logic at any time
   */
  toString() {
    return JSON.stringify(this, null, '\t')
  }
}

// marking all the properties of TaskObject observable
mobx.decorate(TaskObject, {
  Model : mobx.observable,
  PermissionLinks : mobx.observable,
  Payrates : mobx.observable,
  RevertChanges : mobx.action,
  IsChanged : mobx.computed
})

Now, doing new PayRate().IsChanged() works as expected, but new TaskObject.IsChanged() results in:
Uncaught TypeError: Cannot read property 'call' of undefined
    at e.computeValue (mobx.umd.min.js:1)
    at e.get (mobx.umd.min.js:1)
    at e.read (mobx.umd.min.js:1)
    at TaskObject.get (mobx.umd.min.js:1)
    at pen.js:163
e.computeValue @ mobx.umd.min.js:1
e.get @ mobx.umd.min.js:1
e.read @ mobx.umd.min.js:1
get @ mobx.umd.min.js:1
(anonymous) @ pen.js:163

Here is demo
Why is this happening and how can I fix it?

A: You declare IsChanged as a function but decorate it as a computed property, then call it as a function. If you want it to be a computed property, you'd need to:

*

*convert it to a getter: IsChanged() -> get IsChanged()

*call it without parenthesis: TaskObject.IsChanged


text:
Q: Providing new props to all react-router routes I have multiple routes and I want all of them to inherit props from my provider, the problem is that all these components that I want to receive the props have <Route> parents, and it doesn't let the props flow through:

<Layout>
<Route
    key={`other-${i}`}
    path={path}
    render={props => (
        <Component
            someProp={someProp}
            {...props}
        />
    )}
/>
... more routes ...
</Layout>

<Layout /> works fine here because it doesn't provide props, only restructure the layout, but I want another parent that passes props to <Component />. I can make it work by putting this provider as the immediate parent of <Component /> but the problem is I have multiple components and it would get clutterly to put it as a parent for every single case. So how do I add a provider that passes props to all components?


text:
Q: Side by side html containers I can't seem to get my home page adjacent to the navbar on the left side first column. I've created a home page which is under the navbar section but should be on the right of it. I've tried adding a container but that didn't work.  Any advise on how I can do that?  The output should be navbar on left side and content on the right side.

HOME PAGE
{% extends 'layout.html' %}

{% block body %}

Welcome To myStocks Page

This application is built on the Python Flask framework

{% endblock %}

LAYOUT
<!doctype html>

        <meta charset="utf-8">

        <title>Stocks</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"stylesheet"

        {% include 'includes/_dashboard.html' %}

{% block body %}{% endblock %}

A: You might be under the misapprehension that the order of the elements will determine whether they are displayed to the left or right. This is not always the case.
Also, Includes are bit tricky, because you don't really see the full code in one place. Either you must mentally imagine it, or you can temporarily stick the code all together, and then break it back apart (into includes) later on. That last method might be a good idea for you as you are building the page. It might take less time to build it, then divide it, than to troubleshoot as you go.
What I am saying is that this:
    {% include 'includes/_dashboard.html' %}

{% block body %}{% endblock %}

does not put the dashboard on the left. The css is what puts the dashboard on the left.
It looks like you are using bootstrap with your flask project, so perhaps you should review a few bootstrap tutorials on building a page with a left-side navigation dashboard - there are many to choose from, just google. Here's one.
My suggestion, though, is to build your flask/jinja template as a single template page, then break it up later. Or at least do the basic scaffolding first, then break it up as you fine-tune it.
Flexbox Flexbox Flexbox...
Bootstrap4 uses flexbox, which is amazing for layout. In fact, it is so important that the core difference between Bootstrap3 and Bootstrap4 was moving from floats to flexbox for layout. If you invest 30 mins into learning it, you will be so impressed that you will want to buy yourself a beer for having done so.
Here is a great tutorial on using flexbox. And here is a good flexbox cheat sheet.
CSSGrid
Just as flexbox comes along, so does CSS Grid - another amazing layout tool (but a bit more involved to learn - and subsequently also a bit more powerful). But you will also find CSS Grid to be useful to you. In fact, start here.

A: There are several ways to align your containers with CSS. (float, position, grid, flex, etc)
The easiest way prob will be to add float: left to both: your left menu container and your jumbotron.
Nevertheless you should consider to structure your DOM with special care thinking in responsiveness, and future features that will be added.


text:
Q: SAVING XML OUTPUT I have this xml output using php and now i want to save this output as .xml to my file, how do i do that? please help me.

<xml>
<data>
<value>abcd</value>
<color>000000</color>
<border>thin</border>
<fontstyle>11double</fontstyle>
<fontsize>22</fontsize>
<fontname>Adobe Fangsong Std R</fontname>
<fontcolor>000000</fontcolor>
<alignment>general</alignment>
</data>
<data>
<value>efgh</value>
<color>000000</color>
<border>thin</border>
<fontstyle>double</fontstyle>
<fontsize>11</fontsize>
<fontname>Calibri</fontname>
<fontcolor>000000</fontcolor>
<alignment>general</alignment>
</data>
</xml>

A: All you need is file_put_contents(). You can read about it here.
Alternatively, you may use the PHP file functions (fopen(), fwrite(), fclose()).
fopen
fwrite
fclose


text:
Q: preg_match_all doesn't find anything I'm trying to match the following string CouncilTax with preg_match_all() but I keep receiving NULL. I have tested it on this website. This is how I use the function:
preg_match_all('/(?<=href=\")(.*?\.(.*?))\\/', $description, $out)
Where description is the above string and $out is just an empty variable.
Thanks,
Nevo

A: You need 3 consecutives backslashes:
$description = 'CouncilTax';
preg_match_all('/(?<=href=\")(.*?\.(.*?))\\\/', $description, $out);
print_r($out);

output:
Array
(
    [0] => Array
        (
            [0] => \"http://localhost/innovare-kh/wp-content/uploads/2014/07/CouncilTax.pdf\
        )

    [1] => Array
        (
            [0] => \"http://localhost/innovare-kh/wp-content/uploads/2014/07/CouncilTax.pdf
        )

    [2] => Array
        (
            [0] => pdf
        )

)


text:
Q: In what scenarios does the I2C Master pull the SCL line low? I have a board which acts as the I2C master. There is only one master. It is connected to two slaves. One slave supports clock stretching while the other does not. Between a read or write transaction, the line is pulled low. Is it possible that the slave will not pull the line low?

A: Frome Wikipedia, Physical layer paragraph :

While SCL is low, the transmitter (initially the master) sets SDA to
  the desired value and (after a small delay to let the value propagate)
  lets SCL float high. The master then waits for SCL to actually go
  high; this will be delayed by the finite rise time of the SCL signal
  (the RC time constant of the pull-up resistor and the parasitic
  capacitance of the bus) and may be additionally delayed by a slave's
  clock stretching. Once SCL is high, the master waits a minimum time (4 μs for
  standard-speed I²C) to ensure that the receiver has seen the bit, then
  pulls it low again. This completes transmission of one bit.

So yes the master can pull the SCL line low. It's a normal end of transmission.


text:
Q: EC2, Webserver, and MySQL I am about to launch an iOS app that will be communicating with my custom REST API. Right now I am running a single EC2 t2.micro instance running an Apache web server with MySQLi. Before I go ahead and launch it for the public, I want to hear what proper steps should be taken regarding the following.

*

*Should I run two separate EC2 instances? One only for the web server and the other to handle only the database?

*How should I approach setting up the database? Should I still use MySQLi or should I start using Amazon's RDS?

*In relationship to number two, when the database and/or web server runs out of space, how is this issue handled so that it seamlessly adds space to allow the database/web server to continue growth? I also read something regarding auto-scale.

I will be expecting many requests per minute to my web server and want to take precaution.

A: The answer to these questions largely depends on the requirements of your application, your budget, and on what you decide to manage vs. what you'd prefer to allow AWS to manage. However, I'll answer these as best I can.
1) Yes. Separating the database from the web server (that is, 2 different EC2 instances) makes sense for a lot of reasons. This will allow you to tailor resources like memory, CPU, etc. to each layer of your application separately. You do not want your web and database competing for the same resources. Additionally, an issue that forces you to take down one (web or database) will not force you to also take down the other. If your database lives on one of the web servers and you need to perform maintenance, your app will effectively become offline, since down goes your database as you perform updates. Also, ideally you would protect your database server within a private subnet in your VPC. If you have the web and database on the same server, they will both be in a public subnet, since you're web will require access to an internet gateway.
2) Depends. If you want to maintain total control of the database server, than use an EC2 instance where you retain operating system control. If you want to take advantage of features like Multi-AZ for high availability or allowing AWS to manage things like updates for you, RDS can be a great option. Cost also plays a role. For things like read-replicas and Multi-AZ, you will pay more, but you are purchasing performance and high availability. Thus, depends on your requirements. You can find the features of RDS here: RDS Product Details
3) For anything running on an EC2 instance (database or web) or if you decide to use RDS, you may provision and attach additional storage volumes as necessary. The type of storage you select will depend on the performance requirements, your budget, and the kind of workload you expect your database to face. Amazon provides the storage options available to you as well as a section for adding more storage here: RDS Storage Options
If you are worried about too many requests overwhelming your EC2 t2.micro instance, consider creating an ELB load balancer and setting up an auto-scaling group which will allow you to expand your capacity as necessary while distributing traffic such that no one server gets overwhelmed.


text:
Q: python use lazy assignment when passing lists to methods I have a python class A and its child B. I make an object of class B passing some list-type arguments, which are appended in B and the result stored in class A. I would like to be able to change one of those initial arguments and see the change reflected without further ado. Let me explain with an example:
class A():
    def __init__(self,data):
        self.a=data

class B(A):
    def __init__(self,x,y):
        self.x=x
        self.y=y
        A.__init__(self,self.x+self.y)

    def change_x(self,x):
        self.x = x

Now, wen i run
test = B([1, 2], [3,4])
print(test.a)

I obviously get [1,2,3,4]. If I change part of the list as follows:
test.change_x([3,4])
print(test.a)

I would like to get [3,4,3,4], instead of course, I receive [1,2,3,4]. Of course test.a is only evaluated during instantiation.
I understand why this is not the case and I read about generators but don't manage to figure out how to implement this. I don't want to end up with an iterable that i can only iterate once.
Could anyone help me? A clean way to solve this?

A: Is there a reason to have the class A at all? You could create a property or method a that returns what you want within class B.
class B():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def change_x(self, x):
        self.x = x

    @property
    def a(self):
        return self.x + self.y

test = B([1, 2], [3, 4])
print(test.a)  # [1, 2, 3, 4]

test.change_x([3, 4])
print(test.a)  # [3, 4, 3, 4]

Small note: With this implementation, the change_x method shouldn't be necessary. It's generally more Pythonic to just access attributes directly (e.g. test.x = x) than to use getters and setters.

A: You need to implement it "manually". For example, like so:
class B(A):
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.spread_changes()

    def change_x(self,x):
        self.x = x
        self.spread_changes()

    def spread_changes(self):
        A.__init__(self,self.x+self.y)

A: I ended up storing all parts of self.a (in A) directly by slicing/indexing from it's inheriting classes. I added a method "B.update_crc(self)" as suggested by Israel Unterman to reevaluate certain parts of self.a in case of a modification.
Thanks, my first approach just wan't the right one  :)


text:
Q: Spectral theory for Fuchsian groups of the first kind There are tons of material on the spectral theory of $L^2(\Gamma\backslash G)$ for a lattice $\Gamma$ in $G=PSL_2({\mathbb R})$. There are also many papers on the case of $\Gamma$ being convex-cocompact. But what about the intermediary case of Fuchsian groups of the first kind, which are not lattices?
Let me give an example: Let $\Lambda$ be a cocompact, torsion-free lattice in $G$. Then $\Lambda$ is the fundamental group of the Riemann surface $\Lambda\backslash G/K$ with $K=PSO(2)$. The structure of those is known: There are generators $\lambda_1,\dots,\lambda_{2g}$ with only one relation:
$$
[\lambda_1,\lambda_2]\cdots [\lambda_{2g-1},\lambda_{2g}]=1.
$$
So there exists a surjective group homomorphism $\chi:\Lambda\to\mathbb Z$.
The kernel of $\chi$ would be the group I am interested in: $\Gamma=\ker(\chi)$.
So my question is: Is there an explicit description of the representation-theoretic spectrum of $L^2(\Gamma\backslash G)$?
Is there a known theory of Eisenstein series which provides analytic continuation and functional equation?


text:
Q: Invalid property exception in spring I am using spring in my application , When i am loading the springApplicationContext to get the beans i am getting the errors

Caused by:
  org.springframework.beans.InvalidPropertyException:
  Invalid property "abc"

Even though there is a property abc and the setter for that property in the bean.
This is a weird error i know , but i can't figure out where is the problem.
Any pointers will be helpful.
Thanks!
Pratik

A: Ensure that the property has both a public setter and getter. In case of an AnyObject property it should look like:
private AnyObject abc;
public AnyObject getAbc() { return abc; }
public void setAbc(AnyObject abc) { this.abc = abc; }

There is however one special case: in case of a boolean property it should look like:
private boolean abc;
public boolean isAbc() { return abc; }
public void setAbc(boolean abc) { this.abc = abc; }

Note the is prefix instead of get.

A: I remeber the similar question at Spring forums. It was found out that there was a setter signature like
public class MyClass {

    private Aggregated field;

    public MyClass setField(Aggregated field) {
        this.field = field;
    }
}

I.e. the setter's return type was not void.
Anyway, Spring uses standard Instrospector for processing class properties. Try it with your class and check if target property is found.


text:
Q: Datagridview shows column from each SQL Server table in different order I get a wrong datagridview rows order with this query
SELECT
    E.*,
    TA.Numero_Transfert,
    Ta.Code_Transfert,
    TA.Numero_Agent,
    TA.Montant_Transfert,
    D.*
FROM
    Expéditeur E
FULL JOIN
    Transfert_Argent TA ON (E.Cin_Expéditeur = TA.CIN_Expéditeur)
FULL JOIN
    Agent A ON (A.Numero_Agent = TA.Numero_Agent)
FULL JOIN
    Destinataire D ON (D.Cin_Destinataire = TA.Cin_Destinataire);


text:
Q: Передача параметров в функциях с переменным числом параметров #include <stdarg.h>

void myPrintF(const char *__format, ...)
{
    va_list arg;
    va_start (arg, __format);
    printf(__format, arg);
    va_end (arg);
}

int main(void)
{
    time_t t = time(NULL);
    struct tm* aTm = localtime(&t);
    myPrintF("Close log %04d/%02d/%02d %02d:%02d:%02d\n",aTm->tm_year+1900, aTm->tm_mon+1, aTm->tm_mday, aTm->tm_hour, aTm->tm_min, aTm->tm_sec);
    printf("Close log %04d/%02d/%02d %02d:%02d:%02d\n",aTm->tm_year+1900, aTm->tm_mon+1, aTm->tm_mday, aTm->tm_hour, aTm->tm_min, aTm->tm_sec);
    return 0;
}

Почему выводит это? Как исправить?
Close log 6422164/-10800/1567025724 6422152:1980360769:1904456
Close log 2019/08/28 20:55:24

A: Почему вы решили, что printf можно так вызывать? Специально для таких целей есть
vprintf(__format, arg);

A: Вместо этого
printf(__format, arg);

воспользуйтесь
vprintf(__format, arg);


text:
Q: Javascript replace with regular expression not working in IE 11 I'm having some javascript issues with some legacy code, since my company is attempting to upgrade to IE11 from IE8. I have a piece of javascript that finds all commas in a field and replaces it with a couple characters, it is as follows:
document.frm.txt_fieldValue[1].value =
document.frm.txt_fieldValue[1].value.replace(/,/gi, "$0");

In my code this is all on one line, however. This code works in IE8, Chrome, and Firefox. However, in IE9+, specifically IE11 (since this is what my company is upgrading to), this code doesn't replace any commas. I can get it to replace a single comma by using the following code:
document.frm.txt_fieldValue[1].value =
document.frm.txt_fieldValue[1].value.replace(",", "$0");

Because I replaced a single comma, I know my code is reached. But I have searched around and I have yet to find a solid answer. Does anyone else have this problem? If so, has anyone found a solution?
Thanks!

A: You need to replace it with "$$0", which after escaping will turn into a real $0. I doubt if this code ever worked properly, on any browser.

A: I recently fixed a bug that might help.
If your value that you were replacing was 0 -- as a value, not a string -- IE11 would only append the replacement string instead of actually replacing it.
Here's what I was working with:
buf = buf.replace( /%%TOTALAMOUNT%%/gim, "$" + parseFloat( g_UserPurchases[LCV].CurrencyValue.val() ).toFixed(2) );

This printed: "%%TOTALAMOUNT%%.00"
I fixed it by checking:
if( ( g_UserPurchases[LCV].CurrencyValue.val() == 0 ) || ( g_UserPurchases[LCV].CurrencyValue.val() === 0 ) ){
//IE fix: IE did not like the $ character and didn't replace if val = 0
buf = buf.replace( /%%TOTALAMOUNT%%/gim, "$0.00");    }

Please note: IE11 didn't replace the the dollar sign character, $. So, I used the character code instead:
$

Hope this helps!


text:
Q: opencart 3.0 probmem, the site don't send email in contac-us section Hi Currently I manage a site in OPENCART, I have the problem that: in the section about us: when I click send, the email is not sent. Below I show you the "view" part since my intention is to go from the front to the back, someone tell me where to continue?
           <form action="{{ action }} " method="post" enctype="multipart/form-data" class="form-horizontal">
            <fieldset>
                <legend>
{{ text_contact }}
</legend>

{{ comment }}

                  <input type="text" name="name" value="{{ name }}" id="input-name" class="form-control" placeholder="{{ entry_name }} *"/>
                  {% if error_name %}

{{ error_name }}

                  {% endif %}

                  <input type="text" name="email" value="{{ email }}" id="input-email" class="form-control" placeholder="{{ entry_email }} *" />
                  {% if error_email %}

{{ error_email }}

                  {% endif %}

                  <textarea name="enquiry" value="{{ entry_enquiry }}" rows="10" id="input-enquiry" placeholder="{{ entry_enquiry }} *" class="form-control">{{ enquiry }}</textarea>
                  {% if error_enquiry %}

{{ error_enquiry }}

                  {% endif %}

              {{ captcha }}
            </fieldset>

                <button class="btn btn-info" type="submit" onclick="return gtag_report_conversion('https://supertortillamachines.com/index.php?route=information/contact/success')">{{ button_submit }} </button>

          </form>

A: So assuming mail is working otherwise from your website, you need to start debugging the code. find out what controller function is being called by form action="{{ action }} " (it will be visible in the rendered page)  and relate to a directory/file/function name.
From there at the start of the function put in a echo "hello"; just to see if it is even getting that far. and then just start looking at the data passed to the function and the flow of the code to see where it bombs out.


text:
Q: Ctrl + v (Paste) in string or in text file I'm using selenium web driver, I want to copy html text from clip board and paste that in string or in any file.
Here is my code:
IWebElement element1 = driver.FindElement(By.XPath(".//[@id='textAreaforMarkup']"));
element1.Click();
element1.SendKeys(Keys.Control + "v");
String text = element1.Text;
Console.WriteLine("HTML Text:" + text );

But text is null. Is there any way to copy data from website and paste that in a file or in string.
Help will be highly appreciable.
Thanks

A: You can set the Clipboard content by doing this:
Clipboard.SetText(text);


text:
Q: Mock pandas read_csv using pytest I have a python function that takes a BigQuery bucket name & file path as inputs and does the following:

*

*Check if the bucket it exists

*Check if the file is in the bucket

*Read the file into a dataframe and return the dataframe

The function looks something like this:
def function_to_test(client, bucket_name, delimiter, full_path=None, header=None):
    try:
        bucket = client.get_bucket(bucket_name)
        assert bucket is not None
    except (gcp_exceptions.GoogleCloudError, AssertionError) as ex:
        raise AirflowFailException(f"Failed to access bucket: {bucket_name}") from ex

    try:
        blob = bucket.get_blob(full_path)
        assert blob is not None
        if blob.size == 0:
            print(f'File is empty')
            return None
        df = pd.read_csv(f"gs://{bucket_name}/{full_path}", sep=delimiter, dtype='str', header=header)
        return df
    except(gcp_exceptions.GoogleCloudError, AssertionError) as ex:
        raise AirflowFailException(f"Failed to retrieve blob from bucket: {bucket_name}") from ex

I am trying to write pytest tests for this function and so far I have the following:
def test_func(mocker, generic_df):
    bucket_name = 'test_bucket'
    full_path = 'test_path'
    mock_client = mocker.patch('google.cloud.storage.Client', autospec=True)
    mock_bucket = mock_client.get_bucket(bucket_name)
    actual_df =  function_to_test(client=mock_client,bucket_name=bucket_name, delimiter=',', full_path=full_path, header=0)

Currently, the above mocking of the bucket is sufficient to pass the bucket requirements in the function.
However, I am unable to figure out how to mock the read_csv functionality and as such, the dataframe creation is failing.
Is there a way I can mock this function so that the dataframe is mocked too?


text:
Q: gremlin_python query 'object is not callable' error when trying to filter I have some experience with using gremlin in the console but I'm fairly new to gremlin in python. I have found a query that does what I want it to do in the console but I get a 'GraphTraversal' object is not callable error when I try to convert it to gremlin python. The query merges two vertices with the same specified property into one containing the edges of both.
Here is the adapted query:
g.V().has('id', 12345) \
    .fold().filter(count(local).is_(gt(1))).unfold(). \
    sideEffect(properties().group("p").by(key).by(value())). \
    sideEffect(outE().group("o").by(label).by(project("p","iv").by(valueMap()).by(inV()).fold())). \
    sideEffect(inE().group("i").by(label).by(project("p","ov").by(valueMap()).by(outV()).fold())). \
    sideEffect(drop()). \
    cap("p","o","i").as_("poi"). \
    addV("User").as_("u"). \
    sideEffect(
        select("poi").select("p").unfold().as_("kv"). \
        select("u").property(select("kv").select(keys), select("kv").select(values))). \
      sideEffect(
        select("poi").select("o").unfold().as_("x").select(values). \
        unfold().addE(select("x").select(keys)).from_(select("u")).to(select("iv"))). \
    sideEffect(
        select("poi").select("i").unfold().as_("x").select(values). \
        unfold().addE(select("x").select(keys)).from_(select("ov")).to(select("u"))).iterate()

and this is the error I'm getting:
TypeError                                 Traceback (most recent call last)
<ipython-input-165-9ce00a27d167> in <module>
      1 g.V().has('id', 12345) \
----> 2     .fold().filter(count(local).is_(gt(1))).unfold(). \
      3     sideEffect(properties().group("p").by(key).by(value())). \
      4     sideEffect(outE().group("o").by(label).by(project("p","iv").by(valueMap()).by(inV()).fold())). \
      5     sideEffect(inE().group("i").by(label).by(project("p","ov").by(valueMap()).by(outV()).fold())). \

TypeError: 'GraphTraversal' object is not callable

I suspect it's an issue with my gremlin_python translation. Any help would be greatly appreciated.

A: When using Python, certain reserved words conflict with Gremlin steps and need to be suffixed with an underscore. Also certain things like gt are part of the P enum and I prefer to write them out in full. So for the line in question it becomes:
.fold().filter_(__.count(Scope.local).is_(P.gt(1))).unfold().


text:
Q: jqGrid Add Link Column Binded with Specific Function I have this ASP.Net Page with jqGrid, all what I want is to add a link column in the grid that when pressed, it does a JavaScript function, like open a jQuery Dialog in the Page...
I was able to change the first column to link coulmn using column formatter, but I wasn't able to make the link do a JavaScript function...
My Code:
colModel = [
        { name: 'SR', index: 'SR', width: 90, fixed: true, align: 'center', formatter: 'link', formatoptions: { baseLinkUrl: '#'} },
        { name: 'NextCallBackDate', index: 'NextCallBack', width: 100, fixed: true, align: 'left' }]

A: I've acomplished this in PHP but it should work any where. When you prepare the data, change  the column like this:
Instead of field='value' you can do field='value'
The function should look like this:
function foo (item){
alert ($(item).html());
}


text:
Q: Toggle Divs in a Form with Buttons - WIthout the Buttons Submitting the Form The title more-or-less describes my issue.
I can get the divs to toggle on button click...but then every button click submits the form. I've read that adding a 'type="button"' to the button alleviates that, but it doesn't.
I'm using this to toggle the divs:
function togglediv(id) {
    var div = document.getElementById(id);
    div.style.display = div.style.display == "none" ? "block" : "none";
}

And the buttons look like this:
<button type="button" onclick="togglediv('stocking')" class="fusion-button button-default button-large">Stocking/Non-Stocking</button>
<button type="button" onclick="togglediv('address')" class="fusion-button button-default button-large">Address</button>
<button type="button" onclick="togglediv('phone')" class="fusion-button button-default button-large">Phone Number</button>
<button type="button" onclick="togglediv('website')" class="fusion-button button-default button-large">Dealer Website</button>

Here's the whole thing: http://jsfiddle.net/crossbeats/owek6t54/

A: The code is working in stackoverflow snippet. Might me some issue with jsfiddle javascript import because If You add your function at the bottom of the HTML file in  tag then It'll work. Your code is correct.

function togglediv(id) {
      var div = document.getElementById("stocking");
      div.style.display = div.style.display == "none" ? "block" : "none";
  }
<form action="https://docs.google.com/forms/d/1J12Y6xfoiylpwkO53RgPK_Z7zZpwEp6gyuy4J2Oqk5A/formResponse" method="POST" id="ss-form" target="_self" onsubmit="submitted=true;">

Distributor

*

<select name="entry.670683565" id="entry_670683565" aria-label="Distributor" aria-required="true" required class="form-control"><option value=""></option>
<option value="EWI">EWI</option> <option value="GC Duke">GC Duke</option> <option value="KPM">KPM</option> <option value="OWI">OWI</option> <option value="PACE">PACE</option></select>

Dealer's Full Name

*

<input type="text" name="entry.777900997" value="" class="ss-q-short form-control" id="entry_777900997" dir="auto" aria-label="Dealer's Full Name  " aria-required="true" required="" title="">

Your Name

*

<input type="text" name="entry.991155156" value="" class="ss-q-short form-control" id="entry_991155156" dir="auto" aria-label="Your Name  " aria-required="true" required="" title="">

Your Contact Phone Number

*

<input type="text" name="entry.564013658" value="" class="ss-q-short form-control" id="entry_564013658" dir="auto" aria-label="Your Contact Phone Number  " aria-required="true" required="" title="">

Your Contact Email Address

*

<input type="text" name="entry.384036897" value="" class="ss-q-short form-control" id="entry_384036897" dir="auto" aria-label="Your Contact Email Address  " aria-required="true" required="" title="">

What Information Would You Like to Change?

<button type="button" onclick="togglediv('stocking')" class="fusion-button button-default button-large">Stocking/Non-Stocking</button>
<button type="button" onclick="togglediv('address')" class="fusion-button button-default button-large">Address</button>
<button type="button" onclick="togglediv('phone')" class="fusion-button button-default button-large">Phone Number</button>
<button type="button" onclick="togglediv('website')" class="fusion-button button-default button-large">Dealer Website</button>

Stocking or Non-Stocking

<select name="entry.425770693" id="entry_425770693" aria-label="Stocking or Non-Stocking" class="form-control"><option value=""></option>
<option value="Stocking">Stocking</option> <option value="Non-Stocking">Non-Stocking</option></select>

Street Address

<input type="text" name="entry.1539858681" value="" class="ss-q-short form-control" id="entry_1539858681" dir="auto" aria-label="Street Address  " title="">

City

<input type="text" name="entry.656801113" value="" class="ss-q-short form-control" id="entry_656801113" dir="auto" aria-label="City  " title="">

State

<select name="entry.2062628675" id="entry_2062628675" aria-label="State" class="form-control"><option value=""></option>
<option value="AL">AL</option> <option value="AK">AK</option> <option value="AZ">AZ</option> <option value="AR">AR</option> <option value="CA">CA</option> <option value="CO">CO</option> <option value="CT">CT</option> <option value="DE">DE</option> <option value="FL">FL</option> <option value="GA">GA</option> <option value="HI">HI</option> <option value="ID">ID</option> <option value="IL">IL</option> <option value="IN">IN</option> <option value="IA">IA</option> <option value="KS">KS</option> <option value="KY">KY</option> <option value="LA">LA</option> <option value="ME">ME</option> <option value="MD">MD</option> <option value="MA">MA</option> <option value="MI">MI</option> <option value="MN">MN</option> <option value="MS">MS</option> <option value="MO">MO</option> <option value="MT">MT</option> <option value="NE">NE</option> <option value="NV">NV</option> <option value="NH">NH</option> <option value="NJ">NJ</option> <option value="NM">NM</option> <option value="NY">NY</option> <option value="NC">NC</option> <option value="ND">ND</option> <option value="OH">OH</option> <option value="OK">OK</option> <option value="OR">OR</option> <option value="PA">PA</option> <option value="RI">RI</option> <option value="SC">SC</option> <option value="SD">SD</option> <option value="TN">TN</option> <option value="TX">TX</option> <option value="UT">UT</option> <option value="VT">VT</option> <option value="VA">VA</option> <option value="WA">WA</option> <option value="WV">WV</option> <option value="WI">WI</option> <option value="WY">WY</option></select>

Zip Code

<input type="text" name="entry.1350649558" value="" class="ss-q-short form-control" id="entry_1350649558" dir="auto" aria-label="Zip Code  " title="">

Phone Number

<input type="text" name="entry.295675520" value="" class="ss-q-short form-control" id="entry_295675520" dir="auto" aria-label="Phone Number  " title="">

Dealer Website

<input type="text" name="entry.1075621702" value="" class="ss-q-short form-control" id="entry_1075621702" dir="auto" aria-label="Dealer Website  " title="">

<input type="hidden" name="draftResponse" value="[,,"-2745162411652655215"]">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fbzx" value="-2745162411652655215">

<input type="submit" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action fusion-button button-default button-large" style="float:right;">
</form>