text:
Q: Why on earth does this regex pattern only return the last instance? I have the following string that I'm trying to perform regex on:
040A0000 02CCDAD0 F9401401
040A0000 02CCDAD4 F8410021
040A0000 02CCDAD8 B4000041
040A0000 02CCDADC 52800015
040A0000 02CCDAE0 2A1503E1
040A0000 02CCDAE4 17DA29B5

My goal is to retrieve the last block of 8 characters, regardless of how many come before it. I am using the following pattern:
^(([\d\w]+ ){1,})?([\d\w]+)$
Now, according to regex101, this pattern should work just fine: https://regex101.com/r/ZuWIPV/1
However, when running the following code:
    var reg = new Regex("^(([\\d\\w]+ ){1,})?([\\d\\w]+)$", RegexOptions.Multiline);
    if (reg.IsMatch(textBox1.Text))
    {
        var instructions = reg.Matches(textBox1.Text).Cast<Match>().Select(x => x.Groups[3].Value).ToArray();
        foreach (var instruction in instructions)
        {
            MessageBox.Show(instruction);
        }
    }

The only result I get is from the very last line:
17DA29B5
I was expecting to get all 6, like this:
F9401401
F8410021
B4000041
52800015
2A1503E1
17DA29B5

A: First of all, you do not need to use [\w\d] as \w also matches digits. Next, when you define a regex in C#, you should use verbatim string literals to avoid overescaping. Also, only use capturing groups when you need to save some performance.
The issue is that you forgot to match an optional CR char at the end of each line. See Multiline Mode MSDN regex reference

By default, $ matches only the end of the input string. If you specify the RegexOptions.Multiline option, it matches either the newline character (\n) or the end of the input string. It does not, however, match the carriage return/line feed character combination. To successfully match them, use the subexpression \r?$ instead of just $.

You can use
var reg = new Regex(@"^(?:\w+ )*(\w+)\r?$", RegexOptions.Multiline);

To support any whitespaces on a line, you can use
var reg = new Regex(@"^(?:\w+[\p{Zs}\t])*(\w+)\r?$", RegexOptions.Multiline);

where [\p{Zs}\t] matches any horizontal whitespace.
And if you just want to match the last 8 ASCII hex chars at the end of each line you can just use
var reg = new Regex(@"[a-fA-F0-9]{8}\r?$", RegexOptions.Multiline);

Note in .NET \w matches all Unicode letters, digits, connector punctuation and even diacritic marks, so it might not be the best bet in this case. Alas, .NET regex has no shorthand for hex chars, like %x in Lua, [[:xdigit:]] in POSIX BRE/ERE, \p{XDigit} in Java, etc.
Why does regex101.com show correct matches?
At regex101.com, all line breaks are LF only, but in C#, on Windows, line endings are mostly CRLF. However, $ in the multiline matches only before the LF char.
When you need to test out a .NET regex, it is not a good idea to use regex101.com to validate the pattern as this regex testing site does not support .NET regex syntax (and Linux line endings). You can use RegexStorm.net where line breaks are set to CRLF.

A: If you see the documentation about mulitline mode it has this:

By default, $ matches only the end of the input string. If you specify the RegexOptions.Multiline option, it matches either the newline character (\n) or the end of the input string. It does not, however, match the carriage return/line feed character combination. To successfully match them, use the subexpression \r?$ instead of just $.

Your textbox will have \r\n in for its newlines. This works as you'd expect on .net:
string Text = "040A0000 02CCDAD0 F9401401\n040A0000 02CCDAD4 F8410021\n040A0000 02CCDAD8 B4000041\n040A0000 02CCDADC 52800015\n040A0000 02CCDAE0 2A1503E1\n040A0000 02CCDAE4 17DA29B5\n";

//the regex can be simpler if you just want the last hex chars of a line
var reg = new Regex("([A-F0-9]{8})$", RegexOptions.Multiline);
var rr = reg.Matches(Text); //6 matches

I'd point out that if this data will have this regular presentation all the tine it doesn't even need a regex..
textbox.Lines.Select(line => line[^8..])

would also retrieve the last 8 chars from every line, though it wouldn't validate them for being hex (if that's important)


text:
Q: standard trailing zeros in jquery which support cents and string I use the code to add zero after my values and take help from internet and found this code
$(document).ready(function() {
     //var number = 258.20;
     var number = 2;
     var rounded = number.toFixed(2); // rounded = 258.20
     document.write(rounded);
});

and added to my project but later I figure out that this code is not working with cents, I checked this code with my test cases and found that it is not working properly. If I use value 0.99 its convert into 0.00 and when I use value 45 its working fine 45.00 but when I use extra cost is 0.99 cents its convert into NaN. I try to find every where but didn't get succeeds. So is there any way to find the numbers in value and check it, if it is number it should add zeros, if its cents it should work with cents value and if the value is with string it should work also with it.
I found the solution and here it is.
        function isAlphaNumeric(str) {
            var code, i, len;
            for (i = 0, len = str.length; i < len; i++) {
                code = str.charCodeAt(i);
                if (!(code > 47 && code < 58) && // numeric (0-9)
                    !(code > 64 && code < 91) && // upper alpha (A-Z)
                    !(code > 96 && code < 123)) { // lower alpha (a-z)
                    return false;
                }
            }
            return true;
        };

        //var testCases = "extra cost is 0.99 cents";
        //var testCases = 255;
        //var testCases = 0.36;
        //var testCases = 25;
        //var testCases = 1;
        //var testCases = 1000;
        //var testCases = 10000;
        //var testCases = 100000;
        //var testCases = 0.53789;
        var testCases = 0.43789;
        Number.prototype.formatMoney = function(c, d, t){
            var n = this,
            c = isNaN(c = Math.abs(c)) ? 2 : c,
            d = d == undefined ? "." : d,
            t = t == undefined ? "," : t,
            s = n < 0 ? "-" : "",
            i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
            return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
        };

        if(isAlphaNumeric(testCases)) {
            document.write((testCases).formatMoney(2, '.', ','));
        } else {
            document.write(testCases);

        }

A: The toFixed method might not always ensure the correct rounding of the conversion results.
For example, (0.947).toFixed(0) may produce either '0' or '1', depending on the browser; thus, in Internet Explorer 8 and older versions, (0.947).toFixed(0) produces '0' – while in IE9, Firefox or Google Chrome the same conversion produces '1'.
You can use Math.round in combination with toFixed to correct this:
x=0.947;    s0=(Math.round(x)).toFixed(0)           // '1'
x=0.0947;   s1=(Math.round(10*x)/10).toFixed(1)     // '0.1'
x=0.00947;  s2=(Math.round(100*x)/100).toFixed(2)   // '0.01'
x=0.000947; s3=(Math.round(1000*x)/1000).toFixed(3) // '0.001'

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get probability for an interval with continuous marginal probability function? Let's say, I have joint probability function as follows:
$ f(x,y) = 4xy $ for $ 0 \le x \le 1 $ and $ 0 \le y \le 1 $
I want to get the marginal probability distribution of the random variable $ X $ from the joint probability distribution. So I integrate out the other random variable $ Y $. Then I get
$ f_X(x) = \int_{0}^{1} 4xy dy = [2xy^2]_{0}^{1} = 2x $
How can I use the resulted probability distribution function to find a probability between an interval of the random variable $ X $? Do I need to integrate the resulted function for some specific probability density between an interval of the random variable $ X $?

A: Yes, for example, $$P(0<X<1)=\int_0^1 f(x)dx=\int_0^1 2x=1$$
as expected. Note that $f(x)=0$ when $x<0$ or $x>1$.


text:
Q: Python script that moves specific files between S3 buckets So I'm still a rookie when it comes to coding in Python, but I was wondering if someone could be so kind as to help me with a problem.
A client I work for uses the eDiscovery system Venio. They have a web, app,database, and linux server running off of EC2 instances in AWS.
Right now when customers upload docs to their server, they end up re downloading the content to another drive, causing extra work for themselves. There is also an issue of speed when it comes to serving up files on their system.
After setting up automated snapshots with a script in Lambda, I started thinking that storing their massive files in S3,behind CloudFront might be a better way to go.
Does anyone know if there is a way to make a Python script that looks for key words in a file(ex;"Use", "Discard"), and separates them into different buckets automatically?
Any advice would be immensely appreciated!
UPDATE:
So here is a script I started:
import boto3

# Creates S3 client
s3 = boto3.client('s3')

filename = 'file.txt'
bucket_name = 'responsive-bucket'

keyword_bucket = {
    'use': 'responsive-bucket',
    'discard': 'non-responsive-bucket',
}

Essentially what I want is when a client uploads a file through the web API, a python script triggers which looks for the keywords of Responsive or Non-Responsive. Once it recognizes those keys, it PUTS those files into the corresponding named buckets. The responsive files will stay in a standard s3 buckets and the non useful ones will go to a s3-IA bucket. After a set time, they are then lifecycle to Glacier.
Any help would be amazing!!!

A: If you can build a mapping of keywords => bucket names, you could use a dictionary. For example:
keyword_bucket = {
    'use': 'bucket_abc',
    'discard': 'bucket_xyz',
    'etc': 'bucket_whatever'
}

Then you open the file and search for your keywords. When a keyword matches, you use the dictionary above to find the correspondent bucket where the file should go.


text:
Q: My code keeps updating my already existing values in the dictionary despite being new values, how can the code be fixed? When I add a new pair of values for the dictionary in the form of variables (patientname : pinnumber), they replace the ones I've added before
menuoption = str(input("Option: "))
x = menuoption
while x != "EX":
if menuoption == "PR":
    print("Patient Registration [PR]")
    patientdict = {"VRogue Wan": 1234}

    patientname = str(input("Name: "))
    pinnumber = input("Pin Number: ")
    patientdict[patientname] = pinnumber

    menuoption = str(input("Option: "))
    x = menuoption

if menuoption == "PI":
    print("Patient Information [PI]")

    print(patientdict)

    menuoption = str(input("Option: "))
    x = menuoption

A: Initializing of dict should be out of loop.
menuoption = str(input("Option: "))
x = menuoption
patientdict = {"VRogue Wan": 1234} # It should be out of loop
while x != "EX":
    if menuoption == "PR":
    print("Patient Registration [PR]")

    ... Other code ....

A: Initialize the dictionary outside the loop. You can create an empty dict, and let the user add values inside the loop.
Also no need to ask for input("Option: ") in each if block, place it at the beginning of the loop.
patientdict = {} #empty dict

