text:
Q: How to use a 1 line javascript builder pattern Any javascript builder pattern I have seen constructs the desired object in 2 steps:
var foo = new Foo()
var desiredfoo = foo.func1("something").func2("something");

Is there any way to use it like java ie without breaking lines ?
var desiredfoo = new Foo().func1("something").func2("something");

A: If func1 and func2 both return this then your two examples are equivalent.
The builder pattern might be overkill for JavaScript though since you can use object literals for defaults. e.g. new Foo({value1: 9, value2: "hello"}) and have your constructor process those.


text:
Q: Calling API multiple times - Python I'm trying to use an API that converts dates. I've retrieved data from a file that contained full dates, used split and slice to get the day, month and year seperately. I need to send each date and return the conversion to the user.
What I currently have is:
def convert(day, month, year):
        gr_to_hb_url = 'https://www.hebcal.com/converter?cfg=json&gy='+ year+ '&gm='+ month+ '&gd='+ day+'&g2h=1'
        with urllib.request.urlopen(gr_to_hb_url) as response:
            data = response.read()
            obj = json.loads(data)

            results = [(result['hd'], result['hm'],result['hy']) for result in obj]
            return results

hby, hbm, hbd=convert(prep_day, prep_month, prep_year)
print(hby,hbm,hbd)

prep_day/ month/ year are the day, month and year I retrieved from each day separately as I mentioned above.
The error I get TypeError: string indices must be integers.
Appreciate any help. Thanks!

A: Having a look at the output of the request:
{"gy":2020,"gm":1,"gd":1,"afterSunset":false,"hy":5780,"hm":"Tevet","hd":4,"hebrew":"ד׳ בְּטֵבֵת תש״פ","events":["Parashat Vayigash"]}

I think you might want the following instead:
def convert(day, month, year):
        gr_to_hb_url = 'https://www.hebcal.com/converter?cfg=json&gy='+ year+ '&gm='+ month+ '&gd='+ day+'&g2h=1'
        with urllib.request.urlopen(gr_to_hb_url) as response:
            data = response.read()
            obj = json.loads(data)

            results = (obj['hd'], obj['hm'],obj['hy'])
            return results

The reason for the error you were seeing was that when you iterate through a dictionary type you just get the values.
In this case that would be something like the following (Although the order isn't guaranteed when iterating through a dictionary)
[2020,1,1,False, ...]
I imagine that the first element that you were iterating through was something like "Tevet".
If the value of result is "Tevet" then running "Tevet"["hd"]
would result in the error you were seeing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is "view as someone else" recommended from the software design perspective? Some time ago, Facebook introduced a feature that helps set up the permissions on ones profile: view as someone else. It allows the author of a dynamic page to see which user groups (or specific users) can see which information in the page, and thereby debug the permissions. A similar feature exists in LinkedIn
The modern applications, especially B2B, may have much more complex permission settings. Therefore such tool is much more useful. However as far as I know, this function is not very wide spread. I wonder what the disadvantages may be, or if there is any RFC and best practice article I can read before considering it for my own project.

A: Sure, this is called "RunAs", "impersonation", "sudo"...
It is built-in to Spring Security: http://docs.spring.io/spring-security/site/docs/4.0.4.RELEASE/reference/htmlsingle/#runasmanager
It's also built in to most database servers:
https://msdn.microsoft.com/en-us/library/ms181362.aspx
Adding any complexity to a secure application makes it a little more likely to be vulnerable.


text:
Q: Design and construction of a system identifying molecular nitrogen and water I have read papers that use LIDAR-like and LIDAR-Raman systems that detect elements.
I want to measure the vapor water ($\rm H_2O$) and $\rm N_2$ of trees/agriculture using Arduino and low cost elements (DIY).
I am thinking of using 405 nm, 50 mW laser. The problem is how can I detect the returned wavelength?
What I am thinking:

*

*A CCD sensor?

*A Photodiode array?

*A modified webcam?

*A photodiode with a filter?

My question is what do I measure with the wavelength sensor? The time from when I send the pulse of the laser and the time it returns in the wavelength sensor? Only the wavelength? Should I send a specific coded message with the laser? For example 101010011?


text:
Q: Does Google Maps API V2 API require android 4.2.2? I've been using the V1 MapViewfor all my apps.  I thought I should look into going to the Google Maps Android API V2 and began following the tutorial at This Page Of course, like most things android, the tutorial process has enough bugs or omissions that it doesn't work. Further research found that few others can manage to make it work either.
While doing that research, however, I tripped on to This Page that says:

If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.
  Note: Only Android 4.2.2 and higher versions of the Google APIs platform include Google Play services.

I understand that the V2 API operates through Google Play Services so does this mean that my app can't target older android versions if I use the V2 API?
Thanks, Gary

A: the reason you can only test it on 4.2.2 in the emulator is because that version comes with google play services.
google play service works on anything 2.2 and up as long as the device has google play services installed

A: No, it does not require 4.2.2. That documentation you're referencing pertains only to emulation. Prior the the emulator/Google APIs add on for 4.2.2, Google Play services was not included. If you want to test your maps integration on Android versions <4.2.2, you need to use a real device.


text:
Q: Issue with check times overlaps There are two models:
# Table name: activities_people
#
#  activity_id :integer          not null
#  person_id   :integer          not null
#  date        :date             not null
#  id          :integer          not null, primary key

# == Schema Information
#
# Table name: activities
#
#  id          :integer          not null, primary key
#  name        :string(20)       not null
#  description :text
#  active      :boolean          not null
#  day_of_week :string(20)       not null
#  start_on    :time             not null
#  end_on      :time             not null

Relations:
activity.rb
has_many :activities_people
has_many :people, through: :activities_people

activity_people.rb
belongs_to :person
belongs_to :activity

I try to create validation that person can join to one activity taking place in specific date and time(start_on, end_on). If I will try sign up to another activity while before I joined to other exercises(same date, and times overlap) should throw error.
What I try:
  def check_join_client
    activities_date = person.activities_people.where('date = date', date: date)
    if activities_date.exists && person.activities.where('id IN (?)', activities_date)
  end

I don't know how to use create query(person.activities.where ...) to getting person activities related with activies_people. activities_date check if we joined to activities taking place in same date. Second I want get check start_on and end_on.
Thanks in advance.

A: If I'm understanding you correctly, you want to find the activites_people for a user that match a query by the date array and then raise an error unless an associated activity for those matched activities_people.
Your original code for check_join_client uses if incorrectly:
 def check_join_client
    activities_date = person.activities_people.where('date = date', date: date)
    if activities_date.exists && person.activities.where('id IN (?)', activities_date)
  end

To translate this to pseudocode, you're essentially saying:
result = query if result.condition_met?

However the if condition (the expression after the if) will be evaluated before you define results. It might be more clear if I show a correct approach:
result = query
  return result if result.condition_met?
Now to go back to your question about loading associated records, try something like this:
   activities_people_ids_matching_date = person.activities_people
                                               .where(date: self.date)
                                               .pluck(:id)
   # use pluck to get an array of ids because that's all that's needed here
   # not sure how you're getting the date variable, so I'm assuming self.date will work
   # I can use `.any?` to see if the ids list is not empty.
   condition_met = activities_people_ids_matching_date.any? &&\
                   person.activities
                         .where(activities_people_id: activities_people_ids_matching_date)
                         .any?
   condition_met ? true : raise(StandardError, "my error")

There surely is a way to get this done with one query instead of two, but it seems like where you're at with Ruby concepts it's more important to focus on syntax and core functionality than SQL optimization.

A: The correct syntax (one of several options) is:
person.activities_people.where(date: date)


text:
Q: Launching MIT Scheme Can you help me to figure out how to use MIT Scheme? The Edwin editor. There is a huge field to type but it doesn't respond. It allows me to evaluate expressions in the bottom tiny field only when I type esc twice in a row.

A: Edwin is an editor; it is not a interactive shell. The big empty space is used to write a scheme file.
I think you to work in an interactive shell.
Open a console window and type "scheme" to work in an interactive shell.
To write a scheme-program-file you can use an editor in ascii-mode. Use the suffix "scm" to store the file.
To run it, type in the scheme-shell:

(load "start.scm")

40 years ago scheme and edwin were distributed by texas instruments. With these tools I started to love programming. Today I am working under ubuntu and I am using emacs as editor and a bash-shell running MIT/Gnu-Scheme. 5 year ago tryed edwin agin, but I preferd emacs.
The most people would suggest to use DrRacket.
What Operation System you are using?


text:
Q: Swift 3/ iTunesConnect track app sales live As opposed to Google Play Console, I can't find a way to check the amount of app sales being made in real time. I am not a patient person so I'd like to be able to check this information multiple times throughout the day.
At the moment, I track my website's performance with Google Analytics so I can see how many people visit the app's manual compared to the amount of people who did the same thing 7 days ago. However, this value can vary up to 40% while having the same amount of app sales so it's not a very good indicator.
The app is dependent on a very small footprint so including a framework that tracks usage statistics would be overkill. I only need a way to get notified how many people have opened this app today. Have you implemented this somewhere in your own projects? Or is there even a section for that in iTunesConnect?

A: You could log an event with Google Analytics called "App Opened" or something where the label is the identifierForVendor. Another option is to create an UUID and store it in UserDefaults, and use that as the label.
By checking the number of events with a unique label you could see the amount of installs.
This wouldn't require you to add a new framework or to implement anything else.


text:
Q: C# how to read certain properties without knowling length I did a GET to the nuget api to get certain data about a package (in my case stylecop). The call works and i successfully get a json as a result. However the json is has a complex structure and i need to read out all items.
This is the api call i did, it works. This should show you the json im trying to get data from:
https://api.nuget.org/v3/registration3/stylecop.analyzers/index.json
The red area contains the item objects i want to read from. It has a total of 43 items in it. Every of these items has a commitId property. I want to read out all 43 commitId properties from every item to store them in a list.

https://imgur.com/a/kNGytom
dynamic dynJson = JsonConvert.DeserializeObject(x);
   foreach (var item in dynJson)
                    {
                        Console.WriteLine(item.commitid);
                    }

This is what i've tried but i dont know how to access the 2nd layer of items

A: I see that JSON should be quite easy to create C# classes which you can deserialize into. You can use tool like jsonutils.com to generate C# model from your example JSON string and probably tweak it to better resemble your JSON structure.
Then you can deserialize it to C# object using:
var yourObject = JsonConvert.DeserializeObject<YourJsonModel>(jsonString);

and access to any level you'd like via the object arrays/lists in the C# object.


text:
Q: Automatically block DOS attacks in AWS I would like to know what is the best and the easiest solution
to protect http server deployed on AWS cloud against DOS attacks
I know that there is AWS Advanced Shield
that can be turned on for that purpose
however it is too expensive (3000$ per month)
https://aws.amazon.com/shield/pricing/

System architecture

HTTP request -> Application Load Balancer -> EC2

*

*Nginx server is installed on this machine

*Nginx server is configured with rate limiting

*Nginx server responds with 429 code when too many requests are send from one IP

*Nginx server is generating log files (access.log, error.log)

*AmazonCloudWatchAgent is installed on this machine

*AmazonCloudWatchAgent listen on log files

*AmazonCloudWatchAgent send changes from log files to specific CloudWatch Log groups

*Logs from all EC2 machines are centralized in on place (CloudWatch Log groups)

I can configure CloudWatch Logs Metric Filters
to send me alarms when too many 429 requests happen from one IP number
In that way I can manually block particular IP in Network ACL
and cut off all requests from bad IP number in a lower network layer
and protect my AWS resources from being drained

I would like to do it somehow automatically
What is the easiest and the cleanest way to do it?

A: Note that, per the AWS Shield pricing documentation:

AWS Shield Standard provides protection for all AWS customers from
  common, most frequently occurring network and transport layer DDoS
  attacks that target your web site or application at no additional
  charge.

For a more comprehensive discussion on DDoS mitigation, see:

*

*Denial of Service Attack Mitigation on AWS

*AWS Best Practices for DDoS Resiliency

A: There is no one straightforward way to block DDOS to your infrastructure. However, there are a few techniques and best practices which you can follow to at least protect the infrastructure. DDOS attacks can be stopped by analyzing and patching it at the same moment.
You may consider using external services listed below to block ddos at some extent:

Cloudflare: https://www.cloudflare.com/en-in/ddos/
Imperva Incapsula:
  https://www.imperva.com/products/ddos-protection-services/

I have tried both in the production system and they are pretty decent. Cloudflare is right now handling 10% of total internet traffic, they know about the good and bad traffic.
They are not much expensive comparative to shield. You may integrate it with your infrastructure as a code in order to automate for all of your services.
Disclaimer: I am not associated in any way with any of the services I recommended above.


text:
Q: Getting a Unable to exec g++.real error in eclipse I recently installed eclipse on Ubuntu.  I added the CDT plugin.  When I try to run the hello world program for c++ I get a make:*[src] Error 2 error.  In the console I get the Unable to exec g++.real error.  I have been looking up on stack and google how to fix this all morning and have had no luck. From what I can figure out, there is a problem with the makefile, but the CDT plugin makes that file automatically. Anyone have and ideas of what I can do to fix this problem?

A: I would go with :

sudo apt-get install build-essential

Then hopefully g++ should be added to your PATH.


text:
Q: Неверный вывод результатов: Counter считает каждый символ дважды import re #библиотека для работы с регулярными выражениями
import collections
frequency = {} #пустой словарь
document_text = open('text.txt', 'r') #открываем файл на чтение
text_string = document_text.read().lower() #убираем капс
c = collections.Counter(text_string)
for word in text_string:
    c[word] += 1
print(c)

Данный скрипт подсчитывает количество повторений каждого символа в файле, но почему то подсчитывает не верно. Результат в 2 раза больше, чем истинные значения. Где я ошибся?
Используется Python 3.6.1

A: Часть
for word in text_string:
    c[word] += 1

бесполезная, так как Counter сам делает все что нужно.


text:
Q: How can I config prometheus alert with line-notify I've trying to find a way for send alert notification on my prometheus server to line-notify.I checked alert rules configure status on prometheus is OK and alert rules can detect event normally, this my config.yml for alertmanager
global:
  resolve_timeout: 5m

route:
  receiver: "line-noti"
  # group_by: ['test-node-linux', 'test-node-windows', 'test-container-exporter', 'test-jmx-exporter']
  group_interval: 10s
  repeat_interval: 1m

receivers:
- name: 'line-noti'
  webhook_configs:
  - url: 'https://notify-api.line.me/api/notify'
    send_resolved: true
    http_config:
      bearer_token: [my_token]

but it doesn't send any messages to line-notify
How can I do for solved this case?

A: The problem in the receiver's name, you have double quotation marks ". However, the name of receiver should be either with single apostrophes ' or completely without.
Also the url can be without apostrophes.
Try this:
global:
  resolve_timeout: 5m

route:
  receiver: line-noti
  # group_by: ['test-node-linux', 'test-node-windows', 'test-container-exporter', 'test-jmx-exporter']
  group_interval: 10s
  repeat_interval: 1m

receivers:
- name: line-noti
  webhook_configs:
  - url: https://notify-api.line.me/api/notify
    send_resolved: true
    http_config:
      bearer_token: [my_token]


text:
Q: How do I get all the value of Input fields (including select, text-area) from multiple fieldsets inside a single form element? I've a form, which consists both plain <input> tags as well as other fileds inside <fieldset> .
When I do $('.form-class-name').serialize(); , it only takes the value of the those input fields which are outside of the <fieldset> . However if I put some value to the input field inside <fieldset> , serialize will take the value of them too.
The problem here is that, I need all the values of input fields in the whole <form> element even if they are blank, which in my case jquery serialize isn't doing.
Any help/reference/suggestion would be great.
Here's a sample of my html. https://jsfiddle.net/7h61bboc/6/
Has anyone been through this road? Help me.
Here's the updated html with desired result and current result : https://jsfiddle.net/gqwg4pd5/2/
Note: I was trying to get even the blank values of Radio, Checkbox, Select, which is  not supported by Jquery Serialize.

A:         var values = {};
          $.each($('#myForm').serializeArray(), function(i, field) {
              values[field.name] = field.value;
                 });

try this below code
                $('#myForm').bind('submit', function () {
                    var elements = this.elements;
                 });

A: $('#myForm').submit(function() {
// get all the inputs into an array.
var $inputs = $('#myForm :input');

// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
    values[this.name] = $(this).val();
});
});

A: You can use a serialize() function of JQuery:
var datastring = $(".form-class-name").serialize();
    $.ajax({
        type: "POST",
        url: "your url.php",
        data: datastring,
        success: function(data) {
             alert('Data send');
        }
    });


text:
Q: Accessing Objective-c base class's instance variables from a Swift class Having an Objective c base class:
@interface ObjcClass : NSObject {
    NSString *aVariable_;
}

And a swift sub-class:
class SwiftClass : ObjcClass {
    func init() {
        // aVariable_ can't be accessed here. An Objective-c derived
        // class has direct access to it's super's instance variables!
    }
}

How do I access ObjcClass aVariable_ from within SwiftClass?

A: I couldn't find a "proper" way to do this, but I needed badly for it to work. My solution was to create a simple getter method in my Objective C superclass, like this:
header file
@interface ObjcClass : NSObject {
    NSString *myVariable;
}
- (NSString *)myVariable;

in the implementation file
- (NSString *)myVariable {
    return myVariable;
}

I'd love to hear of a better way of doing it, but this at least works.

A: I've searched a lot for this.
Eventually I changed my code from:
@interface PrjRec : NSObject {
    @public
    NSString* name;
}
@end

To:
@interface PrjRec : NSObject {
}

@property NSString* name;

@end

similar to @JasonTyler solution.
Then I can access to my object property from Swift code with simple dot notation <object instance>.name,
But I needed to change all existing objective-c references from
<object instance>->name

To:
<object instance>.name

or
_name

if inside class unit.
I hope for a better solution too.

A: Great query. We have tried to hard to get this done. The only working solution I found
get value by using self.valueForKey("aVariable_")
set value using self.setValue("New Value", forKey: "aVariable_")
Hope that helps. Possible solution without altering super class.

A: This worked as a pretty neat solution for me, just adding a Swift variable like:
var myInstanceVar: String {
    return self.value(forKey: "myInstanceVar") as! String
}

A: If you are willing to have a property, then you can create the property to fit your needs.
@interface ObjcClass : NSObject {
    NSString *aVariable_;
}

@property (nonatomic) NSString *aVariable_;

...
@implementation ObjcClass

@synthesize aVariable_ = aVariable_;

This allows the variable to be accessed as inst->aVariable_ or as inst.aVariable_. In the Objective C class the variable can be accessed as aVariable_ or self.aVariable_.

A: I seriously don't know why anyone does instance variables anymore (for one, they're private by default) vs properties. See Giorgio Calzolato's answer on this (apart from his last line about looking for a better solution - that IS the best solution :) ).
In my case I already had a property and was extra perplexed over why it didn't work. But I realized that the property had a custom time and it needed to be added into my SDK-Bridging-Header.h file.
So if your property is set to a custom type like this:
@property (nonatomic, weak) IBOutlet SDKMyCustomObject *customObject;

...then remember to add it to the bridging header.


text:
Q: Unittesting for correct 'continue' behaviour I have a function that asks a user for confirmation via a prompt. It accepts y or n as answers, otherwise it asks again.
Now, I want to write a unittest for this function. I can test the correct behaviour for y or n just fine, but how do I test that my function correctly rejects inacceptable input?
Here's the code for foo.py:
def get_input(text):
    """gets console input and returns it; needed for mocking during unittest
    """
    return input(text)

def confirm(message='Confirm?', default=False):
    """prompts for yes or no response from the user. Returns True for yes and
    False for no.
    'default' should be set to the default value assumed by the caller when
    user simply types ENTER, and is marked in the prompt with square brackets.
    """
    if default:
        message = '%s [y]|n: ' % (message) # default answer = yes
    else:
        message = '%s y|[n]: ' % (message) # default answer = no

    while True:
        answer = get_input(message).lower()

        if not answer:
            return default
        if answer not in ['y', 'n']:
            print('Please enter y or n!')
            continue
        if answer == "y":
            return True
        if answer == 'n':
            return False

answer = confirm()
print(answer)

And here is my Test class:
import unittest
import foo

class TestFoo_confirm(unittest.TestCase):
    """testing confirm function
    """
    @unittest.mock.patch('foo.get_input', return_value='y')
    def test_answer_yes(self, _):
        self.assertEqual(foo.confirm(), True) # confirmed if 'y' was entered

So, how do I write a similar test for an input-value like '1' (or how do I need to adjust my confirm() function to make it testeable)?
Currently, if I call foo.confirm() from the unittest file, it just gets stuck in an infinite loop and it doesn't return anything. (I understand why this is happening, just not how to circumvent it.)
Any ideas?

A: You could try this:
import unittest, unittest.mock
import foo