while True:
    menuoption = input("Option: ")

    if menuoption == "PR":
        print("Patient Registration [PR]")
        patientname = input("Name: ")
        pinnumber = input("Pin Number: ")
        patientdict[patientname] = pinnumber

    if menuoption == "PI":
        print("Patient Information [PI]")
        print(patientdict)

    if menuoption == 'EX':
        break #exit the loop

In python3, input returns always a string, no need to call str on it.


text:
Q: Центрирование картинки на canvas Имеется такой код:

<!DOCTYPE html>
<html>
    <head>
        <title>Canvas from scratch</title>
        <meta charset="utf-8">

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

        <script>
      function getRandomInt() {
              return Math.floor(Math.random() * (255 - 0)) + 0;
            }
         $(document).ready(function() {
       var coin = new Image();
                coin.src = 'coin.png';
                var canvas = document.getElementById("canvas");
                var ctx = canvas.getContext("2d");
    for (var i = 0; i < 10; i++) {
        var coordinates = 70*i;
                    ctx.fillStyle = "rgb("+getRandomInt()+", "+getRandomInt()+", "+getRandomInt()+")";
                    ctx.fillRect(coordinates, 0, 70, 70);
     ctx.font = "bold 30px Verdana,sans-serif";
     ctx.lineWidth = 1;
     ctx.textAlign = 'center';
                    ctx.strokeText("Н", 70*(i+.5), 50);
     ctx.drawImage(coin, 50*(i+.5), 50);
                }
            });
        </script>
    </head>

    <body>
        <canvas id="canvas" width="700" height="70">
            <!-- Insert fallback content here -->
        </canvas>
    </body>
</html>

Где coin.png  это картинка 16x16, и её надо центрировать по середине, т.е чтобы в каждом квадрате была эта картинка по середине прямо на букве H, пробовал делать ctx.textAlign = 'center'; но к картинке он не применяется.
P.s Ещё хотел бы спросить почему если нажать Ctrl+F5 картинки не вырисовываются, но если просто обновлять то все норм

A: Как я понимаю надо дождаться когда загрузиться картинка. И только после этого её отрисовывать. То есть придется вынести эту отрисовку из первого цикла.
Также отрисовка по центру картинки вполне подвергается общим принципам:
кординатаВнутреннейКартинкиПоX = ШиринаОберткиПоX / 2 - ширинаКартинки / 2;

т.к. координаты начинаются с левого верхнего угла, то в координате ШиринаОберткиПоX / 2 будет левая граница картинки. А чтоб она была по центру - надо её сместить влево. На сколько? Правильно - также наполовину.
зная это, получается:
 ctx.drawImage(coin, 70 * (i + .5) - (coin.width / 2), 5);

Итог:

function getRandomInt() {
  return Math.floor(Math.random() * (255 - 0)) + 0;
}

$(document).ready(function() {
  var coin = new Image();
  var rectCount = 10;
  coin.src = 'http://i.stack.imgur.com/Mnyl3.png';

  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  for (var i = 0; i < rectCount; i++) {
    var coordinates = 70 * i;
    ctx.fillStyle = "rgb(" + getRandomInt() + ", " + getRandomInt() + ", " + getRandomInt() + ")";
    ctx.fillRect(coordinates, 0, 70, 70);
    ctx.font = "bold 30px Verdana,sans-serif";
    ctx.lineWidth = 1;
    ctx.textAlign = 'center';
    ctx.strokeText("Н", 70 * (i + .5), 50);
  }

  coin.onload = function() {
    for (var i = 0; i < rectCount; i++) {
      ctx.drawImage(coin, 70 * (i + .5) - (coin.width / 2), 5);
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="700" height="70">
  <!-- Insert fallback content here -->
</canvas>


text:
Q: "The lights go out" meaning in this context A teacher burning with rage and a student filled with indignation had this conversation:

Teacher: Where have you been?
Student: Just went out to get my mother to the doctor.
Teacher: Oh! I see. But, no excuses! You're late.
Student: Sorry Sir. I won't repeat that.
Teacher: Come late and say sorry and you're gonna save yourself. Now, your ass will be taking rounds and rounds of the playground until the lights go out.

Could that possibly mean when someone dies or until the night or for quite a long time or when someone is panting or  what? I'm confused!

A: I can understand your confusion. You seem to be thinking of the expression knock someone's lights out which means "to hit someone until they are unconcious".
I believe the lights, in this case, refer to street lamps that light areas at night (this can serve as both a security measure and a safety measure). Sometimes, street lamps stay on all night, while some go out at a certain time, usually incredibly early in the morning (3 AM, for example) when citizens are mostly sleeping and are not outdoors.
The teacher specifically mentions the lights going out to convey to the student that they will be running around the playground for a long period of time (i.e. throughout the night until it is so late that the lights over the playground go out).


text:
Q: How to make a recursive solution return all possible solutions? For this recursive function, when you input a list such as [2,8,3,2,7,2,2,3,2,1,3,0], it will find a path from the first index to the index containing the value 0, but can only move through the list by index[i]+i or index[i]-i and cannot go past the bounds of the list or go to an index that has already been visited.
So, if you are at index[0] which equals 2, you can only move forward in the list by 2. Or, if you are at index[3], you can only move forward or backwards in the list by 2; so you can go to either index[1] or index[5].
For the list [2,8,3,2,7,2,2,3,2,1,3,0], I get a solution which is [0,2,5,7,4,11], but there are more solutions such as [0,2,5,3,1,9,10,7,4,11], and I am not sure how to get my function to continue searching for all the other ones.

A: Carry around a second list(of lists) containing all your solutions, eg
def findAllPaths(vector, position, solution, all_solutions):
    if position not in solution and position >= 0 and position < len(vector):
        solution = solution + [position]
        if vector[position] == 0:
            all_solutions.append(solution)
        else:
            stepsize = vector[position]
            findAllPaths(vector, position + stepsize, solution, all_solutions) #step forward
            findAllPaths(vector, position - stepsize, solution, all_solutions) #step back
    return all_solutions

def findPaths(vector):
    paths = findAllPaths(vector, 0, [], [])
    if paths:
        return paths
    else:
        print("No possible path")
        return 0

EDIT:
Each recursive call results in a new stack frame, which is a block of memory containing the function arguments and any local variables created during that call. Each call in turn makes two recursive calls, each with its own stack frame lying on top of the previous one. This precariously wide tower of stack frames is called a call stack, and traces the execution of a recursive function. Eventually, we either go out of bounds or reach the zero in our vector, at which point we return our solution. As you rightly note, the value of position in this stack frame is 11. When we hit the return statement, the return value is passed to the previous frame in the stack, and everything else in the current stack frame is discarded. In this way each stack frame, and hence each recursive call, maintains a different value for position that does not affect the value of position in the function that called it.
So how do we ensure we don't have duplicate solutions? Consider the candidate solutions after each recursive calls. An invocation of findAllPaths with a candidate solution of length n either terminates (if vector[position] == 0) or makes two recursive calls to findAllPaths, each with solutions of length n + 1. In this case, the last element of the two respective candidate solutions areposition + vector[position] or position - vector[position]. These are the identical iff vector[position] == 0], in which case we would already have terminated. Hence the two candidate solutions in our recursive calls are distinct, and the length of the candidate solution increases with each recursive call. Combined, these two facts mean we can never have identical paths in a solution.


text:
Q: simple Akka ssl encryption There are several questions on stackoverflow regarding Akka, SSL and certificate management to enable secure (encrypted) peer to peer communication between Akka actors.
The Akka documentation on remoting (http://doc.akka.io/docs/akka/current/scala/remoting.html)
 points readers to this resource as an example of how to Generate X.509 Certificates.
http://typesafehub.github.io/ssl-config/CertificateGeneration.html#generating-a-server-ca
Since the actors are running on internal servers, the Generation of a server CA for example.com (or really any DNS name) seems unrelated.
Most servers (for example EC2 instances running on Amazon Web Services) will be run in a VPC and the initial Akka remotes will be private IP addresses like
remote = "akka.tcp://sampleActorSystem@172.16.0.10:2553"
My understanding, is that it should be possible to create a self signed certificate and generate a trust store that all peers share.
As more Akka nodes are brought online, they should (I assume) be able to use the same self signed certificate and trust store used by all other peers.  I also assume, there is no need to trust all peers with an ever growing list of certificates, even if you don't have a CA, since the trust store would validate that certificate, and avoid man in the middle attacks.
The ideal solution, and hope - is that it possible to generate a single self signed certificate, without the CA steps, a single trust store file, and share it among any combination of Akka remotes / (both the client calling the remote and the remote, i.e. all peers)
There must be a simple to follow process to generate certificates for simple internal encryption and client authentication (just trust all peers the same)
Question:  can these all be the same file on every peer, which will ensure they are talking to trusted clients, and enable encryption?
key-store = "/example/path/to/mykeystore.jks"
trust-store = "/example/path/to/mytruststore.jks"

Question:  Are X.509 instructions linked above overkill - Is there a simple self signed / trust store approach without the CA steps?  Specifically for internal IP addresses only (no DNS) and without an ever increasing web of IP addresses in a cert, since servers could autoscale up and down.

A: First, I have to admit that I do not know Akka, but I can give you the guidelines of identification with X509 certificates in the SSL protocol.
akka server configuration require a SSL certificate bound to a hostname

You will need a server with a DNS hostname assigned, for hostname verification. In this example, we assume the hostname is example.com.

A SSL certificate can be bound to a DNS name or an IP (not usual). In order for the client verification to be correct, it must correspond to the IP / hostname of the server
AKKA requires a certificate for each server, issued by a common CA
CA
  - server1: server1.yourdomain.com (or IP1)
  - server2: server2.yourdomain.com  (or IP2)

To simplify server deployment, you can use a wildcard *.yourdomain.com
CA
  - server1: *.yourdomain.com
  - server2: *.yourdomain.com

On the client side you need to configure a truststore including the public key of the CA certificate in the JKS. The client will trust in any certificate issued by this CA.
In the schema you have described I think you do not need the keystore. It is needed when you also want to identify the client with a certificate. The SSL encrypted channel will be stablished in both cases.
If you do not have a domain name like yourdomain.com and you want to use internal IP, I suggest to issue a certificate for each server and bound it to the IP address.
Depending on how akka is verifying the server certificate, it would be possible to use a unique self-signed certificate for all servers. Akka probably relies trust configuration to JVM defaults. If you include a self-signed certificate in the truststore (not the CA), the ssl socket factory will trust connections presenting this certificate, even if it is expired or if the hostname of the server and the certificate will not match. I do not recomend it


text:
Q: Result of "rsync" I need to create a script that executes periodically (every 5 seconds) a rsync between two directories.
One requirement is that I need to write, with a timestamp, the copied files into a log file but I cannot find a way to get a result of the rsync copied files. Is there a way to know which files have been copied?

A: You can use the -v (--verbose) option of rsync to get which files are being copied.
To get specific output, rsync has the --info option.
For example, to get only the files that were supposed to be copied, successful/unseccessful both shown:
rsync --info=name /source /destination

To get only transfer stat:
rsync --info=stat /source /destination

You can use uppercase in the option value too (e.g --info=NAME) and append 2 after option value to increase verbosity, if possible (e.g --info=NAME2).
There are a lot of other possibilities too, check man rsync and especially rsync --info=help:
% rsync --info=help
Use OPT or OPT1 for level 1 output, OPT2 for level 2, etc.; OPT0 silences.

BACKUP     Mention files backed up
COPY       Mention files copied locally on the receiving side
DEL        Mention deletions on the receiving side
FLIST      Mention file-list receiving/sending (levels 1-2)
MISC       Mention miscellaneous information (levels 1-2)
MOUNT      Mention mounts that were found or skipped
NAME       Mention 1) updated file/dir names, 2) unchanged names
PROGRESS   Mention 1) per-file progress or 2) total transfer progress
REMOVE     Mention files removed on the sending side
SKIP       Mention files that are skipped due to options used
STATS      Mention statistics at end of run (levels 1-3)
SYMSAFE    Mention symlinks that are unsafe

ALL        Set all --info options (e.g. all4)
NONE       Silence all --info options (same as all0)
HELP       Output this help message

Options added for each increase in verbose level:
1) COPY,DEL,FLIST,MISC,NAME,STATS,SYMSAFE
2) BACKUP,MISC2,MOUNT,NAME2,REMOVE,SKIP

Example:
% rsync --info=name test.txt foobar:/spamegg/
test.txt

% rsync --info=stats test.txt foobar:/spamegg/
sent 86 bytes  received 41 bytes  254.00 bytes/sec
total size is 10  speedup is 0.08

A: Use the -v flag, in addition to whatever other flags you need.
From man rsync:

-v, --verbose
  This option increases the amount of information you are given during the transfer. By default, rsync works silently. A single -v will give you information about what files are being transferred and a brief summary at the end. Two -v options will give you information on what files are being skipped and slightly more information at the end....

A: In case some one ever needs it... After many tests I am going for something like:
#!/bin/bash
rm out.log
touch out.log
while :
do
rsync --log-file=out.log -a /tmp/test /tmp/backup
counter=`wc -l < out.log`
echo $counter
rm out.log
if [[ $counter -gt 2 ]]; then
rsync --log-file=out.log -a /tmp/test /tmp/backup
fi
sleep 5
done


text:
Q: csv import into django models My python csv import script creates an extra empty entry in the database model every time I load data. I have tried to work around various ways but I still get one empty entry plus the actual data am loading from the csv.Here is what my script is like. Please your help will be of great achievment.
class CsvUploadView(LoginRequiredMixin, FormView):
form_class = CsvAttendeeForm
template_name = 'attendee/upload_attendee_csv.html'
success_url = reverse_lazy('home')