class TestFoo_confirm(unittest.TestCase):
    """testing confirm function
    """
    @unittest.mock.patch('foo.get_input', return_value='y')
    def test_answer_yes(self, _):
        self.assertEqual(foo.confirm(), True) # confirmed if 'y' was entered

    @unittest.mock.patch('builtins.print')
    @unittest.mock.patch('foo.get_input', side_effect=['1','yn','yes','y']) # this will make the mock return '1', 'yn' and so on in sequence
    def test_invalid_answer(self, mock_input, mock_print):
        self.assertEqual(foo.confirm(), True) # it should eventually return True
        self.assertEqual(mock_input.call_count, 4) # input should be called four times
        mock_print.assert_called_with('Please enter y or n!')

In the second test case, we imitate a user who enters three invalid inputs, and, after being prompted again, finally enters 'y'. So we patch foo.get_input in such a way that it returns 1 the first time it's called, then yn, then yes and finally y. The first three examples should cause the confirm function to prompt the user again. I also patched the print function, so that the 'Please enter y or n!' message wouldn't show up when testing. This isn't necessary.
Then we assert that our mock input was called four times, meaning that the first three times, the confirm function reprompted.
Finally we assert that the print function was called (at least once) with 'Please enter y or n!'.
This does not test if the correct number of print statements were made or if they were in correct order, but I suspect this would be possible too


text:
Q: SwiftUI - Animate view transition and position change at the same time I have a yellow container with a green view inside. I want to move the container while also hiding/showing the inner green view, with an animation. Currently, I'm using .offset for the movement, and an if statement for the green view's transition.
The problem is, although the yellow container moves, the green view does not. It simply fades in and out at the destination offset. I want it to also move alongside the yellow container.

This is what I get currently
This is what I want

Here's my code:
struct ContentView: View {
    @State var showingSubview = false

    var body: some View {
        VStack {
            Button("Show Subview") {
                withAnimation(.easeInOut(duration: 2)) {
                    showingSubview.toggle()
                }
            }

            if showingSubview {
                Text("Subview")
                    .padding()
                    .background(Color.green)
            }
        }
        .padding()
        .background(Color.yellow)
        .offset(x: showingSubview ? 150 : 0, y: 0)
    }
}

How can I make the green view move along with the yellow container, as it fades in and out? Preferably, I'd like to keep using if or switch statements for the insertion/removal.

A: You can just change the height as it animates.
Code version #1
This will not fade and appears inside the yellow rectangle.
Code:
struct ContentView: View {
    @State var showingSubview = false

    var body: some View {
        VStack(spacing: 0) {
            Button("Show Subview") {
                withAnimation(.easeInOut(duration: 2)) {
                    showingSubview.toggle()
                }
            }

            Text("Subview")
                .padding()
                .background(Color.green)
                .padding(.top)
                .frame(height: showingSubview ? nil : 0, alignment: .top)
                .clipped()
        }
        .padding()
        .background(Color.yellow)
        .offset(x: showingSubview ? 150 : 0, y: 0)
    }
}

Result #1

Code version #2
This version will fade out and appear at bottom edge, as your GIF shows.
Code:
struct ContentView: View {
    @State var showingSubview = false

    var body: some View {
        VStack(spacing: 0) {
            Button("Show Subview") {
                withAnimation(.easeInOut(duration: 2)) {
                    showingSubview.toggle()
                }
            }

            Text("Subview")
                .padding()
                .background(Color.green)
                .padding(.top)
                .frame(height: showingSubview ? nil : 0, alignment: .top)
                .padding(.bottom)
                .background(Color.yellow)
                .clipped()
                .opacity(showingSubview ? 1 : 0)
        }
        .padding([.horizontal, .top])
        .background(Color.yellow)
        .padding(.bottom)
        .offset(x: showingSubview ? 150 : 0, y: 0)
    }
}

Result #2


text:
Q: Django send http response without changing page In Django, if i want to retrieve a POST form, scan the data, if the data has an error like password does NOT match the confirmed password how do i do that?
IE; The user inputs 123 in password and 1234 in confirm password, without changing or refreshing the website or anything like that, how do i send back a response stating 'passwords do not match' similarly, in a login form, if the user credentials they inputed does not match, how do i send it back.
(New to Django, found my errors from dirkgroten answer thanks! Also reason i couldnt get answers on this is because i couldn't phrase it correctly to search!)

A: The URL shown in a browser is the URL of the HTTP request that lead to the response it renders. So if you have a page at URL /appname/ that submits a form at URL /appname/submit/ then the response received (assuming it's a HTTP 200 OK) will be rendered by the browser with the URL /appname/submit/ and there's nothing you can do at the back-end to influence that. So what you want is not possible. Of course you can always redirect (HTTP 302 Redirect) to a different URL, but that's probably not what you're looking for.
You don't give a concrete example of what you're trying to achieve, but the login form mentioned seems to indicate that you're submitting a form to a different URL than the original URL used to fetch the form. Don't do that. Use one URL (and one view) to render and process the form:

*

*With a GET request, you return the page with the empty (or initial) unbound form (HTTP 200).

*With a POST request and invalid data, you return the same page with the filled bound form and errors (HTTP 200).

*With a POST request and valid data, you process the data and redirect to a different page showing success (HTTP 302).

Look at working with forms docs to see an example. This is how you should do it for every form.
Note that on many websites nowadays, forms are submitted via ajax (XHR). That allows you to submit your form in the background without refreshing the page. The javascript can submit it to any URL (on the same domain) since that won't affect the URL the user sees, and the javascript takes care of updating the various elements in the page depending on the response. It also allows you to put the same form on multiple different pages (e.g. a login popup form in the top navigation bar of your website, which is shown on every page of your website).


text:
Q: lighttpd + PHP-fcgi slow response We have a problem regarding lighttpd as the webserver with php5 as backend via fast-cgi.
Sometimes the server's response is taking more than 5 seconds (up to 20 seconds) when requesting a simple file that calls phpinfo();.
The server log does not show any errors and the HTTP response is 200.
When I request a static html file without any PHP content, there is no problem and all the requests are being served fast.
This is the lighttpd-fcgi Config:
fastcgi.debug = 1
fastcgi.server += ( ".php" =>
    ((
        "bin-path" => "/usr/bin/php-cgi",
        "socket" => "/tmp/php.socket",
        "max-procs" => 7,
        "bin-environment" => (
            "PHP_FCGI_CHILDREN" => "5",
            "PHP_FCGI_MAX_REQUESTS" => "5000"
        )
    ))
)

The server is running Debian 7 64 bit.

A: Check you don't have any orphaned fcgi handlers, easiest way is to stop lighttpd and then `ps auX' and look for php-cgi. Kill them off if any exist, then start lighty up again.
Set up a server-status handler in your lighty config. This will allow you to refresh a page and see all connections currently being handled, and what state they are in..
http://redmine.lighttpd.net/projects/1/wiki/Docs_ModStatus
Check lighty is actually able to write to its error log. When stopping and restarting lighty, it should leave a log in error.log. This way if your fcgi-handlers are all tied up and lighty has to stall a request, it will log this.
I wouldn't recommend max-procs => 7 unless youve a very good reason for it. Try lowering max-procs to 1, and raising your FCGI_CHILDREN significantly. My high traffic server is configured to use max-procs 1 and FCGI_CHILDREN 120.
I realise this contradicts the lighttpd wiki, however that is edited by users, whereas my suggestion is based on empirical evidence and also advice directly from the lighty team.
The other thing to bear in mind is that there is a separate opcode cache being maintained for each process. So by reducing it to 1, all scripts are using the same opcode cache, which means less time spent compiling and pruning 7 different caches.

A: Each php worker process can handle only one request at a time; each "proc" (in your case 7) usually has a master process (which doesn't handle requests) and PHP_FCGI_CHILDREN (in your case 5) worker process, which makes a total of 35 worker processes.
lighttpd allocates a separate socket for each "proc", and each socket has its own request queue. So if it takes a long time to handle your request it is most likely that the selected backend has a long queue of requests to handle.
So just do some simple math: if one request takes php about 2 seconds to handle, your setup can handle #workercount / #timeperrequest = 17.5 requests/sec.
In order to increase number of requests per second you have two options:

*

*start more php worker processes (and make sure you have enough memory/CPU for them to run, watch top and other tools)

*improve the response time of single requests (look out for slow SQL queries, http requests to internal services, ...); again check for memory and CPU bottlenecks with top - if your server starts swapping everything will get super slow.

PS: don't put your sockets into /tmp; put them into (/var)/run/lighttpd/ instead and make sure only your lighttpd user (www-data) has access, see CVE-2013-1427


text:
Q: imagemagick cannot read these files I have jasper installed and the lastest version of imagemagick. When I attempt to process these two files: here and here
I get a decode error. Can anyone let me know which other packages I need to install for imagemagick to read these files properly?

A: Has your IM been compiled with --with-jpeg=no or --without-jpeg?
Or did the compilation fail to include JPEG support because of a lack of decoder libraries being installed?  You need libjpeg installed, and the development header files for that library.
You can find out what formats are supported by issuing the command:
$ identify -list format

If you state your OS (inc. distribution if Linux) and how you installed IM, you might get more information on how to resolve it.  If you are on linux the package names are probably libjpeg and libjpeg-devel.


text:
Q: How Do I Select A Distinct Row But Also Add An Original Column On The following MySql;
SELECT DISTINCT students.id
              , students.added
              , students.email
              , students.assessment
           FROM db.students as students
          ORDER
             BY students.email ASC
              , students.added DESC
              , students.id DESC
          LIMIT 10000000

Is giving me
'1751','2020-09-23 18:03:41','a@b.com','Module 6 Assessment'
'1741','2020-09-23 18:02:30','a@b.com','Module 6 Assessment'
'1731','2020-09-23 17:59:59','a@b.com','Module 6 Assessment'
'1721','2020-09-23 17:45:41','a@b.com','Module 5 Assessment'
'1711','2020-09-23 17:23:30','a@b.com','Module 4 Assessment'

But I don't want the 'Module 6 Assessment' to be repeated 3 times, I only want the last (and most up to date completion of that assessment to be shown).
I can remove the students.id and students.added to 'collapse it down' which works, but then I loose the added time of that record.
How can I get the distinct AND also have the extra data added to the final set?

A: For example, it may be
SELECT GROUP_CONCAT(id, ' => ', added SEPARATOR '\n'), email, assessment
FROM students
GROUP BY email, assessment
ORDER BY email ASC, MAX(added) DESC

fiddle


text:
Q: Xcode adds a lot of  tag in my storyboard and xib file Just wanna know if anybody has the same issue as mine: Xcode adds a lot of  tags into the storyboard I touch. I try to remove but I can't because it keep adding those tags back.
It this a bug of the new Xcode I'm using (7.0.1)?

A: As of Xcode 7.2 Beta (7C46I) released on 10/28/2015, just like these tags were added automatically when opening a Storyboard or XIB file in Xcode 7 or 7.1 on El Capitan, these tags are now being removed automatically by just opening a Storyboard or XIB file. (It now seems that the addition of the  tags may have been unintentional.)
As this has caused some issues with modifications to Storyboard and XIB files within some of my teams I recommend that if you're working with multiple people on a project that you a) coordinate to all use the same version of Xcode and b) coordinate a time to switch from Xcode 7.1 to 7.2 to avoid unnecessary merge conflicts.
XIB file showing these tags removed after opening with Xcode 7.2 beta:

A: Confirmed to be fixed on Xcode 7.2 live version (released Dec 8 2015)


text:
Q: limiting Bash output by timestamp I'm trying to write a script that will check on the number of threads being used for given processes.   I have it all written, but one of the pieces that is alluding me is setting it so that it will only output the last hour.   Is there a way to do this?
The timestamp does look like this:
2014-11-18 10:02:02


text:
Q: Query multiple custom post types using ratios (or similar) I'm a bit stumped with this one. I'm using wordpress and I'd like to query multiple custom post types using some kind of ratio and display them on a page.
Let's say I have the following post types:
tweet, project, video & post
At the moment my current query result is flooded with tweets and all the other post types are being pushed down the page.
Is there a way to formulate a query so that (say) 25% of the result is taken up by tweets and the remaining 75% taken up by the other post types? Essentially I'd like to reduce the number of tweets that are appearing in my query result.
I hope that makes sense.
Many thanks

A: I would probably handle this manually with 2 separate custom queries (using WP_Query).  I'm going to assume you want paging enabled (since it's your only blogroll and eventually this will get very large).  In general, the strategy is going to be:
1) Build two different queries (1 for your projects, videos, and posts... And 1 for your tweets).
2) Setup the ratio you'd like to mix using the posts_per_page attribute of your query arguments.
3) Loop each query, but don't output their titles or content just yet, but rather, store each in its own array.
4) Create a new array to contain your "shuffled" blogroll.
5) Loop through this new array to output the content.
$posts_array = array(); // this will temporarily hold your projects/videos/posts
$tweets_array = array(); // this will temporarily hold your tweets