def post(self, request, *args, **kwargs):

    form_class = self.get_form_class()
    form = self.get_form(form_class)
    file = request.FILES.get('file')
    if form.is_valid():
        if file:
            reader = csv.reader(file, delimiter=',')
            next(reader)
            attendee_instance = Attendee()
            Attendee.objects.bulk_create(
                [Attendee(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
                 for row in reader])

            attendee_instance.save()

        return self.form_valid(form)

    else:
        return self.form_invalid(form)

A: It looks like you are initializing and saving an empty instance in addition to the bulk_create
 # This line shouldn't be needed
 attendee_instance = Attendee()
 Attendee.objects.bulk_create(
      [Attendee(firstname=row[0],
           surname=row[1],
           email=row[2],
       )
       for row in reader])

# Nor should this line.
attendee_instance.save()

A: Your problem is with this (cropped) section:
attendee_instance = Attendee()

Attendee.objects.bulk_create(
                [Attendee(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )
attendee_instance.save()

With the first attendee_instance, you're creating a blank Attendee object.  You later save this blank object with attendee_instance.save().
The line in the middle - Attendee.objects.bulk_create... - you're passing in a single item list to bulk_create, so it creates the object (with data) there. You don't need both.
What you want is probably:
Attendee.objects.create(firstname=row[0],
                          surname=row[1],
                          email=row[2],
                          )

You don't need the bulk_create unless you're creating more than one object, you can just use straight-up create.  Similarly, you don't need to create the object by attendee_instance=Attendee() and then manually change the attributes, when you can do it all in one go as described above.
It's worth noting the caveats on the limitations of bulk create, particularly if you're not using Postgres, and also if you get to the point of using post_save and pre_save signals.  The create method does trigger those save signals, so just make sure that you use the most appropriate one for your use case


text:
Q: c# creating new unique instances of objects My question is how do I change the following code to create 10 different instances of objects instead of 10 of the same Object.
 List <OBJ> newList = new List<OBJ> ();
 for (int i = 0; i < 10; i++){
     OBJ newOBJ = new OBJ (i);
     newList.Add(newOBJ);
 }

Where the OBJ class is:
 class OBJ    {
    public static int numb;

    public OBJ(int i)
    {
        numb = i;
    }
}

A: That are 10 different objects. But since the number is static, they all have the same number.
So make it non-static if you want.
class OBJ    {
    public int numb;

    public OBJ(int i)
    {
        numb = i;
    }
}

If you want to count the number of instances, you can leave it as static.
class OBJ    {
    public static int num_instances;
    public int number;

    public OBJ(int i)
    {
        number = i;
        num_instances ++;
    }
}

A: Make numb an instance field instead of a class field. Remove the static:
public int numb;

When static all instances of OBJ use the same int named numb.

A: That is what your code is doing already. the static keyword on your numb member makes numb shared across all instances of OBJ.

A: I'm not sure that i understand your question but try remove the static keyword.

A: Anytime you use new, you get a new instance. The code seems ok. The only problem is that you should REMOVE static from public static int numb.
class OBJ    {
  public int numb;

  public OBJ(int i)
  {
      numb = i;
  }
}

A: You are creating new instances, but your only property is static which gets shared among all instances.

A: You should only remove the static keyword...take a look to this:
http://msdn.microsoft.com/en-us/library/98f28cdx(v=vs.100).aspx


text:
Q: VHDL TESTBENCH ERROR I have to write a testbench code for a block having two inputs which were "X" and "Y" with output "A". The behaviour of the block is addition of two input signals, added value to be stored in "A". Two inputs are 8 bit values and output has 9 bit width.
Here is my code for testbench but I am getting an error.. kindly help me out.
CODE:
library IEEE;
USE ieee.std_logic_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--USE ieee.numeric_std.ALL;

ENTITY intensity1_tb IS
END intensity1_tb;

ARCHITECTURE behavior OF intensity1_tb IS

    -- Component Declaration for the Unit Under Test (UUT)

    COMPONENT intensity1
    PORT(
         X : IN  std_logic_vector(7 downto 0);
         Y : IN  std_logic_vector(7 downto 0);
         A : OUT  std_logic_vector(8 downto 0)
        );
    END COMPONENT;

   --Inputs
   signal X : std_logic_vector(7 downto 0) := '00000000';
   signal Y : std_logic_vector(7 downto 0) := '00000000';

    --Outputs
   signal A : std_logic_vector(8 downto 0) := '000000000';

BEGIN

    -- Instantiate the Unit Under Test (UUT)
   uut: intensity1 PORT MAP (
          X => X,
          Y => Y,
          A => A
        );

   -- Clock process definitions

   -- Stimulus process
   stim_proc: process
   begin
      -- hold reset state for 100 ns.
      wait for 100 ns;

 X <= "00000000";
 Y <= "11111111";
 A <= "011111111";

         wait for 100 ns;

 X <= "00001111";
 Y <= "11110000";
 A <= "011111111";

         wait for 100 ns;

 X <= "00001100";
 Y <= "10011000";
 A <= "010100100";

         wait for 100 ns;

 X <= "01111000";
 Y <= "10001110";
 A <= "100000110";

      end process;

END;

A: These single quotes:
   --Inputs
   signal X : std_logic_vector(7 downto 0) := '00000000';
   signal Y : std_logic_vector(7 downto 0) := '00000000';

    --Outputs
   signal A : std_logic_vector(8 downto 0) := '000000000';

Should be double quotes.  After which your code analyzes. Without the entity/architecture for uut it's not possible to find further errors.


text:
Q: How to merge duplicated rows I have a data frame that looks like

Nicknames
Names

Fonse, Fons
Alfons

Fonse, Fonsi
Alfons

Gustel, Gustl, Guste,
August

Baldi
Balthasar

Hausl, Baldi
Balthasar

Flore, Flori
Florian

I would like to merge the duplicated rows to be :

Nicknames
Names

Fonse, Fons,Fonse, Fonsi
Alfons

Gustel, Gustl, Guste,
August

Baldi, Hausl, Baldi
Balthasar

Flore, Flori
Florian

I was able to creat a subset of the duplicate but I don't know how to combine them
nick2 <- subset(nick, any(duplicated(nick$Names)))

Here is the data as a csv file
https://github.com/Garybertrand/nick

A: This should solve your problem
library(data.table)
library(dplyr)

setDT(df)[, list(Nicknames = paste(Nicknames, collapse = ', ')),
          by = c('Names')] %>%
  select(Nicknames,Names)

A: You can also use base R.
aggregate(Nicknames ~ Names, unique(df), paste, collapse = ", ")

A: The short tidyverse solution would be like this:
library(tidyverse)

df %>%
  group_by(Names) %>%
  summarize(Nicknames = paste0(Nicknames, collapse = ", "))


text:
Q: Reading big .csv file MATLAB with commas I have a big csv file (6.5millions x 25) and trying to load it to Matlab. I already tried xlsread , csvread but can't get satisfying results. I read I can achieve it by using textscan.
My data looks this way:
date_time;writetime;F1;F2;F3;R1;h12;b12;h_main;
01.01.2016 0:00:01;504910801075;1;1;1;3,94;799;1515;3,877;
01.01.2016 0:00:02;504910802314;1;1;1;3,96;795;1516;3,857;

First row is a header. Others rows are data. All other rows are of the same format.
My code:
fileID = fopen('value1.csv','r');
formatSpec = '%s; \n';

formatSpec1 = '%s%f %f %f %f %f %f %f %f %f %f\n';
A1 = fscanf(fileID, formatSpec);

A2 = textscan(fileID, formatSpec1,'Delimiter',{';', ','});

I read header to A1 it's ok:
A1 =
date_time;writetime;F1;F2;F3;R1;h12;b12;h_main;

And read data to A2 too.
A2 =
    {1x1 cell}   [5.0491e+11]   [1]   [1]   [1]   [3]   [94]   [799]   [1515]   [3]   [877]

But how to read 3,94 values? Because it can be just 4 or 0,064 value in this column.
Hope at your help!

A: I would treat them as a string. The following works.
fileID = fopen('value1.csv','r');
formatSpec = '%s; \n';
A1 = fscanf(fileID, formatSpec);
formatSpec1 = '%s%f %f %f %f %s %f %f %s\n';
A2 = textscan(fileID, formatSpec1,'Delimiter',{';'});
A2{6} = str2double(strrep(A2{6},',','.'));
A2{end} = str2double(strrep(A2{end},',','.'));

{1x1 cell}    [5.0491e+11]    [1]    [1]    [1]    [3.94]    [799]    [1515]    [3.8770]


text:
Q: Не отображаются google fonts

@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.3.0');
  src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.3.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.3.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.3.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.3.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.3.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}
body {
  font-size: 14px;
}
h1,
h2,
h3,
h4,
h5,
h6,
p,
ul,
li,
span,
a {
  margin: 0;
  padding: 0;
}
ul {
  list-style: none;
}
ul a {
  text-transform: none;
}
ul a:hover {
  text-transform: none;
  text-decoration: none;
}
a {
  color: inherit;
}
a:hover {
  text-decoration: none;
  color: inherit;
}
.main-text {
  color: black;
  font-family: UnicaOne;
  text-transform: uppercase;
}
.delete-pad-mar {
  margin: 0;
  padding: 0;
}
.menumob {
  width: 123px;
  margin: 0 auto 55px;
  color: #fff;
}
.menumob__but {
  background: none;
  width: 25px;
  height: 15px;
  border: none;
  background-image: url('/img/menubtn.png');
  margin-right: 20px;
  outline: none;
}
.menumob__menu {
  font-family: UnicaOne;
  font-size: 15px;
  font-weight: 400;
  text-transform: uppercase;
}
.menumob__ul {
  position: absolute;
  width: 100%;
  background-color: #202020;
  padding-top: 120px;
  padding-bottom: 104px;
  opacity: 0.95;
  z-index: 40;
  display: none;
  flex-direction: column;
  align-items: center;
}
.menumob__ul > li {
  padding-top: 24px;
  padding-bottom: 24px;
  cursor: pointer;
  font-family: UnicaOne;
  font-size: 15px;
  font-weight: 400;
  text-transform: uppercase;
  color: white;
}
.menumob__ul > li ul {
  text-align: center;
  display: none;
}
.menumob__ul > li ul li {
  padding-top: 27px;
}
.menumob__ul > li ul li a {
  color: #6f6f6f;
}
.menumob_close {
  position: absolute;
  top: 45px;
  right: 37px;
  width: 14px;
  height: 14px;
  background: none;
  background-image: url('../img/menubtn_close.png');
  border: none;
  outline: none;
}
.selected__item {
  border-top: 1px solid #434343 ;
  border-bottom: 1px solid #434343 ;
}
.theme {
  background-color: #202020;
  padding: 30px 94px;
}
.theme__block {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.theme__about {
  color: #c3c3c3;
  font-family: 'Lato', sans-serif;
  font-size: 15px;
  font-weight: 300;
  line-height: 25px;
}
.theme__name {
  color: white;
  font-family: 'UnicaOne';
  font-size: 36px;
  font-weight: 400;
  line-height: 36px;
  text-transform: uppercase;
  border-top: 3px solid white;
  border-bottom: 3px solid white;
}
.social a {
  color: white;
  font-family: FontAwesome;
  font-size: 16px;
  font-weight: 400;
  line-height: 32px;
  margin-right: 27px;
}
.social a:last-child {
  margin-right: 6px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, maximum-scale=1"/>
    <title>Title</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css?family=Unica+One" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/owl.carousel.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/media.css">

        <button class="menumob_close"></button>

HOME

CATEGORIES

TRAVEL

LIFESTYLE

FOOD

CLOTHES

ABOUT ME

CONTACT

            <button class="menumob__but"></button>
            MENU

            Travel & Photo blog.

Mundial

Делаю все как в инструкции:
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">

Делал также через @import. Шрифты подгружаются, но не отображаются. В Диспетчере видно что элементу соответствует прописанный шрифт в css. В чем проблема?

A: Если через Link то импорт не нужен. А можно HTML и CSS файлик


text:
Q: Token Parsing Error .. encountered \' .. in Beanshell? I am trying to run the following Beanshell code--
assignee.toString()!=''

Here 'assignee' is a variable in Beanshell context.
But I am getting the following error--
Caused by: Sourced file: inline evaluation of: ``assignee.toString()!='';'' Token Parsing Error: Lexical error at line 1, column 23.  Encountered: "\'" (39), after : "\'": <at unknown location>

at bsh.Interpreter.eval(Unknown Source)
at bsh.Interpreter.eval(Unknown Source)
at bsh.Interpreter.eval(Unknown Source)
at org.webharvest.runtime.scripting.BeanShellScriptEngine.eval(BeanShellScriptEngine.java:104)

What am I doing wrong here? I want to check if the variable 'assignee' has a null value or not... What is the correct way of accomplishing this?

A: The issue is that 'c' is a character literal, but '' (a character literal for "no character"?) is invalid Java syntax. (Even if it did parse there would be a type error with String == char.)
Perhaps "" (an empty String) literal was meant instead?
Important Note: even if this doesn't have a Syntax Error one should generally not compare Strings with == (or !=) as the results can be unexpected.. There are plenty of questions on SO as to why and how to properly compare String objects in Java: e.g. see String.equals(..) and String.isEmpty().
Happy coding!

A: Compare it directly to null:
if(assignee.toString() != null)
{
   do.something();
}


text:
Q: What Javascript code is required to convert a lead to account I want my agents to be able to convert a lead to an account from the lead list view. I have created the custom button but need the appropriate code. I used what was suggested but get a message Missing ; Before startement
Can anyone help me correct this?
Thanks
Emerson

A: This is how i would have approached this solution
1) Create a global apex class
2) Define a static webservice method with logic to convert the lead
3) call the method from javascript
The apex class would look something like this
global class convertLead{
    WebService static void convertLeadtoAcc(string id){
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(id);
        LeadStatus convertStatus = [SELECT Id, MasterLabel
                                    FROM LeadStatus
                                    WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvertResult lcr = Database.convertLead(lc);
    }
}

Now use the javascript to call this method
{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
sforce.apex.execute("convertLead","convertLeadtoAcc", {id:"{!Lead.Id}"});
Ofcourse you might want to bulkify the methods to process multiple leads at a time. However the basic idea would be the same.
Hope this helps.

A: Looks like you'll have to combine 2 functionalities.
GETRECORDIDS to fetch ids of records for which checkbox was ticked in the listview. (Caveat: last time I had to use it it didn't work in iSafari).
It's unclear whether you want to use visualforce / apex webservice or would you rather stay within pure JS solution... Since you struggle with JS syntax error I'd recommend involving apex like in @Modem's answer. In future maintenance it's more likely that another developer will understand Apex but his JS skills might be not as good.
But - for the sake of completeness. As far as I know whole SOAP API is implemented (exposed?) in the AJAX toolkit. So the convertLead() call is available too.
Here's the example:
var account = new sforce.SObject("Account");
account.Name = "convert lead sample";
account.Phone = "2837484894";
result = sforce.connection.create([account]);
account.Id = result[0].id;

var lead = new sforce.SObject("Lead");
lead.Country = "US";
lead.Description = "This is a description";
lead.Email = "someone@somewhere.com";
lead.FirstName = "first";
lead.LastName = "last";
lead.Company = account.Name;
result = sforce.connection.create([lead]);
lead.Id = result[0].id;

var convert = new sforce.LeadConvert();
convert.accountId = account.Id;
convert.leadId = lead.Id;
convert.convertedStatus = "Qualified";

result = sforce.connection.convertLead([convert]);
if (result[0].getBoolean("success")) {
  log("lead converted " + result[0]);
} else {
  log("lead convert failed " + result[0]);
}


text:
Q: Argument 1 passed to Coinbase\Wallet\Exception\HttpException::exceptionClass() must be an instance of Psr\Http\Message\ResponseInterface, null given When i run the Coin Base Transactions offline it works, but when i put it online it fails.
Here is my code for the transaction.

    $configuration = Configuration::apiKey($apiKey, $apiSecret);
    $client = Client::create($configuration);

    $account = $client->getPrimaryAccount();

    $address = new Address([
        'name' => 'New Address19'
    ]);

    $add = $client->createAccountAddress($account, $address);
    $addressId = $client->getAccountAddresses($account);
    $addresses = $client->getAccountAddress($account, $addressId->getFirstId());
    echo "Your address is: ".json_encode($addresses->getAddress())."
";

ive googled but all in vain, the answers i get from here of updatind the certificate in the etc folder also not working. Someone help me

A: $configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);
$account = $client->getPrimaryAccount();

$address = new Address([
    'name' => 'New Address19'
]);

$add = $client->createAccountAddress($account, $address);
$addressId = $client->getAccountAddresses($account);
$addresses = $client->getAccountAddress($account, $addressId->getFirstId());
echo "Your address is: ".json_encode($addresses->getAddress())."
";

A: I had teh same problem. The solution for was to download the cacert.pem file from:
https://curl.se/docs/caextract.html
Copy it to the Coinbase API etc folder (same place where you will find ca-coinbase.crt).
Then edit src\COnfiguration.php to refer to this new file:
    public function __construct(Authentication $authentication)
    {
        $this->authentication = $authentication;
        $this->apiUrl = self::DEFAULT_API_URL;
        $this->apiVersion = self::DEFAULT_API_VERSION;
//      $this->caBundle = __DIR__.'/../etc/ca-coinbase.crt'; // Replaced with:
        $this->caBundle = __DIR__.'/../etc/cacert.pem';
    }


text:
Q: how to increase Oracle SQL database or web service performance? I got a task to increase Oracle SQL database or web service performance. The web service required billions of data from the Oracle SQL database. Web service needs to populate those billions of data for each startup. Those data is mostly read-only and very rarely need an update or write data.
It is a very old codebase. That is why the solution was done in a way that it loads all data in memory to increase the performance. That is why it is slowing down development. It is like the first launch takes 30+ minutes. If for some reason those in-memory cached data becomes corrupted, I have to reload data from the database. It means another 30+ minutes waiting.
My task is to update this process. I have the flexibility to change the SQL database to something else that could help to speed up this process. Do you have any suggestion? Thanks in advance!

A: You can try to use MySQL. From my knowledge, MySQL has no limitation for the size of the database. I've attached a comparison you can look at between MySQL and Oracle. Comparison


text:
Q: brew install python, but then: "python-2.7.6 already installed, it's just not linked" disclaimer: noob
OSX 10.8.5
When I installed python in bash I got this warning and error:
Warning: Could not link python. Unlinking...
Error: The 'brew link' step did not complete successfully
The formula built, but is not symlinked into /usr/local
You can try again using 'brew link python

So I went ahead and typed
brew link python

and got
Linking /usr/local/Cellar/python/2.7.6... Warning: Could not link python. Unlinking...

Error: Could not symlink file: /usr/local/Cellar/python/2.7.6/bin/smtpd2.py
Target /usr/local/bin/smtpd2.py already exists. You may need to delete it.
To force the link and overwrite all other conflicting files, do:

brew link --overwrite formula_name

Should I do it? What does is mean to link python in this context, let alone force-link it, and what's formula_name?
This question is similar but also different, so I'm afraid to try the top rated answer as it might just dig me deeper into the rabbit hole that I am stuck in right now.

A: It looks like you have installed Python using another method before. Don't be scared. Homebrew is engineered so it won't mess up your system like Mac Ports et al.
You can always do brew link --overwrite --dry-run python to see first what exactly will be overwritten,  without actually doing it.
If once you do this it look like it is only overwriting or deleting *.py scripts, then you should be even less scared.


text:
Q: Understanding node.js callbacks 2.0 I know this question has been asked 1000 times but so far I am not able to put it into the mental context that satisfies my understanding of it. I understand what callbacks are and why. I also understand that by the time a value is returned to the calling function, the program has moved on with its life.  Here are my files.
in file myModule.js
'use strict';
var fs = require('fs');

module.exports = {
    f: function(val, callback){
        var ext = val[3];
        var dir = val[2];
        fs.readdir(dir, function(err,path,files){
        var count = path.length;
        var files = [];
        for(var x = 0; x < count; x++){
            if(path[x].toString().split('.')[1]){
                if(path[x].toString().split('.')[1] == ext) files.push(path[x]);
                }
            }
        callback(files);

           });

       }

};

and server.js that is requiring myModule...
'use strict'

var fs = require('fs');
var myMod = require('./myModule');
var dMod = require('./dMod');
var val = process.argv;
var r = myMod.f(val, function(rtn, callback){
    if(rtn){
        for(r in rtn) console.log(rtn[r]);
        }

    });
// part where I say "Hey you must wait here until we get rtn because we need him!"
console.log(r)

Am I correct in my understanding that rtn is essentially trapped inside the callback and any future function that I want to execute that requires rtn will have to be nested (unless I use async) inside the callback, and so on?

A: Yes you are correct. The scope of rtn is within that callback. The only other way to pass the value without nesting is to call an external callback with the value. Example:
function myCallback(rtn) {
  // use `rtn` here
}

myMod.f(val, function(rtn, callback){
  if (rtn) {
    for(r in rtn) console.log(rtn[r]);
  }
  myCallback(rtn);
});


text:
Q: log4j2 how to disable "date:" lookup - log4j throws exception edit seems not to be possible at the moment filed an issue.

i am using log4j2 in my apache camel application. In camel file names can be configured this way "?fileName=${date:now:yyyyMMdd-HHmmss}ID.${id}.gz"
if i set log level to debug camel tries to log what it is doing but log4j seems to try to lookup/interpret the string with "date:" and throws an exception:
2014-11-24 11:29:19,218 ERROR Invalid date format: "now:yyyyMMdd-HHmmss", using default java.lang.IllegalArgumentExcepti
on: Illegal pattern character 'n'
        at java.text.SimpleDateFormat.compile(Unknown Source)
        at java.text.SimpleDateFormat.initialize(Unknown Source)
        at java.text.SimpleDateFormat.<init>(Unknown Source)
        at java.text.SimpleDateFormat.<init>(Unknown Source)
        at org.apache.logging.log4j.core.lookup.DateLookup.formatDate(DateLookup.java:60)
        at org.apache.logging.log4j.core.lookup.DateLookup.lookup(DateLookup.java:53)
        at org.apache.logging.log4j.core.lookup.Interpolator.lookup(Interpolator.java:144)
        at org.apache.logging.log4j.core.lookup.StrSubstitutor.resolveVariable(StrSubstitutor.java:1008)
        at org.apache.logging.log4j.core.lookup.StrSubstitutor.substitute(StrSubstitutor.java:926)
        at org.apache.logging.log4j.core.lookup.StrSubstitutor.substitute(StrSubstitutor.java:816)
        at org.apache.logging.log4j.core.lookup.StrSubstitutor.replace(StrSubstitutor.java:385)
        at org.apache.logging.log4j.core.pattern.MessagePatternConverter.format(MessagePatternConverter.java:71)
        at org.apache.logging.log4j.core.pattern.PatternFormatter.format(PatternFormatter.java:36)
        at org.apache.logging.log4j.core.layout.PatternLayout.toSerializable(PatternLayout.java:189)
        at org.apache.logging.log4j.core.layout.PatternLayout.toSerializable(PatternLayout.java:53)
        at org.apache.logging.log4j.core.layout.AbstractStringLayout.toByteArray(AbstractStringLayout.java:52)
        at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:
104)
        at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:97)
        at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:428)
        at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:407)
        at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:365)
        at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:112)
        at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:1347)
        at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:1312)
        at org.apache.logging.slf4j.Log4jLogger.debug(Log4jLogger.java:132)
        at org.apache.camel.util.IntrospectionSupport.setProperty(IntrospectionSupport.java:518)
        at org.apache.camel.util.IntrospectionSupport.setProperty(IntrospectionSupport.java:570)
        at org.apache.camel.util.IntrospectionSupport.setProperties(IntrospectionSupport.java:454)
        at org.apache.camel.util.EndpointHelper.setProperties(EndpointHelper.java:249)
        at org.apache.camel.impl.DefaultComponent.setProperties(DefaultComponent.java:272)
        at org.apache.camel.component.file.GenericFileComponent.createEndpoint(GenericFileComponent.java:67)
        at org.apache.camel.component.file.GenericFileComponent.createEndpoint(GenericFileComponent.java:37)
        at org.apache.camel.impl.DefaultComponent.createEndpoint(DefaultComponent.java:123)
        at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:514)
        at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:547)

Is there a way to turn off this "date:" lookup? Why does it try to interpret stuff coming from log at all? I think it should not be touched in any way?!
Edit, very easy to reproduce in test:
public class LogTest {

    private Logger log = LoggerFactory.getLogger(LogTest.class);

    @Test
    public void test() {
        log.info("${date:now:buhu}");

    }
}

It is crucial to us ${date:} - only "data:now" is working.
So this problem is completely independent from camel, but camel uses ${date:...} pattern for several things. Here is a simple route that reproduces the problem - the exception will be thrown on camel set up phase - no test code needed - logging level must be "debug"!:
public class LogTest extends CamelTestSupport{

    private Logger log = LoggerFactory.getLogger(LogTest.class);

    @Test
    public void test() {
        //log.info("${date:now:yyyyMMdd-HHmmss}");

    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {

            @Override
            public void configure() throws Exception {
                from("direct:a").to("file:./?fileName=${date:now:yyyyMMdd-HHmmss}ID.${id}.gz");
            }
        };
    }

}

A: This issue was fixed in 2.7 version of Log4j2.
The solution is to upgrade to that version (or higher) and add in the pattern attribute the option "{nolookups}" to %msg .
%msg{nolookups}

For example
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{1} %L %M %t - %msg{nolookups}%n%xEx%n" />

A: The problem can be avoided, if the simple-Expression is written as $simple{..} instead of ${..}. Then log4j2 won't use his Date-Lookup.
So, if you change your Route from:
from("direct:a").to("file:./?fileName=${date:now:yyyyMMdd-HHmmss}ID.${id}.gz");

to:
from("direct:a").to("file:./?fileName=$simple{date:now:yyyyMMdd-HHmmss}ID.${id}.gz");

it should work, even if you debug Camel.

A: To disable the date lookup locally, you can add a "$" in front of the expression:
    log.info("$${date:now:buhu}");

This will print ${date:now:buhu} instead of throwing an exception printing the stack trace.
As for how to avoid this using Camel, I'm not sure. The cleanest fix would probably be a log4j2 update to disable their DateLookup feature. A temporary fix is to disable DEBUG level logs from the org.apache.camel package:
 <loggers>
     <logger name="org.apache.camel" level="INFO" />
     <root level="debug">
        <appender-ref ref="Console" />
     </root>
 </loggers>

It's not ideal, but we can increase the log level if we ever need to debug Camel context creation since the log statements are not necessary for general everyday development.

A: The correct solution is now to upgrade the log4j-core library to 2.15.0 or above. At time of writing, the latest and current recommended version is 2.16.0.
The variable substitutions happening in logged messages here are symptoms of the same feature exploited in CVE-2021-44228, aka Log4Shell.
The feature is disabled by default in 2.15.0 and removed in 2.16.0.
It's not news to anyone by now, but it's really important to take steps to disable this feature, as a security measure, even if not using Apache Camel or encountering the issue as described.
As an aside, I found this question when searching for early warning signs of the Log4Shell vulnerability. I've quoted it in my write-up.


text:
Q: How to download .exe file from web and run it with some script? I need to create some script (maybe .bat/.vbs or something else) that will download and open the file on double-click.
How can I do this?
Example:
I double-click on file (run.bat) and it goes to the link:
http://download.teamviewer.com/download/TeamViewer_Setup_en.exe
download and install this file.
I've tried something like this:
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.Open "GET", "http://download.teamviewer.com/download/TeamViewer_Setup_en.exe", 0
oXMLHTTP.Send
Set oADOStream = CreateObject("ADODB" & ".Stream")
oADOStream.Mode = 3
oADOStream.Type = 1
oADOStream.Open
oADOStream.Write oXMLHTTP.responseBody
oADOStream.SaveToFile "C:\TeamViewer_Setup_en.exe", 2
dim path, WshShell
path = "C:\"
set WshShell = WScript.CreateObject("Wscript.Shell")
WshShell.Run path & "TeamViewer_Setup_en.exe", ,true

But it didn't work.