// WP_Query arguments for projects, videos, and posts
$post_args = array (
    'post_type'              => array('project', 'video', 'post'),
    'post_status'            => 'publish',
    'pagination'             => true,
    'posts_per_page'         => '10',
);

// The Query
$query_posts = new WP_Query( $post_args );

// The Loop will be used to grab the posts and store them in $posts_array
if ( $query_posts->have_posts() ) {
    while ( $query_posts->have_posts() ) {
        $query_posts->the_post();

        // here you can use any number of functions inside the loop to get content or metadata about this post
        $posts_array[] = array(
            'title' => get_the_title(),
            'permalink' => get_permalink(),
            'excerpt' => get_the_excerpt(),
            'content' => get_the_content(),
            'thumbnail' => get_the_post_thumbnail()
        );
    }
} else {
    // no posts found, maybe handle this differently if you wish
}

// Restore original Post Data
wp_reset_postdata();

// WP_Query arguments just for tweets
$tweet_args = array (
    'post_type'              => 'tweet'
    'post_status'            => 'publish',
    'pagination'             => true,
    'posts_per_page'         => '2',
);

// The Query
$query_tweets = new WP_Query( $tweet_args );

// The Loop will be used for your tweets
if ( $query_tweets->have_posts() ) {
    while ( $query_tweets->have_posts() ) {
        $query_tweets->the_post();

        $tweets_array[] = array(
            'title' => get_the_title(),
            'permalink' => get_permalink(),
            'excerpt' => get_the_excerpt(),
            'content' => get_the_content(),
            'thumbnail' => get_the_post_thumbnail()
        );
    }
} else {
    // no posts found, maybe handle this differently if you wish
}

// Restore original Post Data
wp_reset_postdata();

$final_array = array(); //this is the array that'll hold the shuffled post types

// this loop is currently built to assume the "posts_per_page" ratio from above
// edit these to your liking if you want to increase the number of tweets per 10 other posts
for ($i = 0; $i < 10; $i++) {
    $final_array[] = $posts_array[$i];

    // after the 5th normal post, inject a tweet (we only have 2 tweets, so inject the first one)
    if ($i == 4) {
        $final_array[] = $tweets_array[0];
    }
}

// now that all 10 posts are done, throw in the last tweet next
$final_array[] = $tweets_array[1];

// now output your content in your template
foreach ($final_array as $current_post) {
    // this will be your markup for each post so replace this with the HTML for your own template
    echo '
' . $current_post['title'] . '
';
    echo '
' . $current_post['excerpt'] . '
';

    // etc etc with any of your remaining array elements
}

I didn't test this code, so treat it sort of like pseudocode.  But the general idea is hopefully clear.
Have fun!


text:
Q: How to prove that a Group $G$ with order $p^2$ must be a abelian group(where p is a prime)? I consider that the elements in $G$ only have two cases:
1) $G$ has an element $a$ with order $p^2$ then it's abelian.
2) $G$ has an element $a$ with order $p$, then we have a subgroup $<a>$ and choose another element $b$ $\notin <a>$ then we have $G = <a,b>$ but under this circumstance, how to prove that $<a,b>$ is abelian?
Edit:
With the help of the comments posted by @user1729 and @JohnHughes, I may have a solution:
Consider $Z(G)$, since the order of $G$ is $p^2$ then we know $G$ has nontrivial center, also the center of $G$ is a normal subgroup of $G$, we get the followings results:
(1) $Z(G)$ is abelian with order prime $p$
(2) $G/Z(G)$ has order prime $p$ then is abelian.
Using(1) and (2) we know $G$ is abelian.
Edit: The last edit is wrong, since I do not use that $Z(G)$ is generated by a single element $a$ and $ab = ba$ then $G = <a,b>$ is abelian.

A: The key here is that the center is nontrivial. Once you have that, you can take $a$ belonging to the center, then $a$ commutes with $b$ so the group generated by $a$ and $b$ must be abelian.
So try to prove that the center of a group of order $p^2$ for $p$ prime is nontrivial.


text:
Q: Random direction en 2D lua I want to create a random direction for my sprite, in Lua 2D.
So, i've tried that :
Sprite.x = Sprite.x + vx
Sprite.y = Sprite.y + vy

Sprite.vx = math.random(-1,1)
Sprite.vy = math.random(-1,1)

So, i managed to create a random direction, but my problem is the speed of the sprite, is directly linked to the number of direction. For example if i want the speed to be 1, it can only have 4 direction. I made a sprite with a lot more, by setting the random speed between -3 and 3, but then it's faster than what i want.
What should i do?
I've seen a few posts talking about random direction, but the description wasn't about lua and i couldn't really understand it..
Thanks!

A: If I am understanding the problem correctly, you want to choose random directions for the velocity, but you don't want the speed to change. To do this you can choose random velocity components for the x- and y-directions, and then normalize this to a unit vector by dividing each component by the magnitude of the vector.
Also, math.random(-1, 1) will only give value of -1, 0, or 1. If you want more variety in the directions, use math.random() to get floating point values in the range [0, 1). You can randomly choose to make the components negative to get a full spectrum of directions.
Here is a little function that returns a pair of vx and vy velocity components:
function rand_v_dir ()

   vx = math.random()
   vy = math.random()

   norm = math.sqrt(vx * vx + vy * vy)
   vx = vx / norm
   vy = vy / norm

   if math.random(0, 1) == 0 then
      vx = -vx
   end

   if math.random(0, 1) == 0 then
      vy = -vy
   end

   return vx, vy
end

Here are ten random velocity vectors generated by the above function:
> for i = 1, 10 do
vx, vy = rand_v_dir()
print("Velocity: ", vx, vy)
print("Speed: ", math.sqrt(vx * vx + vy * vy))
end

Velocity:   -0.70784982398251   0.70636295676368
Speed:  1.0
Velocity:   -0.28169296961382   -0.95950459658625
Speed:  1.0
Velocity:   0.71839382297246    -0.69563662577168
Speed:  1.0
Velocity:   0.29007205509751    0.9570048081653
Speed:  1.0
Velocity:   -0.40540707321421   0.91413626171807
Speed:  1.0
Velocity:   -0.7236198731718    0.69019872439091
Speed:  1.0
Velocity:   0.31888322750977    0.94779401096069
Speed:  1.0
Velocity:   -0.64427423170525   0.76479455696325
Speed:  1.0
Velocity:   -0.66481241135881   0.74701034644996
Speed:  1.0
Velocity:   -0.65843036923729   0.75264164704463
Speed:  1.0

We can do better than this, though. This approach gives directions that are biased towards the corners, as pointed out by @JoelCornett and @nobody in the comments. One improvement would be to select a random angle between 0 and 2π, and to take the velocity vector to be a unit vector. Then the cosine of the angle will be the velocity component in the x-direction, and the sine of the angle will be the component in the y-direction (measuring the angle with respect to the positive x-axis).
This approach also has the benefit of being simpler to code:
function rand_polar_dir ()

   dir = 2 * math.pi * (math.random())

   vx = math.cos(dir)
   vy = math.sin(dir)

   return vx, vy
end

Here are ten random velocity vectors generated with the second approach:
> for i = 1, 10 do
vx, vy = rand_polar_dir()
print("Velocity: ", vx, vy)
print("Speed: ", math.sqrt(vx * vx + vy * vy))
end
Velocity:   0.093304068605003   -0.99563766038743
Speed:  1.0
Velocity:   -0.31453683190827   -0.9492452693446
Speed:  1.0
Velocity:   0.72403297094833    0.68976536371416
Speed:  1.0
Velocity:   -0.39261186353618   -0.91970425931962
Speed:  1.0
Velocity:   -0.74523744965918   0.66679917788303
Speed:  1.0
Velocity:   0.15192428057379    -0.98839213522374
Speed:  1.0
Velocity:   0.93666276755405    -0.35023257969239
Speed:  1.0
Velocity:   0.86478573695856    -0.50214104507902
Speed:  1.0
Velocity:   0.64665884247741    -0.7627793530542
Speed:  1.0
Velocity:   0.2877390096936 0.95770886092828
Speed:  1.0