A: EDIT : How can I download a file with batch file without using any external tools?
More detailed answer of how files can be downloaded from internet in windows.
Here are two ways.The first uses bitsadmin.exe and the second hybrid jscript.net/bat (should be saved as .bat).The .net way is faster according to my tests , but creates a small .exe file that is called.And the second is a "pure" batch script.
  @echo off
    setlocal

    call :download "http://download.teamviewer.com/download/TeamViewer_Setup_en.exe" teamv.exe
    teamv.exe
    exit /b %errorlevel%
    :download

    if "%2" equ "" (
        call :help
        exit /b 5
    )

    if "%1" equ "" (
        call :help
        exit /b 6
    )
    set url=%~1
    set file=%~2
    rem ----
    if "%~3" NEQ "" (
        set /A timeout=%~3
    ) else (
        set timeout=5
    )

    bitsadmin /cancel download >nul
    bitsadmin /create /download download >nul
    call bitsadmin /addfile download "%url%" "%CD%\%file%" >nul
    bitsadmin /resume download >nul
    bitsadmin /setproxysettings download AUTODETECT >nul

    set /a attempts=0
    :repeat
    set /a attempts +=1
    if "%attempts%" EQU "10" (
        echo TIMED OUT
        endlocal
        exit /b 1
    )
    bitsadmin /info download /verbose | find  "STATE: ERROR"  >nul 2>&1 && endlocal &&  bitsadmin /cancel download && echo SOME KIND OF ERROR && exit /b 2
    bitsadmin /info download /verbose | find  "STATE: SUSPENDED" >nul 2>&1 && endlocal &&  bitsadmin /cancel download &&echo FILE WAS NOT ADDED && exit /b 3
    bitsadmin /info download /verbose | find  "STATE: TRANSIENT_ERROR" >nul 2>&1 && endlocal &&  bitsadmin /cancel download &&echo TRANSIENT ERROR && exit /b 4
    bitsadmin /info download /verbose | find  "STATE: TRANSFERRED" >nul 2>&1 && goto :finishing

    w32tm /stripchart /computer:localhost /period:1 /dataonly /samples:%timeout%  >nul 2>&1
    goto :repeat
    :finishing
    bitsadmin /complete download >nul
    echo download finished
    endlocal
    goto :eof

    :help
    echo %~n0 url file [timeout]
    echo.
    echo  url - the source for download
    echo  file - file name in local directory where the file will be stored
    echo  timeout - number in seconds between each check if download is complete (attempts are 10)
    echo.
    goto :eof

OR
@if (@X)==(@Y) @end /****** jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist simpledownloader.exe goto :skip_compilation

set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop

call %jsc% /nologo /out:"simpledownloader.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

:: download the file

::
::::::::::
:: simpledownloader.exe "%%~1" "%%~2"

simpledownloader.exe  "http://download.teamviewer.com/download/TeamViewer_Setup_en.exe" teamv2.exe
teamv.exe

:: del /q simpledownloader.exe
::
::::::::
::

exit /b 0

****** end of jscript comment ******/

import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var webClient:System.Net.WebClient = new System.Net.WebClient();
print("Downloading " + arguments[1] + " to " + arguments[2]);
try {
    webClient.DownloadFile(arguments[1], arguments[2]);
} catch (e) {

        Console.BackgroundColor = ConsoleColor.Green;
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("\n\nProblem with downloading " + arguments[1] + " to " + arguments[2] + "Check if the internet address is valid");
        Console.ResetColor();
        Environment.Exit(5);
}


text:
Q: Rails app: best way to only have admin user, no other user I am trying to make a Rails app/site for my ownself where I can put up some info and some text. I was wondering how can I make an admin user (myself) in it without having a provision for any other user. I basically will never require more than one user and all other model data will belong to this one (admin) user.
The options I am thinking of:

*

*Have a user model, with just one entry. Check if any user is logged in and show the admin utils.

*Use a gem like can-can/devise? Is it an overkill?

*Have a very obscure URL where I can carry out admin tasks (sounds lame but easiest!)

A: Would basic auth work for you?  Here's the rails cast on it...
http://railscasts.com/episodes/82-http-basic-authentication

A: "3." is not the safest option.
"1." it might take you some extra time (Michael Hartl's tutorial might give you some ideas).
"2." is a bit of an overkill. You don't need CanCan, Devise alone will do, as long as you don't define routes for signing up and you don't put any link on your views for logging in.

A: I would go for the first option. This way you have a security layer without having to create a lot of code.

A: The first option seems nice... But I would go with the second since you will still need Authentication on your #1 and if you wish to add future features for other users you will be OK with CanCan + Devise.
Also they're pretty simple so I don't think it will give you that much trouble

A: You are going to need some sort of authorization.
I recommend 3 options:

*

*Build it your self

*Use devise <- my goto

*Use sorcery

Once your user model is created, then generate a migration called admin and set it as a boolean.
Then in your application.html.erb file, before the yeild call, create an if statement:
<% if current_user.admin? %>
<%= yield %>
<% else %>
You have no access
<% end %>

A: https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role
I think this explains it step by step! Good luck


text:
Q: Convert date and time to GMT format I have individual calendar and time pickers. I want to combine both and convert to GMT time.
var time = timepicker.Time; //This is in 24hour format, but needs to store in AM,PM format
var date = calendar.SelectedDate;
string add_date_time = date+ " " +time;
DateTime gmt = add_date_time.ToUnviersalTime();

I get the error as

"cannot convert string to System.DateTime"

EDIT:
this is xml code for calendar and timepicker.
 <controls:Calendar  x:Name="calendar"/>
 <TimePicker x:Name="time_picker" Format = "T"/>

After converting to gmt, I want to store in DB.

A: Since calendar.SelectedDate is a DateTime? and timepicker.Time is a TimeSpan, the following code should work:
DateTime gmt = (calendar.SelectedDate.Value + timepicker.Time).ToUniversalTime();

You might want to check calendar.SelectedDate.HasValue is true before running this code, in case no date is selected.
You can then use this DateTime value with your database access code.


text:
Q: CC and CXX unchanged when using sudo This may be similar or even a duplicate of this question but when I export the CC and CXX flags on my Mac OSX, anything that I try to compile only uses the c and c++ compilers specified by the export IF I do not use sudo. sudo'ing overwrites these flags to use the default clang compiler.
This may not be a problem except in cases when I need to use openmp or when I do not have root access. I tried to search for why this happens but came up empty. Is there a reason why sudo overwrites these variables?
Thank you.


text:
Q: SwiftUI List: swipe to delete strange behavior In my app I have a list (populated with data coming from CoreData).
If I perform a "complete" swipe to delete everything works fine, the item is deleted and the change is reflected in the CoreData DB.
If a do a "partial" swipe (left to right) till the delete buttons appears, and then I click on the button, nothing happens, no errors appears in console.
I really do not know which part of code shall I post here, no idea.
This is basically a standard iOS function.
Thanks

A: Here some code (the body)
var body: some View {
    VStack {
        List {
            if products.count > 0 {
                ForEach(products.filter({ "\($0)".lowercased().contains(searchText.lowercased()) || searchText.isEmpty }), id: \.self ) { prd in
                    HStack {

                            Text(prd.name ?? NSLocalizedString("unknown", comment: "text to be displayed when no name is found"))
                                .font(.headline)
                        Spacer()
                    }

                }
                .onDelete(perform: deleteItems)
            }
        .listStyle(GroupedListStyle())
        .navigationBarTitle("Products")
        .navigationBarItems(
                    trailing:
                        Button(action: {
                            self.showingAddItem = true
                        }) {
                            Image(systemName: "plus")
                        }
        )               .sheet(isPresented: $showingAddItem, content: {
            AddView()
                .environment(\.managedObjectContext, viewContext)
        })
    }
}

and here the delete function
private func deleteItems(at offsets: IndexSet) {
    print("delete")
    withAnimation {
        offsets.map { products[$0] }.forEach(viewContext.delete)
        do {
            try viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

If I do a whole swipe to delete, everything fine, if I do a partial one and the tap on delete, no delete is performed; the delete function is even not called (there is no print in the console)


text:
Q: How to register mysql db from my web host in Netbeans IDE I have built a desktop application and I used jdbc (localhost) in order to test it. Now I want to built a applet, that's why I need to get connection to mysql database which I created on my web host by using phpMyAdmin in NetBeans.  I have found a way actually, I click "Services" and rightclick "Database" then click "Register Mysql Server..". I know db username and password but I don't know what to write in "Server Host Name" and "Port". So if it can be done in this way how I find "Server Host Name" and "Port" if not how can I do it ?

A: ServerHostName could be a name or also an IP address. Port for mysql is normally 3306. Maybe this information is enough, but sometimes webHost manager can change this access for security reasons, in this case you must contact your provider

A:
The host is the server host name.


text:
Q: Is there a way to find a list of all available Python Modules? I'm familiar with https://docs.python.org/3/library/
But is there a built-in function in Python that allows you to view this list or a large list of available external modules you can use?

A: If you want a list of installed python modules:
import sys
print(sys.modules)


text:
Q: Why is my PHP not validating? I am trying to make it so that if a person inputs the wrong postal code format or leaves the input null it will give an error. I am trying to figure out why it isn't working. Please help!
Postal Code

    <input type="text" id="postal_code" name="postal_code" value="<?php if($_POST['postal_code'] == null){  echo '';}else{echo $_POST['postal_code'];}?>"/>

    <?php
        if(isset($_POST['send_bulkform'])  && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']) || isset($_POST['send_studentform']) && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']))
        {
            echo "Required, ex. A1A 1A1.";
        }
        elseif(isset($_POST['send_bulkform'])  && $_POST['postalcode'] == null || isset($_POST['send_studentform']) && $_POST['postalcode'] == null)
        {
            echo "Required, ex. A1A 1A1.";
        }
    ?>

A: The problem is with this line:
if(isset($_POST['send_bulkform'])  && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']) || isset($_POST['send_studentform']) && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']))

1 - preg_match returns 1 for match or 0 for no match. So your test:
$_POST['postalcode'] != preg_match(...)

makes no sense and will most of the time be "true".
Just use:
 if(preg_match(...))

2 - Regexp inside preg_match is malformed. Replace:
preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code'])

with:
preg_match("/[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]/",$_POST['postal_code'])

A: Your regex is incorrect, and your PHP usage is incorrect. In PHP regexs need delimiters.
A backslash in a PCRE regex escapes the next character. I would use:
[A-Z]\d[A-Z] \d[A-Z]\d

and in PHP (add anchors so the whole string has to match):
preg_match('/^[A-Z]\d[A-Z] \d[A-Z]\d$/', $string);

If the case is optional add either the i modifier after the delimiter:
preg_match('/^[A-Z]\d[A-Z] \d[A-Z]\d$/i', $string);

or add the lowercase character range as well:
preg_match('/^[A-Za-z]\d[A-Za-z] \d[A-Za-z]\d$/', $string);

Regex Demo: https://regex101.com/r/cG9sG9/1
PHP Demo: https://eval.in/594444 (the 1 is true, for a match)
If the whitespace between the first grouping and second can vary use \h and either the * quantifier or the + quantifier. The * makes it not required (zero or more occurrences).


text:
Q: How to convert Char into Strings in JavaScript? I'm using the split(' ') method in JavaScript to spilt the word for whitespaces.
For example:
I have text like:
var str ="Hello this is testing"

After I call
str.split(' ')

Now I will get Hello this is tesing as output and when I do this
str[2]

I get "l", but I want to get "testing" word (as per array index). How to convert str to array, so that if I put
str[2] //It should be testing.

A: When you do split it actually returns a value.
var foo = str.split(' ');
foo[2] == 'is' // true
foo[3] == 'testing' // true
str[2] == 'l' // because this is the old str which never got changed.

A: var a = str.split(" ");  // split() returns an array, it does not modify str
a[2];  //  returns "is";
a[3];  //  returns "testing";

A: .split() is returning your array, it doesn't change the value of your existing variable
example...
var str = "Hello this is testing";

var str_array = str.split(' ');

document.write(str_array[3]); //will give you your expected result.

A: Strings are not mutable, split[docs] returns an array. You have to assign the return value to a variable. E.g.:
> var str ="Hello this is testing";
  undefined
> str = str.split(' ');
  ["Hello", "this", "is", "testing"]
> str[3]
  "testing"

A: Writing str.split(" ") does not modify str.
Rather, it returns a new array containing the words.
You can write
var words = str.split(" ");
var aWord = words[1];

A: I made this html page and it reports the following:
function getStrs()
{
   var str = "Hello this is testing";
   var array = str.split(' ');
   for(var i=0; i < 4; i ++)
      alert(array[i]);
}

It reported Hello ... this ... is ... testing


text:
Q: GrantPermissionRule leads to PermissionException I've tried today the new android testing support lib. I need the write external storage permission for my tests so I've created the following test with the new GrantPermissionRule.
ExternalDirTest.java
    @Rule
    public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE);

    @Test
    public void test() throws IOException {
        Application.getApplication().createDir();
    }

Application.java
    public void createDir() throws IOException {
        new File(Environment.getExternalStorageDirectory() + "/test").createNewFile();
    }

Officially I get the permission (visible in the app settings). Nevertheless I get the following exception:
java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively0(Native Method)
at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
at java.io.File.createNewFile(File.java:948)
at test.app.directory.Application.createDir(EarApplication.java:253)
at test.app.directory.ExternalDirTest.test(ExternalDirTest.java:24)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at android.support.test.rule.GrantPermissionRule$RequestPermissionStatement.evaluate(GrantPermissionRule.java:109)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:58)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:369)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1932)

If I test the code manual it works perfectly.
Has someone facing the same problem or is it maybe a bug in the library itself?

A: Should now be fixed in version 1.0.2-alpha2
See https://issuetracker.google.com/issues/64389280


text:
Q: jpeg error #53 loading Stream from Datasnap I have a datasnap server with a servermethod to load a stream, im getting jpeg error #53, my goal is get a thumbnail size, im getting the stream from BLOB fiel, load into a Bitmap object, then a create a thumbnail and convert that thumbnail  to a stream back and send to the client
Error after loading the stream
I'm using
XE7, MSSQL, VLC Datasnap Server
Server Side
function TDSServerMethods.GetImage(proid, Width, Height:   Integer;  out ImgStream: TStream): Boolean;
var
  Bitmap,Bitmap2: FMX.Graphics.TBitMap;
  scale: Single;
  T:TStream;
  stream: TStream;
 begin
  Result := False;
  ImgStream := nil;
  WITH SPPROC  do
   begin
           close;
           ProcedureName := 'XXXXXX';
           Parameters.Clear ;
           Parameters.CreateParameter('@ID',     ftInteger,pdInput, 0,proid );
           Open;
          Result := recordcount > 0;

   end;

    try

      T :=   SPPROC.CreateBlobStream(SPPROC.FieldByName('file'),TBlobStreamMode.bmRead);
      T.Seek( 0, TSeekOrigin.soBeginning );
      T.Position := 0;

       Bitmap := FMX.Graphics.TBitMap.Create;
       Bitmap.LoadFromStream( T   );

       scale := RectF(0, 0, Bitmap.Width, Bitmap.Height).Fit(RectF(0, 0, 200, 200));
       Bitmap2 :=  Bitmap.CreateThumbnail(Round(Bitmap.Width / scale), Round(Bitmap.Height / scale));

      stream := TMemoryStream.Create;

     stream.Position := 0;
     Bitmap2.SaveToStream(stream);
     stream.Seek( 0, TSeekOrigin.soBeginning );
     stream.Position := 0;

     ImgStream :=  stream

    except
      Exit(False);
    end;

end;

Client Side
procedure TFrmMain.Button3Click(Sender: TObject);
var
   AImageStream: TStream;
   jp: TJPEGImage;

begin

    if ( DSServerMethods.GetImage(1038,0, 0, AImageStream))   then

            begin
               jp := TJPEGImage.Create;
               AImageStream.Position := 0;
               jp.LoadFromStream(     AImageStream   ); **here i got jpeg error #53**
               Image1.Picture.Assign( jp );

            end;

end;

in this line is the error jpeg error #53
jp.LoadFromStream( AImageStream   );
But, if i use this server function all work fine
   function TDSServerMethods.GetImage(proid, Width, Height:   Integer;  out ImgStream: TStream): Boolean;
    var
      Bitmap,Bitmap2: FMX.Graphics.TBitMap;
      scale: Single;
      T:TStream;
      stream: TStream;
     begin

      Result := False;
      ImgStream := nil;
      WITH SPPROC  do
       begin
               close;
               ProcedureName := 'XXXXXX';
               Parameters.Clear ;
               Parameters.CreateParameter('@ID',     ftInteger,pdInput, 0,proid );
               Open;
              Result := recordcount > 0;

       end;

        try

          ImgStream :=   SPPROC.CreateBlobStream(SPPROC.FieldByName('file'),TBlobStreamMode.bmRead);

        except
          Exit(False);
        end;

    end;


text:
Q: Error While Creating Site Collection I am creating Site Collection with Team Site Template. When I tried to create it shows me error that

The parent content type specified by content type identifier 0x0101
  does not exist.

Note : After I tried to create Custom Content Type which inherits Document Content Type I got this error.

A: Please activate 'SharePoint Server Publishing Infrastructure' feature first, to activate the feature go to team site, site action -> site settings -> site collection feature (under Site Collection Administration group) and find 'SharePoint Server Publishing Infrastructure' activate it, please check and let me know if it worked


text:
Q: Download js libraries according to viewport size I have hamburger menu that is only relevant for mobiles etc, i.e not to all viewports. Because of that, my bundle.js file contains jquery that is not really needed for desktop users of my app. It results in a file size that is larger than needed. I bundle my code with webpack and deploy it as is. Right now, I don't have a separate file for vendors.
The jquery library is imported in app.js but I figured out that I can put it in a script tag, check the resolution dynamically and add it to head if meets criteria. Is there any other way to solve it?

A: Try this:
<script>
    if (screen && screen.width > 900) {
        document.write('<script type="text/javascript" src="https://example.com/desktop.js"><\/script>');
    }
</script>

<script>
    if (screen && screen.width < 900) {
        document.write('<script type="text/javascript" src="https://example.com/mobile.js"><\/script>');
    }
</script>


text:
Q: Cannot update Google Sheet from Dataframe -- json issue, single cell issue I have a dataframe of which I want to append the non-header records to a google sheet.
import gspread
import csv

latest = pd.read_csv("/Users/sam/Downloads/transactions.csv")

updatesheet = sheet.worksheet("testpy")

updatesheet.append_row([update], table_range='A1')

This gives an error of Object of type DataFrame is not JSON serializable
I have tried other options from various stack threads, most would result in a non JSON type error, but when I would convert df.to_json() it puts it all into a single cell.
Edit: Updating table_range='A1:A' did not fix.

A: I can think of 2 approaches here, I've included both below.
The JSON type error you're experiencing can be solved by casting a df row as a list, as shown in method2.
The issue where everything gets put into cell A1 can be solved by simply ommitting the table_range.
import gspread
import pandas as pd

# set variables
docid = 'yourdocidhere'
worksheetid = 'transactions'
credfile = 'path/to/file/credentials.json'
csvfile = 'path/to/file/transactions.csv'

# load GSheet
gc = gspread.service_account(filename=credfile)
sheet = gc.open_by_key(docid)
worksheet = sheet.worksheet(worksheetid)

# load CSV file into df
df_csv = pd.read_csv(csvfile)

def method1(worksheet: gspread.Worksheet, df: pd.DataFrame):
    """This is the 'cheaty' way. Just load the existing worksheet
    into df, append other df and overwrite existing worksheet.
    Note that this doesn't check if the values in df are already
    in the worksheet...

    Args:
        worksheet (gspread.Worksheet): the worksheet with which to work
        df (pd.DataFrame): the df to append
    """
    # just load existing GSheet into a df
    df_cheat = pd.DataFrame(worksheet.get_all_records())
    # perform append. You might want to play with how you merge/append
    # This method has the advantage of easy sorting.
    df_cheat = df_cheat.append(df).sort_values(by='Date')
    # overwrite worksheet
    # you could easily create a new worksheet with this method as you have
    # the df_cheat to work with
    worksheet.update([df_cheat.columns.values.tolist()] + df_cheat.values.tolist())

def method2(worksheet: gspread.Worksheet, df: pd.DataFrame):
    """This method goes through the df row by row and adds
    it to the worksheet by using casting.
    https://www.w3schools.com/python/python_casting.asp

    Args:
        worksheet (gspread.Worksheet): the worksheet with which to work
        df (pd.DataFrame): the df to append
    """
    # go over the values in the df by row
    for row in df.values:
        # cast as list
        row = list(row)
        # if you leave out the table_range it will append at the end
        worksheet.append_row(row)

method1(worksheet, df_csv)
method2(worksheet, df_csv)

path/to/file/transactions.csv
Date,Time,Amount,Type,Description,Category
4/1/2019,21:49:02,-$11,Withdrawal,Intuit,*QuickBooks Work - Organization