For both of the above approaches, the magnitude of the velocity vector is 1. If you want to double the speed, just multiply the random vector by 2.


text:
Q: Erro de validade do certificado usado para assinar o app Google Play Console Ao realizar upload do arquivo .aab me deparei com a mensagem que a data de início do certificado usado para assinar o aplicativo não é válido. Entretanto baixei o certificado usado no menu configuração -> integridade do app -> Assinatura de apps -> Fazer download do certificado.
"Você fez upload de um APK ou Android App Bundle assinado com um certificado que ainda não é válido. Assine-o com um que esteja no período de validade."


text:
Q: Artifactory not listing all repositories in settings generation I have set up a local Artifactory installation.
Apart from the pre-existing repos, I have created a few additional ones.
However, when trying to generate settings.xml file, the drop down menus do not incorporate all existing repos.
Here is the list of existing repos:

And here are the only options available for say Releases (same goes for all other options, e.g. Snapshots, etc)

Why aren't other repos visible to these drop down menus?
UPDATE: I see now that when exporting maven settings, only virtual or remote repositories can be used. Why are local repositories excluded from this process?
(but are eligible as deploy targets in <distributionManagement> elements?)

A: When generating the Settings.xml file in Artifactory, Artifactory will only show the virtual repositories available.
This considered as the best practice, as this will allow the Artifactory Admins to change, in case needed, the used repositories in the background and the end user will need to change nothing on his end.
By default, Artifactory has 'libs-releases' virtual, for resolution of RELEASE artifacts and 'libs-snapshots' for resolution of SNAPSHOTS artifacts.
You can read more on virtual repositories in the link below:
https://www.jfrog.com/confluence/display/RTF/Virtual+Repositories


text:
Q: GeoJson to TopoJson converter with Attributes I have GeoJson file converted from .shap file. each object has arc , points and some other property . Now When i tried to converter This GeoJson file to TopoJson file with this online app  http://shancarter.github.io/distillery/  the converted TopoJson is Working Greate with D3.js But the object has only type: Polygon and arc attributes. all other attributes like id , GEOFIP etc are gone. I need these not all but at-least 2-3 attributes must need to add some more functionality to map in D3.js

A: you can convert to topojson using http://geojson.io, or http://mapshaper.org


text:
Q: RazorEngine IsolatedTemplateService is not preventing growth of number of loaded assemblies I am attempting to use the IsolatedTemplateService in RazorEngine 3.2.0.
According to http://www.fidelitydesign.net/?p=473, this should prevent an ever-increasing number of assemblies from being loaded into my main AppDomain.
This doesn't seem to be the case, however.  I am using PerfMon to monitor the number of loaded assemblies and each time I execute a template, the counter value goes up.
Repro:
1) Open perfmon and start watching the .NET CLR Loading: Current Assemblies and .NET CLR Loading: Current Appdomains counters
2) Parse a template using the IsolatedTemplateService
Results:
The "Current Appdomains" counter DOES spike up when the template is parsed, and then drops back down afterwards. It does look like a separate appdomain is being created.
The "Current Assemblies" counter just keeps going up. It does NOT drop back down at any time.
Am I reading these counters wrong? Or is the IsolatedTemplateService failing to constrain the dynamic assembly creation to the temporary AppDomain?


text:
Q: Broken cross symbol for closing in notification message After revoting on question opening or successful flag, cross symbol in the notification message is broken.
Revote for opening:

Vote for opening:

A: This issue seems to have been fixed (checked on Meta.SE, Meta.SO and one other site):

I am quite sure that the fix was related to this answer by Nick Craver:

Update: Meta has been reverted to master. We'll be at the drawing board figuring out how to fix this if anyone needs us.


text:
Q: Are Adapter and Visitor patterns appropriate for my use cases? My use case is that I am making requests to various APIs that return different external data types. Then I have to decorate the data with additional metadata that I retrieve from other APIs. Then I return a response depending on what clients want.
First I am making requests for the data, and based on those results, I am retrieving the appropriate metadata for each piece of data.
My approach so far:

*

*Call APIs and receive external types

*Convert external types to an internal interface with Adapter pattern

*Call other APIs to retrieve metadata for each data piece

*Mutate the adapted internal object with Visitor pattern

*Format the internal object appropriately for the client

I'm concerned about #3 (EDIT: I'm concerned about #4, not #3). Is using Visitor pattern on adapted internal types appropriate or is there an easier way? Would it be a good practice to create Visitor operations that each mutate the objects in sequence, in different ways? (i.e. setting fields in the list of data objects)

A: Based on our discussion in chat :

Mutate the adapted internal object with Visitor pattern

Actually your requirement can be fulfilled with Builder pattern instead of Visitor pattern because you have to build object gradually.
Visitor is behavioural pattern and it was meant for different purpose :
Similar operations have to be performed on objects of different types grouped in a structure
Related SE questions:
When would you use the Builder Pattern?
When should I use the Visitor Design Pattern?

Convert external types to an internal interface with Adapter pattern

Adapter is a structural pattern. If you want to convert external interface to internal interface (structure), you can use Adapter pattern.
If you want to transform external object into internal object, you can achieve it without any pattern. You just need a Transform function ( on lines of Builder).
Have a look at related SE question ( object transformation without pattern):
How to prune an object of some of its fields in Java?


text:
Q: What does TGZ mean? I can recall my professor saying it means "Tar-able Gzip." I'm searching it in Google and couldn't find it. I know what Tar and Gzip are. I also know what a TGZ is, but I want to know the meaning of the acronym. I'm really curious whether it is correct or not.
Thanks!

A: tgz is often used as a file name suffix of tar archives that have been compressed using gzip, possibly by compressing it at creation time using tar -cz.
It is just a contraction of tar.gz, which would be the suffix you would get if you first created a tar archive and then compressed it with gzip.
On filesystems that enforces the old "8.3" naming rules of DOS, using tgz as the file name suffix would enable one to store these files too.
If it "means" anything, it means "gzip-compressed tar archive". Just remember that in Unix, file name suffixes do not determine the format of the contents (it's just a help to the user).  It used to be that many web browsers, for example, would download and decompress files while retaining the original name and suffix.

A: tgz is the extension of file which is archived by tar and compress by gzip.


text:
Q: Not able to submit new question in Opera in ubuntu ! I'm trying to ask a new question in stack-overflow through the Opera browser installed on my ubuntu 10.10. But I'm not able to press the submit button Opera. Everything works fine with firefox and IE browsers.

A: Taking a look, there was some Opera-specific code in the tag plugin that suppressed submission when you press enter
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
    if (blockSubmit) {
        blockSubmit = false;
        return false;
    }
});

Apparently newer versions of Opera handle this differently.
I removed the opera "fix" but there is a side-effect; pressing enter will submit the form in most cases (unlike all other browsers). You will need to select autocomplete tags using your mouse and not the keyboard. Well, technically you can use tab then shift+tab but that's a bit of a workaround.
Shrug. Such is the delightful, delightful world of Opera.


text:
Q: Is there a way to easily create release notes with the list of changes (commit) and merge requests on Gitlab? I have a Gitlab project with a repository containing submodules (subrepo). Is there an easy way to generate a release note containing the list of changes and merge requests by bundles that occurred on a certain date over a specific period time?
Thank you in advance


text: Q: Create procedure in Oracle to populate table from SSRS parameter I have been running a report in Oracle for my customer where they provide a list of id numbers. I import the id numbers into a table and run a query which includes this table.  However, the customer would like the ability to run this report. I can create the report in SSRS and take a few id numbers, but not the entire list.  I would like to know if I can create a procedure that would check the table for data, delete if it exists, then import the data from the parameter in SSRS into the table which SSRS can then run the query which includes the newly populated table.  How would such a procedure look, and can that be called in SSRS with the parameter to include the id numbers that will be imported. I had thought of creating a temp table and populating it, but was advised that Oracle does not use temp tables, and I already have the table created within the database.


text:
Q: How do you handle optional file uploads with Sails JS? I have a form that a user can submit with or without a file.
The form:
<form method="post" action="/file/upload" enctype="multipart/form-data">
    <input type="file" name="media" />
    <input type="submit" value="Submit" />
</form>

The Controller
module.exports = {
  upload: function (req, res) {
    // Check if any files were uploaded
    if (!req.file('media')._files[0]) {
        return res.send('no file given!');
    }

    req.file('media').upload({
      dirname: '/tmp/uploads'
    },function whenDone(err, uploadedFiles) {
      if (err) {
        sails.log.error('Error uploading file', err);
      }
      res.send('thanks for your file');
    });
  }
};

If they don't upload a file, I get the following error. There doesn't seem to be a way to catch it or suppress it unless I go into the skipper code and comment out the error throwing. How can I submit the form without attaching a file and not crash the app?
Error: EMAXBUFFER: An Upstream (`NOOP_media`) timed out before it was plugged into a receiver. It was still unused after waiting 4500ms. You can configure this timeout by changing the `maxTimeToBuffer` option.

I've been through a number of forums and blog posts but nothing has helped so far.

A: You have to do the check inside the .upload(). Remove the if statement.
req.file('media').upload({
  dirname: '/tmp/uploads'
}, function whenDone(err, uploadedFiles) {
  if(uploadedFiles.length === 0){ // Check the number of files uploaded.
    return res.send('no file given!');
  }
  if (err) {
    sails.log.error('Error uploading file', err);
  }
  return res.send('thanks for your file');
});

A: When a file input is left empty it seems to act like a normal text input and it will be empty so you can try checking for something like this:
 if(typeof req.param('media') !== 'undefined' && req.param('media').length == 0)) {
        return res.send('no file given!');
   }else {  //handle the file upload }

A: You could abort the stream with noMoreFiles().
const skipperUpstream = req.file('media');

// skipperUpstream._files is an internal array containing the uploaded files for key `media`
// here i just expecting a single file, or none
const file = skipperUpstream._files[0];

if (!file) {
  // `skipperUpstream.__proto__` is `Upstream`. It provides `noMoreFiles()` to stop receiving files.
  // It also clears all timeouts: https://npmdoc.github.io/node-npmdoc-skipper/build/apidoc.html#apidoc.element.skipper.Upstream.prototype.noMoreFiles
  skipperUpstream.noMoreFiles();
  return;
}

skipperUpstream.upload(/* your stuff */);


text:
Q: Evaluate boolean expression in a string in Javascript without eval I have a string that contains Boolean logic, something along the lines of:
((true && true) || false && !true)

What is the best way in Javascript to safely evaluate this string to get the boolean result? I would like to avoid using eval().

A: I wrote this boolean string parser for another question:

var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "((true && true) || false && !true)";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";

console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));