BEFORE

AFTER


text:
Q: Make the language of First Order Logic uncountable The question is in regards to The Lowenheim-Skolem theorem and the question asks to give a set of sentences that is only true in an uncountable domain. My teacher told me to solve this by "relaxing" the conditions on the language of first order logic so that it is uncountable.
Because the question asks to give a set of sentences in an uncountable domain this leads me to believe that I should try to make either the set of countably infinite constants and/or countably infinite variables uncountable, in the language, but i'm stuck on how to do this and apply it so there's sentences that are only true in this uncountable domain. Any help is appreciated.


text:
Q: Django project deployment: cannot load static files I'm deploying a Django project using:

*

*virtualenv

*nginx

*gunicorn

following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps

My configuration
django settings
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATIC_URL = '/static/'

/etc/nginx/sites-available/esmart2
GNU nano 2.0.9                 File: /etc/nginx/sites-available/esmart2

server {
    server_name 192.168.30.17;
    access_log off;

    location /static/ {
        alias /new_esmart/esmart2/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
}

Running
(esmart_env) [root@eprssrv09 esmart2]# /new_esmart/esmart_env/bin/gunicorn --bind 192.168.30.17:8001 esmart2.wsgi:application

My Django project is running but:
Not Found: /static/admin/css/login.css

Any advice?

UPDATE 1
I think that nginx settings are been avoided:
deleting any reference in 'sites-enabled' folder, django project runs and the problem concerning static files remain.
UPDATE 2
if in Django settings debug=True I get
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/login.css
Not Found: /static/admin/css/base.css

A: It seems I solved BUT I don't think is the better solution. I mean, it's a good solution depending on the project requirements: mine allows using this solution.

install package
pip install whitenoise
on wsgi.py I added:
from whitenoise.django import DjangoWhiteNoise
application = get_wsgi_application()
application = DjangoWhiteNoise(application)

This way nginx site conf is ignored (but I think they had already ignored!)
Django WhiteNoise documentation

With a couple of lines of config WhiteNoise allows your web app to
  serve its own static files, making it a self-contained unit that can
  be deployed anywhere without relying on nginx, Amazon S3 or any other
  external service. (Especially useful on Heroku, OpenShift and other
  PaaS providers.)
It's designed to work nicely with a CDN for high-traffic sites so you
  don't have to sacrifice performance to benefit from simplicity.
WhiteNoise works with any WSGI-compatible app but has some special
  auto-configuration features for Django.
WhiteNoise takes care of best-practices for you, for instance:
Serving compressed content (gzip and Brotli formats, handling
  Accept-Encoding and Vary headers correctly) Setting far-future cache
  headers on content which won't change Worried that serving static
  files with Python is horribly inefficient? Still think you should be
  using Amazon S3? Have a look at the Infrequently Asked Questions.

A: It looks to me like the issue is two-fold:

*

*It looks like you may have an error in your nginx config. Is new_esmart/ really in your root directory/ or is it somewhere like /home/sam/new_esmart/? If it is not in your root directory, make sure to provide the complete path.

*It looks like your STATIC_ROOT will point to path/to/new_esmart/static/ rather than /new_esmart/esmart2/static/. Keep in mind that STATIC_ROOT is the place where your static files will be copied to when you run collectstatic not the place you personally place static files when creating them initially.
So what you probably need to do is confirm that you really want your static files collected to /actual/path/to/new_esmart/static/ and then use that same path in your nginx config.
Also, as discussed in the comments, you could try adding listen 8001; to your nginx config:
server {
    listen      8001;
    server_name 192.168.30.17;
    access_log off;
    ...


text:
Q: InvalidSignatureException when calling EKS cluster I am using ubuntu app on windows. Using this ubuntu app, I was connecting to EKS cluster till yesterday.
Suddenly, it stopped working due to below error. I searched lot and found many answers related to ntpd and system clock but not sure why this has happened now.
This is the error:

An error occurred (InvalidSignatureException) when calling the DescribeCluster operation: Signature expired: 20230219T082231Z is now earlier than 20230219T084848Z (20230219T085348Z - 5 min.)

how to fix this?
I see that system clock is correct on my windows machine but is is not getting synced correctly with ubuntu app. what commands I should run to make this successful?


text:
Q: Vue and Laravel: Are the Vue components even necessary if everything is being read of a bundled file? I am building an an app inside a Laravel project using Vue components.  The blade layout reads off of the bundled app.js so I was wondering when using frameworks like Vue and React, are the files even necessary other than just being there for the bundle process?  Like what I had actually removed the .vue files I have (components) -- would it still work since it's reading off the bundled source file?

A: .vue files are source files, and should therefore be in source control all the time. When it is compiled (using vue-cli for instance), a .js file will come out of it and that is what the browser needs.
So yes for production environments you can remove the .vue files since you only need the bundled and compiled code.


text:
Q: Spatial Overlapping - Filter by % of Coverage I am working with 2 Polygon Shapefiles: parcels & wetlands
Essentially what I want to accomplish is to filter the parcels dataset, where I only keep parcels that contain less than 50% Wetlands. For example the yellow parcels marked blue would be kept while the others would be filtered out, as the wetlands layer covers too much of the parcel

I've researched and tried various Spatial Joins, but none offer an option for %'s, and the gpd.overlay option only works on a DataFrame Level, not on individual polygons.
I was thinking some sort of comparison of Shape Areas, where:
filtered_parcels = filtered_parcels[(wetlands['shape_area'] <= parcels['shape_area'] * 0.5)]
However, I don't know how to obtain the Shape Area of the Wetlands contained only within a certain parcel.

A: I would first dissolve the wetlands gdf down to a single shape. Then I would use geopandas.overlay to make a gdf of the overlapping areas.  I would calculate the area of the parcels and also overlapping areas e.g. using the area package, after converting to an equal-area projection like cea. Then a pandas merge between the parcels and overlapping gdfs would let you compare the areas.
Obviously a lot going on between the lines above - let me know if I need to expand on any points.


text:
Q: svg animation on an animated path I have a piece of svg code that links an animation to a simple path and that works well :
<path id="p0" d="M 110,150 C 300,80 400,300 450,100  500,-100 -90,220 110,150"
stroke="black" fill="none" stroke-width="1" />
<ellipse  rx="20" ry="12" fill="#aaa" stroke="#666" stroke-width="2" opacity=".8">
<animateMotion id="One" dur="10s" fill="freeze"
rotate="auto" repeatCount="indefinite" >
<mpath xlink:href="#p0"/>
</animateMotion>
</ellipse>

Now I need to have the same animation on an animated path. I tried the following :
<path id = "p0" stroke = "black" stroke-width = "1" fill = "none" >
<animate attributeName="d" dur="2s" repeatCount="indefinite" values=
"M 100 200
  C 100 150 250 150 100 100
  C 0 50 100 400 100 200;
M 100 200
  C 100 150 250 150 100 100
  C 0 50 100 100 100 200;
M 100 200
  C 100 150 250 150 100 100
  C 0 50 100 400 100 200" />
</path>
<ellipse  rx="20" ry="12" fill="#aaa" stroke="#666" stroke-width="2" opacity=".8">
<animateMotion id="One" dur="10s" fill="freeze"
rotate="auto" repeatCount="indefinite" >
<mpath xlink:href="#p0"/>
</ellipse>

But to no avail : the ellipse doesn't follow the path and remains invisible...
Any idea ? Is it at least possible ?
Thanks in advance.

EDIT : I just noticed that it works on Firefox, but the problem is that it links the ellipse to the first part of the path values only; in other words it doesn't follow the path animation... :(

A: If you give the path a valid d attribute, it seems to work in Chrome.

<svg width="500" height="500">
  <path id = "p0" stroke = "black" stroke-width = "1" fill = "none"
        d="M 100 200 C 100 150 250 150 100 100 C 0 50 100 400 100 200">
    <animate attributeName="d" dur="2s" repeatCount="indefinite" values=
"M 100 200
  C 100 150 250 150 100 100
  C 0 50 100 400 100 200;
M 100 200
  C 100 150 250 150 100 100
  C 0 50 100 100 100 200;
M 100 200
  C 100 150 250 150 100 100
  C 0 50 100 400 100 200" />
  </path>
  <ellipse  rx="20" ry="12" fill="#aaa" stroke="#666" stroke-width="2" opacity=".8">
    <animateMotion id="One" dur="10s" fill="freeze"
rotate="auto" repeatCount="indefinite" >
      <mpath xlink:href="#p0"/>
    </animateMotion>
  </ellipse>
</svg>


text:
Q: How do you detect if a specific word is at the end of a string in php I have event listings that look like this
PAPA ROACH AT THE PARAMOUNT IN HUNTINGTON ON APR 28, 2015

Im trying to remove everything after the last "ON"
$s="PAPA ROACH AT THE PARAMOUNT IN HUNTINGTON ON APR 28, 2015";
echo strstr($s, 'ON', true);

I came up with something like this but it removes everything after the first "ON" it detects, is there a way to run this backwards or tell to skip to the last "ON"

A: You can use strrpos function to perform search from the end of the string:
$s="PAPA ROACH ON THE PARAMOUNT IN HUNTINGTON ON APR 28, 2015";
echo substr($s, 0, strrpos($s, ' ON ') + 3); // +3 is to include the word ON


text:
Q: proper alignment with bootstrap horizontal forms I am using the code as shown in the bootstrap site for horizontal forms. I have included the bootstrap.css file necessary. However my horizontal forms are not aligning as expected. The labels are at the extreme left and the forms start from 25% of browser margin and extend till end of page horizontally and the forms touch each other above and below without any spacing.
The bootstrap page says about using the .form-horizontal class but I am clueless as to where should I use it. Help will be appreciated. Pasting my code below.
<form role="form" class=".form_horizontal">

                Category

                <input type="text" class="form-control" id="category_type" placeholder="Select a category">

                Title

                <input type="text" class="form-control" id="project_title" placeholder="Enter Title here">

                Quarter/Year

                <input type="text" class="form-control" id="quarter" placeholder="Enter Quarter here Eg. Q2,2013">

                Project Description

                <textarea class="form-control" id="project_description" rows="3" placeholder="Enter Description here"></textarea>

                Contributors

                <input type="text" class="form-control" id="contriutors" placeholder="Contributors">

</form>

A: I'm not sure but maybe this:
  <form role="form" class=".form_horizontal">

Should be changed to this
   <form role="form" class="form-horizontal">

The classname looks odd for bootstrap

A: I got it working.
the problem was <form role="form" class=".form_horizontal">
It should be <form role="form" class="form-horizontal">