function parseBoolStr(str) {
  var expressions = {};
  var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
  var expressionIndex = 0;
  str = str.trim();
  while (str.match(expressionRegex)) {
    var match = str.match(expressionRegex)[0];
    var expression = 'boolExpr' + expressionIndex;
    str = str.replace(match, expression);
    match = match.replace('(', '').replace(')', '');
    expressions[expression] = match;
    expressionIndex++;
  }
  return evalBoolStr(str, expressions);
}

function evalBoolStr(str, expressions) {
  var conditions = str.split(' ');
  if (conditions.length > 0) {
    var validity = toBoolean(conditions[0], expressions);
    for (var i = 1; i + 1 < conditions.length; i += 2) {
      var comparer = conditions[i];
      var value = toBoolean(conditions[i + 1], expressions);
      switch (comparer) {
        case '&&':
          validity = validity && value;
          break;
        case '||':
          validity = validity || value;
          break;
      }
    }
    return validity;
  }
  return 'Invalid input';
}

function toBoolean(str, expressions) {
  var inversed = 0;
  while (str.indexOf('!') === 0) {
    str = str.replace('!', '');
    inversed++;
  }
  var validity;
  if (str.indexOf('boolExpr') === 0) {
    validity = evalBoolStr(expressions[str], expressions);
  } else if (str == 'true' || str == 'false') {
    validity = str == 'true';
  } else {
    validity = window[str]();
  }
  for (var i = 0; i < inversed; i++) {
    validity = !validity;
  }
  return validity;
}

function a() {
  return false;
}
function b() {
  return true;
}
function c() {
  return true;
}
function d() {
  return false;
}

Functions a, b, c and d can, and should, be removed. Just an example.
Usage: parseBoolStr('((true && true) || false && !true)');

A: You can use Angular $parse service. Angular parsing expressions, without eval them.
Example of use:
var x=$parse(' ((true && true) || false && !true) ')()
console.log(x)  // will return true

ReadMore:

*

*https://docs.angularjs.org/guide/expression

*https://docs.angularjs.org/api/ng/service/$parse

var a=angular.module('app',[])
a.run(function($parse){
  alert($parse('true || false || true || false')())
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app=app>


text:
Q: Local variable vs data. Huge loss in performance I have a VueJS and Cesium project that is having a performance issue in regards to a degradation in frame-rate. I know where the issue is, yet, I don't know why or how to work around it.
export default {

    name: "Map",

    components: { ... },

    data: function () {
        return {
            viewer: {}
        }
    },

    methods: { ... },

    mounted() {

        // 150-200 FPS; but no access to the viewer object outside of this component.
        let viewer = new Viewer('cesiumContainer');

        // 20-30 FPS; but yields me the access I need for other components to utilize.
        this.viewer = new Viewer('cesiumContainer');

        ... rest of my source code ...
    }

I can maintain well above 150-200 FPS with all the content I need to display versus an abysmal 20-30 FPS. I have eliminated the rest of my source code and simply have just tried rendering the Cesium world using just the above source code and this still happens - which is why I believe this is the root of my entire problem. But I do not understand why is this.viewer causing such a huge performance hit.... What can I do to resolve the problem?
EDIT #1:
Here is a sandbox incorporating Vue and Cesium:
https://codesandbox.io/s/peaceful-satoshi-1mog9
Using the search function at the top right, go to "Grand Canyon National Park, AZ" and use the 'Ctrl' and mouse to angle the camera to see the terrain. You should get something like this (note the low FPS and sluggish response rate):

However, if I do the same thing making viewer a localized variable, the response rate and FPS is far superior:

A: From anatoly's comment:
Assigning to a prop in the data section automatically makes your object and all its props reactive and if these props change their values frequently this can impact on a performance.
To avoid this, create your variable outside of the export default {} object.
It will look like this:
var myCesiumObj = null

export default {
    name: "",
    components: {...},
    mounted: function() {
        myCesiumObj = new Viewer('cesiumContainer');
    },
    data() {
        return {
            /* Do not put it here */
        }
    },
    methods: {...},
}

Note you will not need to use this. to access the variable, it will be available everywhere in this component.


text:
Q: How to insert multi data form to database I'm trying to insert some files and json data to database with django. (I'm totally new to Django, thus, please have mercy :) )
My model is as follows :
class Files(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   file_type = models.ForeignKey(to=FileType)
   file = models.FileField(upload_to='media/%Y/%m/%d/', blank=True)

   def __str__(self):
       return self.file_type.name

The view where I fetch the data is as follows :
def save_user(request):
    user = json.loads(request.POST.get("user"))
    for file_key in request.FILES.keys():
        file = Files()
        file.file_type = FileType.get_by_key(file_key.split('/')[1])
        file.file = request.FILES[file_key]
        file.save()

    return HttpResponse("User saving...")

And the data that I get in request is as follows :
request.FILES
<MultiValueDict: {'file/ID_CARD': [<InMemoryUploadedFile: check.png (image/png)>], 'file/STATUTES': [<InMemoryUploadedFile: pictures.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}>

and user
{'companyName': 'Autralis', 'btwNumber': '84515', 'address': 'Hundelgemsesteenweg 575', 'country': 'Belgium', 'zipcode': '9820', 'place': 'Merelbeke', 'phone': '+32 486386069', 'mobilePhone': '+32 486386069', 'firstName': 'Maida', 'lastName': 'Mesanovic', 'email': 'maida@autralis.com', 'userName': 'Maida', 'password': '123', 'confirmPassword': '123', 'files': [{'file_type': 'LETTER_HEAD', 'values': {'active': False, 'fileName': 'Blank letterhead', 'file': None}}, {'file_type': 'COMPANY_PICTURE', 'values': {'active': False, 'fileName': 'Company photo', 'file': None}}, {'file_type': 'ID_CARD', 'values': {'active': True, 'fileName': 'check', 'file': {}}}, {'file_type': 'STATUTES', 'values': {'active': True, 'fileName': 'pictures', 'file': {}}}], 'terms': True, 'emailNotifications': True, 'smsNotifications': True}

How can I add it to the database?


text:
Q: Does RecycledViewPool works fine when I set it into different RecyclerView in different Activity? When we use RecyclerView in RecyclerView, like Google play App, we can set same RecycleredViewPool to both outer and inner RecyclerView.
What if two RecyclerView in different Activities? Is RecycledViewPool still works fine? These two views have the same adapter.
I had tried, and onCreateView has called in the second activity, but I think that because I miss something.
The reason of I doing this is for performance. Every time onCreateView called, lots of time will cost, because LayoutInflater parse xml.
Otherwise, leave this question on the other side, how to build a high performance list page, just like Youtube, their FPS is very high.

A: You should not use RecycledViewPool across multiple Activities.
The Views inside have a reference to their host Context and wouldn't work properly when being used in a different Context from where they where created.
Additionally there would be a memory leak by keeping both Activities alive, since the pool references the views, referencing the Activities.
To accomplish this in the first place you might have a static reference to the RecycledViewPool. This should be a dead giveaway that it might not be a good idea as you are holding static references to Views, and thus indirectly to their Contexts.

TL;DR new Activity means new View pool.


text:
Q: The cardinal of some set of cosets is countable Let $G$ be an abelian group and $(G_n)_{n \in \mathbb{Z}}$ be a family of subgroups of $G$ with $G_{n+1} \subset G_n$ for any $n$ and $G=\bigcup_{n \in \mathbb{Z}} G_n$. In addition, we suppose that the index $[G_n:G_{n+1}]$ of $G_{n+1}$ in $G_n$ is finite.
How prove that there are only countably many cosets of $G_j$ in $G$ ?

A: The coset space $G/G_j$ can be written as $\bigcup_{n\geq j} G_n/G_j$, a countable union of finite sets.

A: Hint: if you let $H_i$ = $G_{j+i}/G_j$ for $i = 0, 1, \ldots$, then $(H_i)$ is an ascending chain of finite groups whose union is isomorphic to $G/G_j$.


text:
Q: Spark Dataframe join Exception thrown in awaitResult I'm trying to join two Dataframes, one is around 10 million records and the other is about 1/3 of that. Since the small DataFrame fits comfortably in the executor's memory, I perform a broadcast join and then write out the result:
val df = spark.read.parquet("/plablo/data/tweets10M")
  .select("id", "content", "lat", "lon", "date")
val fullResult = FilterAndClean.performFilter(df, spark)
  .select("id", "final_tokens")
  .filter(size($"final_tokens") > 1)
val fullDFWithClean = {
  df.join(broadcast(fullResult), "id")
}
fullDFWithClean
    .write
    .partitionBy("date")
    .mode(saveMode = SaveMode.Overwrite)
    .parquet("/plablo/data/cleanTokensSpanish")

After a while, I get this error:
org.apache.spark.SparkException: Exception thrown in awaitResult:
at org.apache.spark.util.ThreadUtils$.awaitResultInForkJoinSafely(ThreadUtils.scala:215)
at org.apache.spark.sql.execution.exchange.BroadcastExchangeExec.doExecuteBroadcast(BroadcastExchangeExec.scala:125)
at org.apache.spark.sql.execution.InputAdapter.doExecuteBroadcast(WholeStageCodegenExec.scala:231)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeBroadcast$1.apply(SparkPlan.scala:124)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeBroadcast$1.apply(SparkPlan.scala:124)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:135)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:132)
at org.apache.spark.sql.execution.SparkPlan.executeBroadcast(SparkPlan.scala:123)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.prepareBroadcast(BroadcastHashJoinExec.scala:98)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.codegenInner(BroadcastHashJoinExec.scala:197)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.doConsume(BroadcastHashJoinExec.scala:82)
at org.apache.spark.sql.execution.CodegenSupport$class.consume(WholeStageCodegenExec.scala:153)
at org.apache.spark.sql.execution.ProjectExec.consume(basicPhysicalOperators.scala:36)
at org.apache.spark.sql.execution.ProjectExec.doConsume(basicPhysicalOperators.scala:68)
at org.apache.spark.sql.execution.CodegenSupport$class.consume(WholeStageCodegenExec.scala:153)
at org.apache.spark.sql.execution.FilterExec.consume(basicPhysicalOperators.scala:88)
at org.apache.spark.sql.execution.FilterExec.doConsume(basicPhysicalOperators.scala:209)
at org.apache.spark.sql.execution.CodegenSupport$class.consume(WholeStageCodegenExec.scala:153)
at org.apache.spark.sql.execution.FileSourceScanExec.consume(DataSourceScanExec.scala:141)
at org.apache.spark.sql.execution.FileSourceScanExec.doProduceVectorized(DataSourceScanExec.scala:392)
at org.apache.spark.sql.execution.FileSourceScanExec.doProduce(DataSourceScanExec.scala:315)
.....

There's this  question that addresses the same issue. In the comments, it's mentioned that increasing spark.sql.broadcastTimeout could fix the problem, but after setting a large value (5000 seconds) I still get the same error (although much later, of course).
The original data is partitioned by date column, the function that returns fullResult performs a series of narrow transformations and filters the data so, I'm assuming, the partition is preserved.
The Physical Plan confirms that spark will perform a BroadcastHashJoin
*Project [id#11, content#8, lat#5, lon#6, date#150, final_tokens#339]
+- *BroadcastHashJoin [id#11], [id#363], Inner, BuildRight
:- *Project [id#11, content#8, lat#5, lon#6, date#150]
:  +- *Filter isnotnull(id#11)
:     +- *FileScan parquet [lat#5,lon#6,content#8,id#11,date#150]
Batched: true, Format: Parquet, Location:
InMemoryFileIndex[hdfs://geoint1.lan:8020/plablo/data/tweets10M],
PartitionCount: 182, PartitionFilters: [], PushedFilters:
[IsNotNull(id)], ReadSchema:
struct<lat:double,lon:double,content:string,id:int>
   +- BroadcastExchange
HashedRelationBroadcastMode(List(cast(input[0, int, true] as bigint)))
      +- *Project [id#363, UDF(UDF(UDF(content#360))) AS
 final_tokens#339]
     +- *Filter (((UDF(UDF(content#360)) = es) && (size(UDF(UDF(UDF(content#360)))) > 1)) && isnotnull(id#363))
        +- *FileScan parquet [content#360,id#363,date#502] Batched: true, Format: Parquet, Location: InMemoryFileIndex[hdfs://geoint1.lan:8020/plablo/data/tweets10M], PartitionCount: 182, PartitionFilters: [], PushedFilters: [IsNotNull(id)], ReadSchema: struct<content:string,id:int>

I believe that, given the size of my data, this operation should be relatively fast (on 4 executors with 5 cores each and 4g RAM running on YARN in cluster mode).
Any help is appreciated

A: In situations like this, the first question is how big is the dataframe you are trying to broadcast? It's worth estimating its size (see this SO answer and this also).
Note that Spark's default spark.sql.autoBroadcastJoinThreshold is only 10Mb so you are really not supposed to broadcast very large datasets.
Your use of broadcast takes precedence and may be forcing Spark to do something it otherwise would choose not to do. A good rule is to only force aggressive optimization if the default behavior is unacceptable because aggressive optimization often creates various edge conditions, like the one you are experiencing.

A: This can also fail if spark.task.maxDirectResultSize is not increased. It's default is 1 megabyte (1m). Try spark.task.maxDirectResultSize=10g.


text:
Q: Рассчитать траекторию пули Пишу игру и нужно рассчитать траекторию полета пули. Пишу для тачскрина и траектория создается в зависимости от точки касания, позиции пальца на экране, но получается что работает только на вторые 45 градусов из первой половины экрана, вот как выглядит.
А мне нужно, что бы стреляло в любую точку. Помогите, пожалуйста, как рассчитать? Вот как я сделал, что бы оно так летало:
angle = Math.atan((y - gameView.shotY) / (x - gameView.shotX)); //позиция начальная - координата косания

x = (int)(x + xSpeed * Math.cos(mAngle));
y = (int)(y + ySpeed * Math.sin(mAngle));

Достиг того эффекта, а нужно что бы равномерно летело. Заранее спасибо!
A: У меня выдавало странные результаты пока не конвертнул тип данных для x, y к double.
проблема в неявном конвертировании типов в первой формуле. попробуй так:
angle = Math.atan ( (double) (y - viewY) / (x - viewX) ) ;

UPDATE: что, где, когда:
Если я правильно понял то происходит следующее (y - viewY) и (y - viewY) int. При делении результат неявно конвертируется к типу int (здесь и отрезается дробная часть). После чего он неявно конвертируется к типу double для передачи в функцию atan.
проверить можно так:
    System.out.println ( 5 / 3 ) ;
    System.out.println ( (double) 5 / 3 ) ;

A: Помимо angle = Math.atan ( (double) (y - viewY) / (x - viewX) ) ;
надо (int) заменить Math.round
x = Math.round(x + xSpeed * Math.cos(mAngle));
y = Math.round(y + ySpeed * Math.sin(mAngle));


text:
Q: following constructor parameters did not have matching fixture data : DbContextOptions'1options    public class StudentService
    {

}

I have a student class where I am accessing MsDbContext to do entity framework related work.In the above code, options are coming from abstractDbBasedService.
AbstractDbBasedService :
public class AbstractDbBasedService

}

Now, I have a test class where I am accessing all the above services.
StudentTestClass :
    public class StudentServicesTests : AbstractDbBasedService
    {

}
       [Fact]
        public void Assert_CreatedStudent_WhenStudentParemeterInvalid()
        {

        }

}

when I am trying to the run the tests, It is giving me the error - The following constructor parameter did not have matching fixture data:DbContextOptions'1 options. Please help me on this.


text:
Q: how to use the userVariables in Testcafe using the CLI I am trying to use the new userVariables option, which is newly introduced in Testcafe's recent version.
I was wondering if the userVariables can be used through the CLI.
I understand that the variables could be added to the testcaferc.json as mentioned in the documentation:
https://testcafe.io/documentation/402638/reference/configuration-file#uservariables
I couldn't figure out a way to add or modify the variables and values through the command line.
Thanks in advance for any help/hints.

A: You can set up custom user variables only in the configuration file. Please refer the following topic for more info: https://testcafe.io/403403/release-notes/framework/2021-9-8-testcafe-v1-16-0-released#support-for-custom-user-variables-in-the-configuration-file
Also, you might want to track the following issue in the TestCafe GitHub repository: https://github.com/DevExpress/testcafe/issues/6621


text:
Q: Plotting the PMF of the Poission Distribution of Columns from a csv Dataframe I am trying to finish writing a function that uses plt.bar function to plot a pmf of a poisson distribution.
I am a beginner and I don't understand how plt.bar works even after looking at https://pythonspot.com/matplotlib-bar-chart
def plot_poisson(df, col='open', n_pts=100):
fig, ax = plt.subplots(figsize=(10, 5))
plt.bar
plt.xlabel("X")
plt.ylabel("P(X|\mu)")
plt.title("Poisson PMF")
return ax

A: So if I understood correctly, you want to draw n_pts numbers from a Poisson distribution whose average number of events per interval is equal to the mean value of your data (from the dataframe column).
And then you want to plot the distibution.
If so, you can do it easily with numpy, which provides functions to draw random numbers from distributions. For example, numpy.random.poisson draws numbers from a Poisson distribution.
It's much easier to use plt.hist instead of plt.bar.
With bar you must choose a bin size and the bin positions, count by yourself how many data you have in each bin, and plot the histogram. plt.hist does all this for you.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def plot_poisson(df, col='open', n_pts=100):
    lm = df[col].mean() #get the mean value of your data
    poisdata = np.random.poisson(lm, n_pts)
    plt.hist(poisdata, density=True, alpha=0.5)
    plt.xlabel("X")
    plt.ylabel("P(X|\mu)")
    plt.title("Poisson PMF")
    plt.show()

An example picture produced by this function:

A: Try this one:
 def plot_poisson(df, col='open', n_pts=100):
    pts=np.arange(n_pts)
    fig,ax=plt.subplots(figsize=(10,5))
    lm = df[col].mean() #get the mean value of your data
    poisdata = np.random.poisson(lm)
    ax.bar(pts,poisdata.pmf(pts))
    ax.set_xlabel("X")
    ax.set_ylabel("P(X|\mu)")
    ax.set_title("Poisson PMF")
    return ax


text:
Q: annotation.kotlin_module:Module was compiled with an incompatible version of Kotlin.Binary version of its metadata is 1.8.0,expected version is 1.6.0 Due to "duplicate class kotlin.time.jdk8.DurationConversionsJDK8Kt found in modules jetified-kotlin-stdlib-1.8.0" error , I have updated  kotlinVersion = "1.6.0" to kotlinVersion = "1.8.0".
But now i am getting this error /Users/abc/.gradle/caches/modules-2/files-2.1/androidx.annotation/annotation-jvm/1.6.0-beta01/a7257339a052df0f91433cf9651231bbb802b502/annotation-jvm-1.6.0-beta01.jar!/META-INF/annotation.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.8.0, expected version is 1.6.0..
Tried everything but nothing works.
If anyone has solution for this, Please share with us. Thank you.


text:
Q: Can't connect to Azure from OPC UA client I'm pretty new to Java and I'm trying to create an OPC UA client that can send information to an Azure IoT Hub.
Everytime the OPC UA client reads a value from the OPC UA server, that value and the name of the node must be sent to Azure IoT Hub.
I followed this tutorial https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-java-java-getstarted#comments-container and I successfully created a simulated device that is able to connect to the Hub and send messages to it.
On the other hand, I have working OPC UA client that can connect with the OPC UA server and read values from it.
I used the code in the example I linked above to modify my OPC UA client to send messages to the Hub in the read operation. I'm using the same connection string and device Id that I used in the tutorial.
I'm able to build and run the modified OPC UA client, but the messages does not arrive to the Hub whatsoever.
I noticed that the execution gets stuck in the statement "client_azure.open()" for about 10 minutes, then it continues the execution, so I believe that it is not able to open the connection to the Hub, but I don't know why.
My code would be like this:
public class OPCUAclient {  //main class of the OPC UA client

    private static String connString = "HostName=XXXXX;DeviceId=YYYYYY;SharedAccessKey=ZZZZZZZ";
    private static IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
    private static String deviceId = "YYYYYYY";
    private static DeviceClient client_azure;
    public static void main(String[] args) throws Exception, IOException, URISyntaxException {
        client_azure = new DeviceClient(connString, protocol);
        client_azure.open();        //Here is where the application takes like 10 minutes  to react
           .
           .
           .
           azure_client.close()
     }

    //OPC UA code
   .
   .
   .
   //inside a method of the OPC UA code, I execute the following

   MessageSender sender = new MessageSender();
     ExecutorService executor = Executors.newFixedThreadPool(1);
     executor.execute(sender);
     //System.out.println("Press ENTER to exit.");
   //System.in.read();
   executor.shutdownNow();

   .
   .
   .

   //At the end of the OPCUAclient class, the following methods are defined

    private static class TelemetryDataPoint {
           public String deviceId;
           public String node;
           public int value;
           TelemetryDataPoint(int value_t, String node_t){
                 value = value_t;
                 node=node_t;
            }
            public String serialize() {
                  Gson gson = new Gson();
                  return gson.toJson(this);
             }
      }
      private static class EventCallback implements IotHubEventCallback
      {
            public void execute(IotHubStatusCode status, Object context) {
                  System.out.println("IoT Hub responded to message with status: " + status.name());

                  if (context != null) {
                        synchronized (context) {
                              context.notify();
                        }
                  }
             }
      }

      private static class MessageSender implements Runnable {
            public int value;
            public String node;  //NodeId
            MessageSender(){
                 value = 1; //value_azure;
                 node = "Blue"; //node_azure;
            }
           public void run()  {
                  try{
                         TelemetryDataPoint telemetryDataPoint = new TelemetryDataPoint(value, node);
                         telemetryDataPoint.deviceId = deviceId;
                         String msgStr = telemetryDataPoint.serialize();
                         Message msg = new Message(msgStr);
                         System.out.println("Sending: " + msgStr);
                         Object lockobj = new Object();
                         EventCallback callback = new EventCallback();

                         client_azure.sendEventAsync(msg, callback, lockobj);
                         synchronized (lockobj) {
                               lockobj.wait();
                }
               Thread.sleep(1000);
                } catch (InterruptedException e) {
                          System.out.println("Finished.");
                }
         }
     }
}

Any idea on what is wrong with my code?
Thanks in advance


text:
Q: get core data latest -id and give -(+1) for new insert I have coredata user table and have inside
user
id (int32)
name (string)
I want to look firstly latest id and I want to do let newid = latestid(from user table) - (-1) for example;
My user table have
id = 0 name = Mary
id = -1 name = john
I want new insert id must be -2

How can I do it ?

My codes under below.
 let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "user")
        let sortDescriptor = NSSortDescriptor(key: "id", ascending: true)
        fetchRequest.sortDescriptors = [sortDescriptor]

        var newid = Int32()

        do {
            let result = try context.fetch(fetchRequest).last as! user!
            if result != nil {
                if Int((result?.id)!) < 0 {
                    let lw = Int((result?.id)!)
                    newid = Int32(Int(lw - (1)))
                }else{
                    newid = Int32(Int((result?.id)!) - 1)
                }
            }
        } catch let error as NSError {
            NSLog("Error \(error)")
        }

        let Add = NSEntityDescription.insertNewObject(forEntityName: "user", into:context) as! user
        Add.id = Int32(newid)
        Add.name = name.text
            (UIApplication.shared.delegate as! AppDelegate).saveContext()

     print(newid)

When I try that codes , first time doing id = 0 true, after I try again gives id -1 true , but when I try more more gives id -1 all of them. must be -2,-3,-4,-5 etc..

A: Finally I found solition
use ascending: false  and change only
if result != nil {
                if Int((result?.id)!) < 0 {
                    newid = Int((result?.id)!)
                }else{
                    newid = 0
                }
  newid = Int((result?.id)!) - (+1)


text:
Q: SQL: Changing numeric date to "Date" My date variables are Numeric(37) in the format (20160404,20160405,...). Following other questions I have tried the following,
select convert(datetime, date_var)

with error Column datetime does not exist.
select convert(date, date_var)

same error as above.
Also tried,
select convert(date, convert(float, date_var))

with the same error.
select cast(convert(VARCHAR, date_var) as datetime)

gives a similar error Column "VARCHAR" does not exist
I apologize, my knowledge of SQL is just a few weeks old and if I needed to do further research before posting this question. I feel I am making some error, such as using wrong function for a wrong database. Can anyone please help me?

A: I would just use cast():
select convert(date_var as datetime)

I'm not sure if Vertica supports the particular conversion, but this should work:
select convert(date_var as varchar(255))

cast() is the ANSI standard function for converting between different types.
In Vertica, you can also do:
select date_var::varchar(255)

This is a syntax inherited from Postgres.
For your actual problem, I wouldn't be surprised if you had to convert twice:
select (date_var::varchar(255))::datetime

A: You mean this, I suppose:
WITH
input(datenum) AS (
          SELECT 20180602
UNION ALL SELECT 20180603
)
SELECT datenum::VARCHAR(16)::DATE FROM input;

Output is:
datenum
2018-06-02
2018-06-03

A: it depends what you are using to run this statement.
i guess an easy outside the box approach would be to run a script. like the one bellow.
For the conversion of numeric value to character value try the following code
PROC SQL;

  CREATE TABLE y AS

  SELECT PUT(x.subjid, 6.) AS subjid,

         PUT(x.date, YYMMDD10. ) AS date

  FROM x;

QUIT;

or if you need to do a select statement only..
SELECT CONVERT(DATETIME,CONVERT(VARCHAR(8),NumberDate),112)

or if u need to declare a new numeric and set the date format of x
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), @x));


text:
Q: How to extract only Message from the system eventvwr I am trying to extract only the Message from the system eventvwr for a specific ID, but when i try using the below command i am getting the entire mesaage which is very long to print or send over mail.
Need help in trimming the message or extract only some part of the message.
Get-EventLog -LogName Application -InstanceId 12510 -Newest 1 | Select-Object -Property Message | Out-GridView

A: Try it this to get the whole message
(Get-EventLog -LogName Application -Newest 1).Message
# Results
<#
Windows Management Instrumentation Service subsystems initialized successfully
#>

You can parse this into objects to make it more readable if there is more data.
Now, sending this Out-GridView will be again, one long string. It does not have a text wrapping feature.
What I am showing is dumping this to the console (ISE/VSCode/CLI). So, if you want it all readable, then dump it to the console or push it out to Notepad or the like, or cover the text to an object and format as needed.
Here is another approach you can use to break this up for viewing. Remember EV data is just XML. So, just parse it:
$event         = Get-WinEvent -LogName Application -MaxEvents 1
[xml]$xmlEvent = $event.ToXml()
$xmlevent.Event.EventData.Data |
Out-GridView

Update as per your comment and my response to that
Extracting text from between X and Y thing is a very common thing in all languages. This is not unique to PowerShell. Regular expressions (RegEx), is the q&d (Quick and Dirty) of getting this done. For example:
[regex]::matches( 'The Exchange web service request <message> GetAppManifests </message> succeeded.' , '(?<=<message>\s+)(.*?)(?=\s+</message>)' ).Value
# Results
<#
GetAppManifests
#>

If the file is XML, JSON, then that is what the XML and JSON cmdlets are there for.
Update as per your specific event ID comment
Again, just an example - tweak as needed.
$result = Get-WinEvent -FilterHashtable @{LogName="Security";Id=4648} -MaxEvents 1 |
ForEach-Object {
    # convert the event to XML and grab the Event node
    $eventXml = ([xml]$_.ToXml()).Event
    # create an ordered hashtable object to collect all data
    # add some information from the xml 'System' node first
    $evt = [ordered]@{
        EventDate = [DateTime]$eventXml.System.TimeCreated.SystemTime
        Computer  = $eventXml.System.Computer
    }
    $eventXml.EventData.ChildNodes | ForEach-Object { $evt[$_.Name] = $_.'#text' }
    # output as PsCustomObject. This ensures the $result array can be written to CSV easily
    [PsCustomObject]$evt
}

# output to screen
$result


text:
Q: Creating elements appended at different levels in an HTML file using JAVASCRIPT update_5.enter().append("div")

    .append("form").merge(update_5)
    .attr("action",d => d.market)
    .attr("target","_blank")
    .style("width","100%")
    .style("height","282")

    .append("input").merge(update_5)
    .attr("type","submit")
    .attr("target","_blank")
    .style("width","100%")
    .attr("value","Jogo Betfair")

    .append("iframe").merge(update_5)
    .attr("src",d => valorparaiframe(d.value))
    .style("width","100%")
    .style("height","282");

The result is one element becoming the child of the other:

     <form>
           <input>

I'm looking to create several totally different appendages:

     <form>
           <input>

How should I go about this?
I tried to use append and appendChild but the result was not positive to.

A: Use:
const div = update_5.enter().append("div")

div.append("form").merge(update_5)
    .attr("action",d => d.market)
    .attr("target","_blank")
    .style("width","100%")
    .style("height","282")

    .append("input").merge(update_5)
    .attr("type","submit")
    .attr("target","_blank")
    .style("width","100%")
    .attr("value","Jogo Betfair")

div.append("iframe").merge(update_5)
    .attr("src",d => valorparaiframe(d.value))
    .style("width","100%")
    .style("height","282");

A: If you want a pattern like this that "body > div > form > input". Plus, you want to add iframe Element as a child of div. You can do this easily by using appendChild() method in javascript. In this code, i make iframe Element as the last child of div. You can put iframe Element before any child element with the help of insertBefore() method.
// Creating some Elements
const div_node = document.createElement("div");
const form_node = document.createElement("form");
const input_node = document.createElement("input");
const iframe_node = document.createElement("iframe");
const body_element = document.getElementsByTagName("body")[0];

// Appending new created div Element inside the body tag of html
body_element.appendChild(div_node);
// Appending the form Element inside the div
div_node.appendChild(form_node);
// Appending the input Element inside the form
form_node.appendChild(input_node);
// Appending the iframe Element inside the div as the last child, not the child of input
div_node.appendChild(iframe_node);


text:
Q: Problem with crontab My script which starts a process and writes the PID of that process to file. This works
as it's supposed to when I execute it from shell:
process & echo $! > /home/xxx/PIDs/process.pid

But when I let cron do that, the process is executed but the PID file is missing.
This is weird to me. What could be wrong?
The cronjob is a simple @reboot trigger. I tried, as Jeff Schaller mentioned,
*/10 * * * * /home/xxx/bin/process & echo $! > /home/xxx/PIDs/process.pid

but this does not work.

A: To me it sounds like the user your cron job runs as, does not have permission to write the PID-file to /home/xxx/PIDs/.
This could be the case if e.g. /home is mounted over NFS for example, or perhaps due to things like SELinux.
Try checking local e-mail. In most setup's cron sends error to the local root user by e-mail.
It may also be worth to try running the command as user account xxx by specifying this in the crontab, or login as user xxx and run crontab -e to edit the 'personal' crontab of user xxx.

A: Sry I said scripts are at subfolder on exHDD thats not correct, they are stored in /home/subfolder but doesn't matter anymore.
reinstalling cron does it. Can't figure out why...