Q: Unexpected result at summing numbers using a while loops in console application I am trying to make a program to sum numbers until the user enter OK.
The program make the sum, but return a bad result.
i'm not sure where is my error...
int sum = 0;
Console.WriteLine("Enter number:");
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
    {
       sum += num;
    }
Console.WriteLine(sum);

A: you don't keep the number the use enter in the while loop.
you need to input the readline to a variable.
var num = Console.Readline();
sum += num; //parse first

A: Inside your while loop you need to update num:
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
    num = Int32.Parse(Console.ReadLine());
    sum += num;
}

Also just as a note, if you need your program to be a little safer, you can you use the following:
int num;
if(Int32.TryParse(Console.ReadLine(), out num)) {
    //do something..
}
else {
    //do something else.. like end program, throw exception etc.
}

Int32.TryParse:

Converts the string representation of a number to its 32-bit signed
  integer equivalent. A return value indicates whether the conversion
  succeeded

This way you can do something in the instance that the input string was not a valid conversion.  Example: if someone input cat, which can not be converted to an int, it would crash your program without the TryParse.

A: You need to input the number once per iteration, and store it each time. So each value retrieved from Console.ReadLine() needs to be captured in an assignment statement, then converted to a number if it is not "OK".
I think you're after this:
int sum = 0;
string input;

Console.WriteLine("Enter number: ");
while ((input = Console.ReadLine()) != "OK")
{
    int inputNum = Convert.ToInt32(input);
    sum += num;

    Console.WriteLine("Enter number: ");
}

The statement (input = Console.ReadLine() assigns the user input to the input variable, then the assignment statement returns the value of input. Then that value is compared against OK.
An alternative way to get input, then check it is:
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
while (input != "OK")
{
    ...
    Console.WriteLine("Enter number: ");
    input = Console.ReadLine()
}

A: int sum = 0;
Console.WriteLine("Enter number:");
int num = int.Parse(Console.ReadLine());
while (sum< num)
{
     sum++;
}
Console.WriteLine(sum);


Q: Is it possible to capture Android Screen multiple times simultaneously? Is it possible to capture Android screen multiple times with different settings on Android 13? I've tried two approaches:

*

*Create two media projections using the same Activity.RESULT_OK and intent

*Create one media projection and two virtual displays by invoking the createVirtualDisplay method twice with the different parameters.

I need this because I need to cast one screen (virtual display, technically speaking) via the WebRTC with the ScreenCapturerAndroid and record on the device the second using the MediaRecorder API.
On devices with the API Level prior to 33 (Android 11), the approach #1 works fine, but not on devices with API Level 33.
Are there any ways to overcome this?


Q: Git : Unable to unlink / cannot create directory, on ignored folder I'm using SourceTree, and when I try to checkout from one branch to another, I've got the following error message :
warning: unable to unlink sf2/web/bundles/mybundle: Permission denied
fatal: cannot create directory at 'sf2/web/bundles/mybundle': Permission denied

Though, on both branches, the folders in sf2/web/bundles/ are ignored, since many commits, as you can see in my .gitignore :
/sf2/web/bundles/*

That's pretty normal I guess, I'm on Windows, symlinks are sh*t.
As a workaround, I can remove the folder and then checkout, but that's not so great.
It seems that, because I commited this folder/symlink some times at the begining, it now has to redo all the modifications step by step, including the ignored folders ?!
EDIT : I confirm it's creating this folder, an old version of it, even if it's supposed to be ignored now. And if I remove this folder, it's showing the few old files inside as working copy changes...

A: Finally found the solution here :
Applying .gitignore to committed files
It's apparently because some files inside has been commited one time, so they are in the repo.
If I understand it right, that means it's very important to modify the .gitignore before commiting any file inside, otherwise it can be a mess !


Q: Failed to create maven project with maven-archetype-webapp When I tried to create a Maven project with maven-archetype-webapp, some problems came out.
An internal error occurred during: "Creating maven-archetype-webapp".
org/apache/maven/shared/filtering/MavenFilteringException

An internal error occurred during: "Updating Maven Dependencies".
org/apache/maven/shared/filtering/MavenFilteringException

I have tried a lot of solutions related to this, nothing worked.
How can I solve this?Thanks!
ps:I was using eclipse 4.4.1 and m2e 1.5.0


Q: "Invalid host in redirect target" using ACME on pfsense I've set up pfsense to manage my network, and I have the ACME plug in installed. I'm to correctly direct traffic to my secure webservers, but first I need to get the certificates onto PFSense.
At the moment, my certificates are using certbot on the webservers, but I want pfsense to manage all the certs.
When I use the stand alone method for the ACME plugin, I get this error, and I'm not sure where I went wrong in setting up pfsense. If someone could help me out, it would be great, thanks.
Renewing certificate
account: myaccount
server: letsencrypt-production-2
/usr/local/pkg/acme/acme.sh  --issue  -d 'domain.ca' --standalone --listen-v4 --httpport '80' --home '/tmp/acme/myaccount/' --accountconf '/tmp/acme/myaccount/accountconf.conf' --force --reloadCmd '/tmp/acme/myaccount/reloadcmd.sh' --log-level 3 --log '/tmp/acme/myaccount/acme_issuecert.log'
Array
(
    [path] => /etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/
    [PATH] => /etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/
    [port] => 80
    [ipv6] =>
)
[Fri Jul 10 10:53:49 MDT 2020] Standalone mode.
[Fri Jul 10 10:53:49 MDT 2020] Single domain='domain.ca'
[Fri Jul 10 10:53:49 MDT 2020] Getting domain auth token for each domain
[Fri Jul 10 10:53:51 MDT 2020] Getting webroot for domain='domain.ca'
[Fri Jul 10 10:53:51 MDT 2020] Verifying: domain.ca
[Fri Jul 10 10:53:51 MDT 2020] Standalone mode server
[Fri Jul 10 10:53:55 MDT 2020] domain.ca:Verify error:Fetching https://domain.ca.well-known/acme-challenge/VBYshVeuP8BQXWnuUMggKU3Rn_cD4k5Tg9FD0gS_-7k: **Invalid host in redirect target**

A: My problem was with AAAA DNS record. Ipv6 record pointed to another host.


Q: php createimage does not output an image to browser can you help?
Using XAMPP I have localhost/drawrectangle.php containing the following code which does not render an image, ll I get is an image placeholder, can you help?
<?php

// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);

// Output and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);

?>


Q: C# Dates - Databases, Display and Localization What are some Date (& Time) format best practices when wanting to adhere to localization in a new application.
For example, what format do you use to write dates to the database.
How do you display the following to the user using their own locale settings once the date has been obtained from the database.
ShortDate
LongDate
DateTime
Any tips for punters appreciated.

A: Always store dates in UTC and when displaying them, calculate the local time based on the user's time zone (which you will have to ask for at some point and store).

A: DateTime2 (aka long date in MS SQL) is only going to be useful if you need that level of granularity or 10,000 year range. DateTime seems to be the norm. If you only need the date portion and can ignore the time, use the new Date datatype in SQL 2008. Ask your clients what granularity is necessary for the project.
UTC is the best way to store the date since your server or your client can be anywhere in the world (assuming a web-based deployment). Also, if you move your server or have a new co-located server you won't need to adjust for timezone since everyone is already running on UTC.
You should only convert from UTC to local time in the presentation later. If your client is using a web browser you can get the timezone offset from javascript. Then if you need that value on the server-side, either store the value in a cookie or in a hidden HTML field for easy access.
I've used a tweaked version of this javascript sample from CodeProject to do the same.


Q: Nginx + Django + Gunicorn: 502 Bad Gateway upstream prematurely closed connection while reading response header from upstream I am creating (for the first time) a website.
More specifically, the user uploads an image and after some computations the website displays some result.
However, sometimes (not always, sometimes just retrying or changing image it works) during this process I get "502 Bad Gateway nginx/1.10.3 (Ubuntu)"
Looking at the error I get:
[error] 7836#7836: *16 upstream prematurely closed connection while reading response header from upstream, client: 131.175.147.1, server: _, request: "POST / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "165.227.170.231", referrer: "http://165.227.170.231/"

I tried this but it did not help much, while I think this is not my case.
The settings are:
/etc/nginx/sites-available/django :
upstream app_server {
server unix:/home/django/gunicorn.socket fail_timeout=0;
}

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

root /usr/share/nginx/html;
index index.html index.htm;

client_max_body_size 4G;
server_name _;

keepalive_timeout 5;

# Your Django project's media files - amend as required
location /media  {
    alias /home/django/django_project/django_project/media;
}

# your Django project's static files - amend as required
location /static {
    alias /home/django/django_project/django_project/static;
}

# Proxy the static assests for the Django Admin panel
location /static/admin {
   alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
}

location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
        proxy_buffering off;

        proxy_connect_timeout 75s;
        proxy_read_timeout 300s;

        proxy_pass http://app_server;
        }
}

The /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
   ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    proxy_connect_timeout 75s;
    proxy_read_timeout 300s;
  }

  #mail {
  #       # See sample authentication script at:
  #       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
  #
  #       # auth_http localhost/auth.php;
  #       # pop3_capabilities "TOP" "USER";
  #       # imap_capabilities "IMAP4rev1" "UIDPLUS";
  #
  #       server {
  #               listen     localhost:110;
  #               protocol   pop3;
  #               proxy      on;

  #       }
  #}

The /ect/gunicorn.d/gunicorn.py:
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from os import environ

def max_workers():
    return cpu_count() * 2 + 1

    max_requests = 1000
    worker_class = 'gevent'
    workers = max_workers()
    TIMEOUT=120

And I start gunicorn in this way:
service gunicorn start --timeout 300

Basically, I tried everywhere to avoid timing out, but still encounter the same problem.


Q: Optimising the query which has joins and unions in mysql I am using the laravel to build my web app. In that for listing all orders I have an query but it takes upto 40s in my localhost whereas in goddady shared hosting it takes upto 95s. Although I implemented the server side datatable yet the query takes bit long to execute. I need someone to suggest or help to make the query to excute more efficient. There are majorly two sets and I make that union.
select * from ((
select `subscription`.`id`,
`subscription`.`order_id`,
`users`.`name` as `user_name`,
`subscription`.`new_dated`,
`subscription`.`rescheduling_delivery_date` as expected_date,
COUNT(`subscription_items`.`product_id`) as items,
`subscription`.`od_dis_total` as `total`,
`subscription`.`order_discount`,
`area`.`area_name`,
`subscribe_orders`.`action` as ordertype,
driver.name as driver_name,
'NA' as payment_mode,
`payment_status`.`status_name` as payment_status,
`subscription_status`.`status_name` as order_status,
`subscription`.`od_payment_method`,
`subscription_items`.`product_id`,
subscription.delivered_dated
from `subscription`
left join `subscription_items` on `subscription`.`id` = `subscription_items`.`subscription_id`
left join `users` on `subscription`.`user_id` = `users`.`id`
left join `users` as `driver` on `subscription`.`driver_id` = `driver`.`id`
left join `ycias_address` on `subscription`.`add_id` = `ycias_address`.`id`
left join `area` on `ycias_address`.`area_id` = `area`.`id`
left join `subscribe_order_items` on `subscription`.`subscribe_order_id` = `subscribe_order_items`.`subscribe_order_id`
left join `subscribe_orders` on `subscription`.`subscribe_order_id` = `subscribe_orders`.`id`
left join `payment_status` on `subscription`.`payment_status` = `payment_status`.`id`
left join `subscription_status` on `subscription`.`od_status` = `subscription_status`.`id`
group by `subscription_items`.`subscription_id`)
union (
select `orders`.`id`,
`orders`.`order_id`,
`users`.`name` as `user_name`,
`orders`.`new_dated`,
`orders`.`expected_delivery_date` as expected_date,
COUNT(order_items.product_id) as items,
`orders`.`od_dis_total` as `total`,
`orders`.`order_discount`,
`area`.`area_name`,
'Instant Order' as ordertype,
driver.name as driver_name,
orders.payment_mode,
`payment_status`.`status_name` as payment_status,
`order_status`.`status_name` as order_status,
`orders`.`od_payment_method`,
`order_items`.`product_id`,
`orders`.`delivered_dated`
from `orders`
left join `order_items` on `orders`.`id` = `order_items`.`order_id`
left join `users` on `users`.`id` = `orders`.`user_id`
left join `users` as `driver` on `driver`.`id` = `orders`.`driver_id`
left join `ycias_address` on `orders`.`add_id` = `ycias_address`.`id`
left join `area` on `ycias_address`.`area_id` = `area`.`id`
left join `payment_status` on `orders`.`payment_status` = `payment_status`.`id`
left join `order_status` on `orders`.`od_status` = `order_status`.`id`
group by `order_items`.`order_id`)) as all_orders limit 10 offset 0

A: As per the suggestion given by Andy Lester I have added the index for the necessary columns. So the execution time is reduced to half that is 18 secs in localhost. I further investigated that the index columns are of datatype VARCHAR. So I changed that to INT and then executed, got results within 0.9 secs. Thanks to Andy Lester.


Q: How do I place a Google recaptcha in my website successfully? I am having real trouble putting a Google recaptcha into my website. There seems to be no easy to follow tutorial. I am brand new to JavaScript, but am building a website which receives a huge amount of spam from the contact form. I'd like a Google recaptcha form, possibly v2 as that seems the 'easiest' but I am still having issues.
I have PHP, JS and HTML and I am not understanding how any of it links, and it is not working. The form submits successfully, however, there is no way of telling the form has submitted, nothing happens on the page. I would like a Bootstrap success alert to take place when I press submit.
Here is the PHP:
<?php

    $Fname = $_POST['Fname'];
    $Lname = $_POST['Lname'];
    $email = $_POST['email'];
    $number = $_POST['number'];
    $company = $_POST['company'];
    $message = $_POST['message'];

    $email_from = "Your website";
    $email_subject = "You have a new submission form from Your website";
    $email_body = "First Name: $Fname.\n".
                    "Last Name: $Lname.\n".
                    "Email Address: $email.\n".
                    "Telephone Number: $number.\n".
                    "Company Name: $company.\n".
                    "Message: $message.\n";

    $to = "howdy@yourwebsite.co.uk";
    $headers = "From: $email_from \r\n";
    $headers .= "Reply-To: $email \r\n";

    $captcha;
    if(isset($_POST['email'])){
        $email=$_POST['email'];
    }
    if(isset($_POST['message'])){
        $message=$_POST['message'];
    }
    if(isset($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
        echo '
Please check the "I am not a robot" checkbox"
';
        exit;
    }
    $secretKey = 'acombinationoflettersandnumbers';
    $ip = $_SERVER['REMOTE_ADDR'];
    // post request to the server
    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
    $response = file_get_contents($url);
    $responseKeys = json_decode($response, true);
    // should return JSON with success as true
    if($responseKeys["success"]) {

        mail($to,$email_subject,$email_body,$headers);

    } else {
        echo '
This has been unsuccessful according to our security checks
';
    }
?>

Here is the HTML form:
<form action="contact.php" id="contact-form" method="POST" role="form">

                    First Name*
                    <input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>

                    Last name*
                    <input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">

                    Email address*
                    <input id="form_email" type="email" class="form-control" name="email" placeholder="becks@example.com" required data-error="Please provide your email address">

                    Contact number*
                    <input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">

                    Your company name
                    <input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">

                    Your message*
                    <textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="I need the world's best website...HELP!" required></textarea>

                  <input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">

            </form>

Here is the JavaScript:
var onloadCallback = function() {
        grecaptcha.render('html_element', {
        'sitekey' : 'acombinationoflettersandnumbers'
      });
      };
      onloadCallback();

    $('form').on('submit', function(e) {
      if(grecaptcha.getResponse() == "") {
      e.preventDefault();
      alert("You can't proceed!");
    } else {
      alert("Thank you");
    }
    });

I have only got this far by following steps from lots of different tutorials and am not sure if any of it is correct. Hope someone is able to assist with a step by step process that allows me submit a contact form, with a success Bootstrap alert and form refresh once it has been submitted.
Thank you!

A: You could try something like this:
front-end

back-end
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
 // not a robot
} else {
 // robot
}

The Recaptcha response will be placed in your g-recaptcha input tag. This value will be sent to the back-end (PHP) of the application. There you can validate the Recaptcha response and show a result based on the outcome of the Recaptcha.


Q: CanvasJS, issues with setting a user input Title for chart I am currently facing an issue with creating a user input title for a canvasJS chart. I am currently running through the tutorial over at canvasJS, and I thought it would make a neat small project to create a user input oriented pie chart.
The current issue I am facing is trying to get the text inputted from HTML to show up correctly.
[JSFiddle]https://jsfiddle.net/n3n0pssc/
var chart = new CanvasJS.Chart("chartContainer",{
               title:{
document.getElementById("chartTitle").setAttribute("text")
}`

I understand that the title must be set by tying it together with the addDataPointsAndRender function, but I am confused as canvasJS only displays set text by title: {text : "title"} and I am trying to figure out how it would go together by fetching input text.
Thank you for any assistance.

A: You can set the user inputs to the chart by either using chart options or by using the set() methods of the CanvasJS API.
I have modified your jsfiddle, and its working now.
function addDataPointsAndRender(){
    chart.options.title.text =document.getElementById("chartTitle").value;
    chart.options.data[0].dataPoints.push({
        y: parseFloat(document.getElementById("yValue1").value),
        indexLabel: document.getElementById("indexLabel1").value
    });
    chart.render();
}

Also have a look at :

*

*Tutorial on Rendering chart from user Input

*Updating Chart Options

*CanvasJS Methods & Properties Documentation


Q: Java: Creating New Strings During Runtime to Edit I'm creating a Mad Lib generator in Java. If you know what a Mad Lib is, this will be easier to understand. Also, I'm new to Java, so bear with me here. I want to make it so that each Mad Lib only asks for the number of adjectives, nouns, etc. that are in that specific one. For example, Mad Lib 1 may have 3 nouns, while Mad Lib 2 has 5 nouns. Is there a way to write a separate method to be run X times, creating X new strings (for the player to enter X nouns), and giving each string a different name? Just giving the strings names like nounA, nounB, nounC, or noun1, noun2, noun3 would be perfect. I need the final story to be able to differentiate between them. It will be really nice if each time I decide to add another Mad Lib to my program to just be able to loop an addNoun() method 8 times instead of writing
String nounA = scan.next();
System.out.print("\f");
String nounB = scan.next();
System.out.print("\f");

...and so on every time for each part of speech. I have not yet learned about arrays, and I think this may have a solution involving that. Like I said, I'm new to Java, so if you try to show me anything advanced, please explain it in a way that I can understand it or find a simpler way to do it.

A: If I understand your problem correct then you need to use ArrayList and HashMap to achieve this:
First you can create ArrayList of String to store X nouns. An ex: of Arraylist is:
  List<String> nouns = new ArrayList<String>();
  nouns.add('nounA'); // add related noun
  //or
  String nounStr = 'new Noun'
  nouns.add(nounStr);

Then you can categorise particular nouns by HashMap
HashMap<String, List<String> > nounCategory = new HashMap<String, List<String> >();
nounCategory.put('madLib1', 'nouns'); // add all list with a unique key madLib1 ...

To learn more about using List and HashMap read reference List:here and HashMap:here

A: If you have the count of nouns, say, in int nounCount, use arrays like this:
String[] nouns = new String[nounCount]; // Create an array
for (int i = 0; i < nouns.length; i++) {
    nouns[i] = scan.next(); // Set each item
}

Then you would be able to access different words as noun[0], noun[1], etc. You're likely to use loops and store index of selected noun somewhere though.
See also: Java arrays tutorial


Q: How to create custom component using JSF 1.2? I am new in the JSF world, please tell me step by step answer of how to create JSF custom component i search on the net but i didn't get any proper answer or give me some link which shows how to create custom component.
Thanks
Vinod

A: Googling for "extend UIComponentELTag" or "extends UIComponentELTag" should yield enough hints.
This is one of my favourites: http://blogs.steeplesoft.com/2006/12/jsf-component-writing-check-list/

A: RichFaces includes CDK (component development kit) that can be used for components development.
Here is the link to the guide: RichFaces CDK Developer Guide


Q: When validation fails, associated record count still changes Here's a problem.   I have my models:
class Collection < ActiveRecord::Base

    has_many    :collection_ownerships
    has_many    :items
    has_many    :users, :through => :collection_ownerships

    validates :title, presence: true, length: { maximum: 25 }
    validates :description, length: { maximum: 100 }
end

class Item < ActiveRecord::Base

    belongs_to :collection
    has_many :item_ownerships, :dependent => :destroy
    accepts_nested_attributes_for :item_ownerships

    validates :name, :presence => true, length: { maximum: 50 }
    validates :collection, :presence => true

end

class ItemOwnership < ActiveRecord::Base

    belongs_to  :item
    belongs_to  :user

    validates :user, :presence => true
    validates :item, :presence => true
end

Here is my controller code:
before_filter(:except => :toggle_item_owned_state) do
    @collection = current_user.collections.find(params[:collection_id])
end

def new
    @item = @collection.items.new
    @item_ownership = @item.item_ownerships.build(:owned => true, :user => current_user, :item => @item)
end

def create
    @item = @collection.items.new(item_params)
    @item_ownership = @item.item_ownerships.build(:owned => false, :user => current_user, :item => @item)

    if @item.save
        redirect_to collection_items_path(@collection)
    else
        flash.now[:alert] = "There was a problem saving this item."
        render "new"
    end
end

I have a couple of controller tests:
describe 'POST#create' do

            context "with bad data" do
                it "should not create a new record for 'items'" do
                    expect { post :create, :collection_id => batman_collection.id,
                                       :item => { :name => '',
                                                :item_ownership_attributes => { :owned => '1'} }
                            }.to change(Item,:count).by(0)
                end

                it "should not create new record 'item_ownerships'" do
                    expect { post :create, :collection_id => batman_collection.id,
                   :item => { :name => 'item_name',
                            :item_ownership_attributes => { :owned => '1'} }
                            }.to change(ItemOwnership,:count).by(0)
                end
            end
        end

When I run my tests, the second one fails:
  1) ItemsController authenticated user POST#create with bad data should not create new record 'item_ownerships'
     Failure/Error: expect { post :create, :collection_id => batman_collection.id,
       expected #count to have changed by 0, but was changed by 1
     # ./spec/controllers/items_controller_spec.rb:62:in `block (5 levels) in <top (required)>'

And ultimately this reflects in the view as well.   Now, when I look in the db, I don't see the record created.   I assume this his happening because somehow Count is reflecting the count of objects in memory, not in the db.
How can I get a handle on the situation.   The problem manifests itself in that when the form is submitted for populating the validation fails for Item, however, multiple instances of ItemOwnership end up showing up on form.
Thanks

A: I found the problem.  My second test is wrong as it's actually submitting a valid request to the server in that 'name' is not blank.
I removed it and now the test passes.

A: Rails will by default save records created from nested attributes even if the validations of the parent record fails. Thats why Item.count increases. .count unlike collection#size always queries the database.
What you need to do is create a validation on Item that tells Rails that an Item is not valid unless the parent collection is valid.
class Item < ActiveRecord::Base

    belongs_to :collection
    has_many :item_ownerships, :dependent => :destroy
    accepts_nested_attributes_for :item_ownerships

    validates :name, :presence => true, length: { maximum: 50 }
    validates :collection, :presence => true
    validates_associated :collection #!

end

http://guides.rubyonrails.org/active_record_validations.html#validates-associated


Q: Best practice for keeping denormalized schema up to date? I'm creating a game with points for doing little things, so I have a schema as such:
create table points (
  id int,
  points int,
  reason varchar(10)
)

and to get the number of points a user has is trivial:
select sum(points) as total from points where id = ?

however, performance has become more and more of an issue as the points table expand.  I want to do something like:
create table pointtotal (
  id int,
  totalpoints int
)

what is the best practice for keeping them in sync?  Do I try to update pointtotal on every change?  Do I run a daily script?
(Assume I have the right keys - they were left out for conciseness)
Edit:
Here are some characteristics that I left out but should be helpful:
Inserts/Updates to Points are not all that frequent
There are a large number of entries, and there are a large number of requests - the keys were pretty trivial, as you can see.

A: The best practice is to use a normalized database schema.  Then the DBMS keeps it up to date, so you don't have to.
But I understand the tradeoff that makes a denormalized design attractive.  In that case, the best practice is to update the total on every change.  Investigate triggers.  The advantage of this practice is that you can make the total keep in sync with the changes so you never have to think about whether it's out of date or not.  If one change is committed, then the updated total is committed too.
However, this has some weaknesses with respect to concurrent changes.  If you need to accommodate concurrent changes to the same totals, and you can tolerate the totals being "eventually consistent," then use periodic recalculation of the total, so you can be sure only one process at a time is changing the total.
Another good practice is to cache aggregate totals outside the database, e.g. memcached or in application variables, so you don't have to hit the database every time you need to display the value.

The query "select sum(points) as total from points where id = ?" should not take 2 seconds, even if you have a huge number of rows and a lot of requests.
If you have a covering index defined over (id, points) then the query can produce the result without reading data from the table at all; it can calculate the total by reading values from the index itself.  Use EXPLAIN to analyze your query and look for the "Using index" note in the Extra column.
CREATE TABLE Points (
  id     INT,
  points INT,
  reason VARCHAR(10),
  KEY    id (id,points)
);

EXPLAIN SELECT SUM(points) AS total FROM Points WHERE id = 1;

+----+-------------+--------+------+---------------+------+---------+-------+------+--------------------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref   | rows | Extra                    |
+----+-------------+--------+------+---------------+------+---------+-------+------+--------------------------+
|  1 | SIMPLE      | points | ref  | id            | id   | 5       | const |    9 | Using where; Using index |
+----+-------------+--------+------+---------------+------+---------+-------+------+--------------------------+

A: By all means keep the underlying table normalized. If you can deal with data potentially being one day old, run a script each nigh (you can schedule it), to do the roll up and populate the new table. Best to just re-create the thing each night from the source table to prevent any inconsistencies between the two.
That said, with the size of your record, you must either have very slow server, or very large # of records, because a record that small, with an indexed field on id should sum very quickly for you - however, I am of the mindset that if you can improve user response time by even a few seconds, there is no reason not to use rollup tables - even if DB purists object.

A: Have the extra totalpoints column on the same table, and create/update the value of totalpoints for every row creation/update.
If you need totalpoints for a certain record, you can lookup the value without computing totalpoints. For example if you need the last value of totalpoint, you can get it like this:
SELECT totalpoint FROM point ORDER BY id DESC LIMIT 1;

A: There is another approach: caching. Even if it's cached for only a few seconds or minutes, that is a win on a frequently accessed value. And it's possible to dissociate the cache-fetch with the cache-update. That way, a reasonably current value is always returned in constant time. The tricky bit is having the fetch spawning a new process to do the update.

A: I'd suggest to create a layer that you use to access and modify the data. You can use these DB access functions to encapsulate the data maintenance in all tables to keep the redundant data in sync.

A: You could go either way in this case, because it's not very complicated.
I prefer, as a general rule, to allow the data to be temporarily inconsistent, by having just enough redundancy, and have a periodic process resolve the inconsistencies. However, there is no harm in having a trigger mechanism to encourage early execution of the periodic process.
I feel this way because relying on event-based notification-style code to keep things consistent can, in more complex cases, greatly complicate the code and make verification difficult.

A: You could also create another reporting schema and have it reload at fixed intervals via some process that does the calculations.  This is not applicable to realtime information - but is very standard way of doing things.

A: Keeping Denormalized Values Correct


Q: Why aren't composed self-recursive functions with same data structure (same dims) on in and out inlined together with other recursions? In tutorial https://markkarpov.com/tutorial/ghc-optimization-and-fusion.html#fusion-without-rewrite-rules is a code example, which will not be optimized by fusion.
map0 :: (a -> b) -> [a] -> [b]
map0 _ []     = []
map0 f (x:xs) = f x : map0 f xs

foldr0 :: (a -> b -> b) -> b -> [a] -> b
foldr0 _ b []     = b
foldr0 f b (a:as) = foldr0 f (f a b) as

nofusion0 :: [Int] -> Int
nofusion0 = foldr0 (+) 0 . map0 sqr

sqr :: Int -> Int
sqr x = x * x

My question is: Why isn't function foldr0 (+) 0 . map0 sqr automatically inlined together into one recursion if the compiler can easily prove, that map0 doesn't change data structure dimension and deduce everything on run from the up of structure to the down of structure? I can't still find out, why this kind of code can't be automatically optimized without rewritting rules.
Do you know any specific reason, why this optimization isn't used please?
Thanks.

A: I think the most promising approach that could optimize your example is called supercompilation. There is a paper about supercompilation for lazy functional languages: https://www.microsoft.com/en-us/research/publication/supercompilation-by-evaluation/.
In the future work section of the paper the authors state:

The major barriers to the use of supercompilation in practice are code bloat and compilation time.

There has been work on trying to integrate supercompilation into GHC, but it has not yet been successful. I don't know all the details, but there is a very technical GHC wiki page about it: https://gitlab.haskell.org/ghc/ghc/-/wikis/supercompilation.


Q: Effects on Input Variable after Failed Input Stream I was working on the following code.
#include <iostream>

int main()
{
  std::cout << "Enter numbers separated by whitespace (use -1 to quit): ";
  int i = 0;
  while (i != -1) {
    std::cin >> i;
    std::cout << "You entered " << i << '\n';
  }
}

I know that using while (std::cin >> i) would have been better but I don't understand a specific occurrence.
If I provide an invalid input, the loop becomes infinite because the Input Stream enters a failbit state. My question is that what happens to the input variable i? In my case, it becomes 0 regardless of the previous value entered. Why does it change to 0 after an invalid input? Is this a predefined behaviour?

A: You get zero because you have a pre-C++11 compiler.  Leaving the input value unchanged on failure is new in the latest standard.  The old standard required the following:

If extraction fails, zero is written to value and failbit is set. If
  extraction results in the value too large or too small to fit in
  value, std::numeric_limits::max() or std::numeric_limits::min()
  is written and failbit flag is set.

(source)
For gcc, you need to pass -std=c++11 to the compiler to use the new behavior.


Q: Restlet ServerResource method parameters? This is probably a really stupid/simple question with such an obvious answer that it seems not worth stating in restlet documentation. Where and how (if at all) can Restlet pass parameters to methods in ServerResource classes?
Given this class:
public class FooServerResource extends ServerResource {
    @Get
    public String foo(String f) {
        return f;
    }
}

and a Router attachment router.attach("/foo", FooServerResource.class);
I know that if I use a Restlet client connector I could create a proxy for this class and invoke methods directly, but what if I am making calls to this ServerResource from some other non-java language, e.g. PHP?

A: You can access the query parameters using from the resource reference. Typically, something like this:
@Get
public String foo() {
    Form queryParams = getReference().getQueryAsForm();
    String f = queryParams.getFirstValue("f");
    return f;
}

Generally speaking (and this would work for other methods that GET), you can access whatever is passed to the request (including the entity, when appropriate) using getRequest() within the ServerResource.

A: hithe question is about one year old, but I just started with Restlet and stumbled into the "same" problem. I am talking about the server, not the client (as Bruno marked it, the original question is mixing server and client part)
I think the question is not completely answered. If you, for instance, prefer to separate the Restlet resource from semantic handling of the request (separating business logics from infrastructure) it is quite likely that you need some parameters, like an Observer, or a callback, or sth. else. So, as I fas as I see, no parameter could be transmitted into this instantiation process. The resource is instantiated by Restlet engine per request. Thus I found no way to pass a parameter directly (is there one?)
Fortunately it is possible to access the Application object of the Restlet engine from within the resource class, and thus also to the class that creates the component, the server, etc.
In the resource class I have sth. like this
protected Application initObjLinkage(){

    Context cx = this.getContext();
    Client cli = cx.getClientDispatcher();
    Application app = cli.getApplication() ;
    return app;
}

Subsequently you may use reflection and an interface to access a method in the Application class (still within the resource class), check reflection about this...
Method cbMethod = app.getClass().getMethod("getFoo", parameterTypes) ;
CallbackIntf getmethodFoo = ( CallbackIntf )cbMethod.invoke( app, arguments );
String str = getmethodFoo()

In my application I use this mechanism to get access to an observer that supplies the received data to the classes for the business logics. This approach is a standard for all my resource classes which renders them quite uniform, standardized and small.
So... I just hope this is being helpful and that there is {no/some} way to do it in a  much more simple way :)


Q: How do I get the color of a specific pixel from a picture box? I have a picture box in one of my programs which displays my images just fine. What's displayed consists of a chosen "BackColor" and some filled rectangles using a brush and some lines using a pen. I have no imported images. I need to retrieve the color value of a specified pixel on the picture box. I've tried the following:
Bitmap b = new Bitmap(pictureBox1.Image);
                Color colour = b.GetPixel(X,Y)

But pictureBox1.Image always returns null. Does .Image only work with imported images? If not how can  I get this to work? Are there any alternatives?

A: Yes you can, but should you?
Here is the change your code needs:
Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle);
Color colour = b.GetPixel(X, Y);
b.Dispose();

But there is really no way around giving the PictureBox a real Image to work with somewhere if you want to do real work with it, meaning if you want to use its possibilities e.g. its SizeMode.
Simply drawing on its background is just not the same.  Here is a minimal code to get a real Bitmap assigned:
public Form1()
{
   InitializeComponent();
   pictureBox1.Image = new Bitmap(pictureBox1.ClientSize.Width,
                                  pictureBox1.ClientSize.Height);
   using (Graphics graphics = Graphics.FromImage(pictureBox1.Image))
   {
     graphics.FillRectangle(Brushes.CadetBlue, 0, 0, 99, 99);
     graphics.FillRectangle(Brushes.Beige, 66, 55, 66, 66);
     graphics.FillRectangle(Brushes.Orange, 33, 44, 55, 66);
   }
}

However if you really don't want to assign an Image you can make the PictureBox draw itself onto a real Bitmap. Note that you must draw the Rectangles etc in the Paint event for this to work! (Actually you must use the Paint event for other reasons as well!)
Now you can test either way e.g. with a Label and your mouse:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (pictureBox1.Image != null)
    {   // the 'real thing':
        Bitmap bmp = new Bitmap(pictureBox1.Image);
        Color colour = bmp.GetPixel(e.X, e.Y);
        label1.Text = colour.ToString();
        bmp.Dispose();
    }
    else
    {   // just the background:
        Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
        pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
        Color colour = bmp.GetPixel(e.X, e.Y);
        label1.Text += "ARGB :" + colour.ToString();
        bmp.Dispose();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.FillRectangle(Brushes.DarkCyan, 0, 0, 99, 99);
    e.Graphics.FillRectangle(Brushes.DarkKhaki, 66, 55, 66, 66);
    e.Graphics.FillRectangle(Brushes.Wheat, 33, 44, 55, 66);
}


Q: Django Ajax 'GET' newbie here. I am trying to get some data from my database using ajax.
In my views.py,
def getEvents(request):
    eventList = Events.objects.all()
    events=[]
    for event in eventList:
        events.append({"name": event.name, "start": event.start, "end": event.end})
    return HttpResponse(events, content_type="application/json")

Note that Events is the model that I am trying to parse. After I collect the data from this model, I want to return it to my template using the following ajax code:
            $.ajax({
                url: 'getEvents/',
                datatype: 'json',
                type: 'GET',
                sucess: function(data) {
                    alert(data.name);
                }
            });

In my urls.py:
url(r'^getEvents/', views.getEvents, name='getEvents'),

However, I think I am doing something wrong because it doesn't work. I have been stuck on this for hours...Any ideas?
EDIT:
Okay. When I append the getEvents to the url, I do see all the database objects together in a dict but it seems my ajax is not working. How do I parse this data? The data is in the form:
[{"start": "2017-02-06", "end": "2017-02-07", "name": "Capstone Meeting"},
{"start": "2017-02-07T0:00", "end": "2017-02-08", "name": "Capstone"},
{"start": "2017-01-31T0:00", "end": "2017-02-01", "name": "dasdsd"},
{"start": "2017-01-31", "end": "2017-02-01", "name": "hjb"}]

Here is what I have so far...
            $.ajax({
                url: 'getEvents/',
                datatype: 'json',
                type: 'GET',
                sucess: function(data) {
                    $.each(data, function(index, element) {
                        $('body').append($('<div>', {
                            text: element.name
                        }));
                    });
                }
            });

A: One of your errors is being caused by not using a JsonResponse in your view instead of an HttpResponse.  Here’s how to fix that issue:
from django.http import JsonResponse

def getEvents(request):
    eventList = Events.objects.all()
    events=[]
    for event in eventList:
        events.append({"name": event.name, "start": event.start, "end": event.end})
    return JsonResponse(events)

From the docs, the JsonResponse is

An HttpResponse subclass that helps to create a JSON-encoded response.

The reason that your regular HttpResponse didn’t work, is because you have to manually serialize the data to JSON when using an HttpResponse, e.g., something like:
import json

response_data = json.dumps(events)
return HttpResponse(response_data, content_type="application/json")

Otherwise, I think what will happen is that you will get a call to __repr__ on the events list which will get you python ast serialized data and not JSON serialized data.

A: First of all, there's a typo of your sucess function, it should be success.
Secondly, JSON response should be a dict object rather than a list, if you really want to get a JSON array response anyway, then you have to specify safe=False when you serializing the data by using JsonResponse(events, safe=False), otherwise you'll get a TypeError like TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
So the code sample should be:
def getEvents(request):
    eventList = Events.objects.all().values("name", "start", "end")
    return JsonResponse({"events": eventList})

And for frontend:
        $.ajax({
            url: 'getEvents/',
            datatype: 'json',
            type: 'GET',
            success: function(data) {
                $.each(data.events, function(index, element) {
                    $('body').append($('<div>', {
                        text: element.name
                    }));
                });
            }
        });


Q: Influxdb howto update tag values I would like to do a query like this:
SELECT max(value) as value, "counter" = 'countergasconsumption'
INTO "home"."1month"."test"
FROM "telegraf"."autogen"."mqtt_consumer"
WHERE time > now() - 11d AND "topic" = '/utilitiesmonitor/countergasconsumption'
GROUP BY time(5m)

I already have data with the countergasconsumption tag (not the whole topic). I can't get it to work, tried different select into's and the docs are not really helpful on this topic. The old data is one measurement with a tag for the type of counter, the new data comes in on separate topics via Telegraf.


Q: Segmentation fault when writing to array of strings I am trying to copy some of the arguments passed in argv to an array of strings. Here is my program.
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char * argv[]) {
    char **args = malloc(argc * sizeof(char *));
    for (int i = 0; i < argc - 1; ++i) {
        strcpy(*(args+i), argv[i+1]);
    }
}

I am getting a segmentation fault in the for loop. Why is this happening?

A: You get the segmentation fault because you are using uninitialized pointers.
In other words: *(args+i) is uninitialized.
Let's look at your memory:
char **args = malloc(argc * sizeof(char *));

This will give a local variable args that points to a dynamic allocated memory area consisting of argc pointers to char. Looks like this:

But the argc pointers to char are uninitialized (i.e. malloc doesn't initialized anything) so the real picture is:

That is - the argc pointers to char may point anywhere.
So when you do
strcpy(*(args+i), argv[i+1]);
       ^^^^^^^^^
       Read uninitialized pointer

you read the i'th uninitialized pointer and copy the string at argv[i+1] to that location. In other words - to a location that we can't know where is and most like doesn't belong to your program. This is likely to result in a seg fault.
So before you copy anything you want those char-pointers to point to some chars. Like:

So basically you need to do additional malloc.
Now one problem is: How many chars do you need to malloc?
Well, you can't know until you know the length of the input strings. So you need to put the malloc inside the loop. Like:
int main (int argc, char * argv[]) {
    char **args = malloc(argc * sizeof(char *));
    for (int i = 0; i < argc - 1; ++i) {
        *(args+i) = malloc(strlen(argv[i+1]) + 1);  // Allocate memory
        strcpy(*(args+i), argv[i+1]);
    }
}

Note:

*

*You don't need to write sizeof(char) as it is always 1

*You have to add 1 to the string length of the input string in order to reserve memory for the string termination.

*You should always check that malloc doesn't return NULL

*Instead of *(args+i) you can use the more readable form args[i]
So after a real execution the picture could be:

A: The problem lies in this part of your code:
malloc(argc * sizeof(char *));

Don't think that sizeof(char*) would give you the size of a string.
What is the size of a pointer?
Solution:
int main(int argc, char* argv[])

{
    char* copyOfArgv;

    copyOfArgv = strdup(argv[1]);
}

strdup() - what does it do in C?

A: The problem is you allocated memory for the pointers not for the string (arguments from argv itself) hence the strcpy is invalid - causing segmentation fault.
It would've been better to just:
Allocate memory for the pointers (as you have done) then make those pointers point to the arguments passed. Example:
 #include <string.h>
 #include <stdlib.h>
 #include <unistd.h>

 int main (int argc, char * argv[]) {
     char **args = malloc(argc*sizeof(char *)); //allocated memory for the pointers only
     int i=0;

     for(;i<argc;i++)
     {
         args[i]=argv[i];  //making the pointers POINT to the arguments including the 0th argument as well
         i++;
     }
     return 0;
 }

For using strcpy you should've allocated memory for the arguments itself and then copied those.


Q: Overriding timeout for database connection in properties file I was wondering if there is a specific way to override database connection timeout in the properties file in my Java web project? I am using Hibernate, Spring, and MySQL DB. I have tried several different property fields and reduced the timeout time to 1 millsecond, yet the connection is still completed with transactions still being processed properly.
These are the property fields I have used to no avail...

*

*spring.jpa.properties.javax.persistence.query.timeout=1

*spring.jdbc.template.query-timeout=1

*hibernate.c3p0.timeout=1
Is hibernate overriding this timeout value or am I just setting it improperly?
Thanks in advance!

A: Assuming that you're using Spring Boot you can try:
spring.transaction.defaultTimeout=1

This property sets defaultTimeout for transactions to 1 second.
(Looking at the source code of TransactionDefinition it seems that it is not possible to use anything more precise than seconds.)
See also: TransactionProperties

javax.persistence.query.timeout
This is  a hint for Query. It is supposed to work if you use it like this:
entityManager.createQuery("select e from SampleEntity e")
    .setHint(QueryHints.SPEC_HINT_TIMEOUT, 1)
    .getResultList();

See also QueryHints

spring.jdbc.template.query-timeout
Remember that according to the JdbcTemplate#setQueryTimeout javadoc:

Any timeout specified here will be overridden by the remaining transaction timeout when executing within a transaction that has a timeout specified at the transaction level.

hibernate.c3p0.timeout
I suspect that this property specifies timeout for getting from the connection pool, not for a query execution


Q: quill error with Invalid Quill Container on Vuejs when used with vuetify tab Error on plugin quill occurred when i placed the editor in a tab container of Vuetify. It is created under the mounted hook.
The error in Console is

quill Invalid Quill container undefined
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property
'on' of undefined"

Below is the vue file.

<template>
  <v-app class="panel" ref="panel">
    <v-tabs fixed-tabs v-model="tab">
      <v-tabs-slider></v-tabs-slider>
      <v-tab key="1" href="#tab1">
        Tab 1
      </v-tab>
      <v-tab key="2" href="#tab2">
        Tab 2
      </v-tab>
      <v-tabs-items v-model="tab">
        <v-tab-item key="1" value="tab1">

Edit text in tab 1

        </v-tab-item>
        <v-tab-item key="2" value="tab2">
          <v-card-text>This is tab 2</v-card-text>
        </v-tab-item>
      </v-tabs-items>
    </v-tabs>
  </v-app>
</template>

A: this is probably due to the fact that

 is inside a child component's slot v-tab-item which is conditionally rendered.
that means that the v-tab-item is mounted AFTER the parent's mounted() executes, so the content (including your refs) are not available.
If you can defer the initialization until the child has mounted then you can access the ref, but getting that to work is a complex endeavor.
Instead, I would opt to define a component that handles quill initialization and that can be nested in the tab.
ie:
<v-tab-item key="1" value="tab1">
    <MyQuillComponent v-model="value"/>
</v-tab-item>


Q: How to use coalesce to take sum Can I use sum() in coalesce()?
I want to use it in a stored function in Postgres.
For example
case (COALESCE(t3.Count3,0)+ COALESCE(t2.Count2,0) >= t4.Count4::float)
then ( select (t4.Count4::float/((t3.Count3::float)+(t2.Count2::float))) * 100 as Count5 )
else ''0''
end as Count5

A: It's hard to tell what you're trying to do here because there are multiple issues in the code. Also though your title mentions SUM your code doesn't include it (though you do have + but that's not the same).
If this is part of a SELECT statement, then I'm guessing what you want is:
SELECT
CASE
    WHEN COALESCE(t3.Count3,0)+ COALESCE(t2.Count2,0) >= t4.Count4::float
    THEN 100 * t4.Count4::float/(COALESCE(t3.Count3::float,0)+COALESCE(t2.Count2::float,0))
    ELSE 0
END as Count5
FROM MyTable


Q: Count 1's between the intersection of two binary arrays Given two binary arrays, how can one quickly find the number of 1's occurring between intersecting bits for both arrays?
For example, consider a pair of bitsets (i1, i2) and their intersection (i12):
i1  = [0001001000100100];
i2  = [0101000100010110];
i12 = [0001000000000100]; // (i1 & i2)

The intersecting bits are in position 3 and 13, so count the number of 1's in positions 0-2 and 4-12:
x1 = [0, 2] // results i1
x2 = [1, 2] // results for i2

Now generalize this idea to 32-bit integers. Toy example:
int i1[2] = {2719269390, 302235938};
int i2[2] = {2315436042, 570885266};

Toy example in binary:
i1      = [10100010 00010100 11000010 00001110, 00010010 00000011 11000001 00100010]
i2      = [10001010 00000010 11000000 00001010, 00100010 00000111 00000100 10010010]
i1 & i2 = [10000010 00000000 11000000 00001010, 00000010 00000011 00000000 00000010]

Expected results:
x1 = [2, 2, 0, 1, 1, 1, 0, 0, 4];
x2 = [2, 1, 0, 0, 0, 1, 1, 0, 3];

I can see a "brute-force" approach using __builtin_clz() to determine leading zeros in i1 & i2, shifting i1 and i2 right by that number, doing __builtin_popcount() for the shifted i1 and i2 results, and repeating the procedure until no intersections remain. My instinct suggests there may be a more elegant approach, as this involves a few temporaries, many instructions, and at least two logical branches.
C/C++ implementations are welcome, but I would be satisfied enough with conceptual perspectives.  Suffice it to say this approach intends to remove a critical bottleneck in a popular program.

A: std::popcount returns the number of active bits in a value. It is able to call intrinsic functions, if available.
constexpr auto get_popcount(auto list) {
    decltype(list) result;
    std::transform(list.begin(), list.end(), result.begin(), [](auto x) {
        return std::popcount(x);
    });
    return result;
}

int main() {
    constexpr auto i12 = std::array{
        0b10000010u, 0b00000000u, 0b11000000u, 0b00001010u,
        0b00000010u, 0b00000011u, 0b00000000u, 0b00000010u};

    static_assert(get_popcount(i12) == std::array{ 2u, 0u, 2u, 2u, 1u, 2u, 0u, 1u });
}

A: Can't test this right now but (I1 XOR I2) AND I1 should leave only the bits that you want to count, so:
constexpr auto get_popcount(auto i1, auto i2) {
    std::vector<std::pair(int,int)> res;
    std::transform (i1.begin(), i1.end(), i2.begin(), res.begin(), []
        (auto x, auto y){
            return std::tie(std::popcount((x^y)&x),std::popcount((x^y)&y));
    });
    return res;
}

Where the first item of the touple is the number of bits on I1 and the second on I2.

A: I'm dealing with a similar problem, where I have to count the
number of '1' bits from a run-time-determined range. Don't know how long your bit array is, but mine is millions to billions of bits.
For a very long bit arrays (say, millions of bits), you could build an auxiliary tree structure for each bit array. The root node counts all bits 0~N in the array, the left child node of root stores the partial sum of bits 0~N/2, the right child node store the partial sum of bits (N/2+1)~N, etc. etc. That way, when you want to count the number of '1' bits from an arbitrary range, you traverse the tree and add the partial sum values stored in appropriate nodes of the tree. The time complexity is O(log(N)). When your array is huge, this is going to be much more efficient than iterating over the entire array (complexity O(N)).
If your array is smaller, I would guess SSE/AVX instructions can result in higher throughput? Like Stack Danny has implied, intrinsic functions may already be the underlying implementation of popcount.
If you just use a for loop, GCC is able to vectorize your loop into SSE/AVX (e.g. if you got AVX2 on your CPU, add '-mavx2 -O3' to your compiler command). That works for summing elements of an integer array, but I never examined if looping on a bitarray can also result in vectorized code. https://gcc.gnu.org/projects/tree-ssa/vectorization.html

A: Use the AND operator for i1 and i2 to get only the intersecting bits. Then in a loop, SHIFT right checking each bit using the AND operator until the variable is zero.
Assuming the arrays are in packs of 4 bytes (unsigned long), this should work:
size_t getIntersecting(unsigned long* i1, unsigned long* i2, size_t nPacks) {
    size_t result = 0;
    unsigned long bitsec;
    for (size_t i = 0; i < nPacks; i++)
    {
        bitsec = i1[i] & i2[i];
        while (bitsec != 0) {
            if (bitsec & 1) {
                result++;
            }
            bitsec >>= 1;
        }
    }
    return result;
}

I'm not at my workstation to test it. Generally it should count intersecting bits.
EDIT:
After reexamination of your question, try something like this.
// Define the global vectors
vector<unsigned long> vector1;
vector<unsigned long> vector2;

// Define the function
void getIntersecting(unsigned long* pi1, unsigned long* pi2, size_t nPacks) {
    // Initialize the counters to 0
    unsigned long i1cnt = 0;
    unsigned long i2cnt = 0;
    // Local storage variables
    unsigned long i1, i2;
    // Loop through the pointers using nPacks as the counter
    for (size_t i = 0; i < nPacks; i++) {
        // Get values from the pointers
        i1 = pi1[i];
        i2 = pi2[i];
        // Perform the bitwise operations
        unsigned long i4 = i1 & i2;
        // Loop for each bit in the 4-byte pack
        for (int ibit = 0; ibit < 32; ibit++) {
            // Check the highest bit of i4
            if (!(i4 & 0x80000000)) {
                // Check the highest bit of i1
                if (i1 & 0x80000000) {
                    i1cnt++;
                }
                // Check the highest bit of i2
                if (i2 & 0x80000000) {
                    i2cnt++;
                }
            }
            else {
                // Push the counters to the global vectors
                vector1.push_back(i1cnt);
                vector2.push_back(i2cnt);
                // Reset counters
                i1cnt = 0;
                i2cnt = 0;
            }
            // Shift i4, i1, and i2 left by 1 bit
            i4 = i4 << 1;
            i1 = i1 << 1;
            i2 = i2 << 1;
        }
    }
}


Q: Want to make db layer generic and not tied to spring's JdbcDaoSupport Current I have a seperate maven module for my database access, all my DAO classes inherit from:
public class GenericDaoImpl<T> extends JdbcDaoSupport implements GenericDao<T> {
}

My maven module has a spring dependancy:
org.springframework spring-orm

So a typical Dao class looks like:
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDao {

    @Override
    public void insert(User user) {
        getJdbcTemplate().update("insert into users(...)...");
    }
}

My Dao's get autowired with the dataSource bean.
Can I make this generic somehow so I can continue to use it in my spring MVC application, yet it will work if I need to use this library in a cron job service type environment?  (without having to bring in spring's application context into the picture).

A: I'd start to observe the following:

*

*You have a GenericDao<T> which means that you can have different implementations.

*Currently, you have GenericDaoImpl<T> extends JdbcDaoSupport which means that you cannot use in the other environment you described without any application context unless you prepare all the object in a manual fashion.

So my suggestion is:

*

*Allow GenericDao<T> extends org.springframework.jdbc.core.JdbcOperations

*Develop an AbstractGenericDao<T> implements GenericDao<T> to bring the abstract general functionality you need.

*Develop a MyEnvGenericDao<T> extends AbstractGenericDao<T> that is responsible to provide a data source and underlying implementation of different methods you need; could be using a direct Hibernate/OpenJPA implementation to directly executing the queries.

*Develop a SpringGenericDao<T> extends JdbcDaoSupport implements GenericDao<T> that comes is already with a getJdbcTemplate() to perform the operations you need and is delegated to Spring JDBC template. In this scenario, you need to delegate the operations to JdbcDaoSupport.getJdbcTemplate().

Related to Maven, then you can actually have different modules for MyEnv and Spring implementations but both with one parent to have access to GenericDao<T> interface.


Q: Css media print show additional data, how to avoid them not come in print I am working On a laravel project and used CSS media print in somewhere, It is good but it shows additional data in Chrome Print Dialog like the below image as I marked them, So I don't want them to display when I print it, how to avoid it?

this the HTML code:

مشخصات شاگرد

         نام
         تخلص
         نام پدر
         جنسیت
         سن
         تلیفون
         آدرس
         ایمیل
         حالت مدنی
         نمبر تذکره

          {{ $student->first_name }}
         {{ $student->last_name }}
          {{ $student->father_name }}
         {{ $student->gender }}
          {{ $student->age }}
         {{ $student->phone }}
          {{ $student->address }}
          {{ $student->email_address }}
          {{ $student->marital_status }}
          {{ $student->ssn_number }}

this my script code:

this is style for print:

A: use instead of every  tags from  tag.

مشخصات شاگرد

         نام
         تخلص
         نام پدر
         جنسیت
         سن
         تلیفون
         آدرس
         ایمیل
         حالت مدنی
         نمبر تذکره

          {{ $student->first_name }}
         {{ $student->last_name }}
          {{ $student->father_name }}
         {{ $student->gender }}
          {{ $student->age }}
         {{ $student->phone }}
          {{ $student->address }}
          {{ $student->email_address }}
          {{ $student->marital_status }}
          {{ $student->ssn_number }}


Q: Regex string must contain certain substrings only and separated by whitespace So, I've been trying to come up with a regexp in PHP which can pick out substrings like "XX-035" (or alternatively "XX035" or "XX35") from a larger string of words and character sequences - that's the easy part - with the added proviso that the required substrings must be separated by one or more whitespace characters from other substrings in the main string.
In addition the substrings must also start with a particular two-letter group like "AB","CG" or "MS", etc., followed by zero or one dashes, and then 1 to 4 numerals (again, that part is easy). So, I have tried many different regex's, with and without \b word-boundaries, with and without whitespace \s, the latest of which is as follows:
/\b(\s+[^\/a-zA-Z](AB|CG|MS|MT|NA|OQ|TS){1}[\-]?\d{1,4})\b/i

but I just can't seem to crack the whitespace requirement. I've gone through many iterations in https://regex101.com/ and still haven't managed to get it down.
Obviously, I'm no expert when it comes to regular expressions, so any help would be appreciated here.

A: You may use
(?<!\S)(?:AB|CG|MS|MT|NA|OQ|TS)-?\d{1,4}(?!\S)

See the regex demo
Details

*

*(?<!\S) - the previous char should be a whitespace or start of string

*(?:AB|CG|MS|MT|NA|OQ|TS) - one of the 2-letter alternative

*-? - an optional hyphen

*\d{1,4} - one to four digits

*(?!\S) - the next char should be a whitespace or end of string.

PHP:
if (preg_match_all('~(?<!\S)(?:AB|CG|MS|MT|NA|OQ|TS)-?\d{1,4}(?!\S)~', $s, $matches)) {
    print_r($matches[0]);
}


Q: Spring security jet always redirecting to "/" after successful auth I have made a Rest API project with Spring Boot 2. I have used jwt for authentication. I can generate tokens fine. But when I send the generated token in a header with a request, it always redirects me to "/" path instead of the requested path (in my case "/rest/hello").
This is my custom AuthenticationProvider
@Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private JwtValidator jwtValidator;
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken)authentication;
        String token = jwtAuthenticationToken.getToken();
        JwtUser jwtUser = jwtValidator.validate(token);
        if (jwtUser == null) {
            throw new RuntimeException("JWT Token not correct");
        }
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(jwtUser.getRole());
        return new JwtUserDetails(jwtUser.getUserName(), jwtUser.getId(), grantedAuthorities, token);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

This is my custom Filter
public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
    public  JwtAuthenticationTokenFilter() {
        super("/rest/**");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Token ")) {
            throw new RuntimeException("JWT Token is missing");
        }
        String authenticationToken = header.substring(6);
        JwtAuthenticationToken token = new JwtAuthenticationToken(authenticationToken);
        return this.getAuthenticationManager().authenticate(token);
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    public void setAuthenticationSuccessHandler(JwtSuccessHandler jwtSuccessHandler) {
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);
        chain.doFilter(request, response);
    }

}

This is my Security config
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationProvider authenticationProvider;
    @Autowired
    private JwtAuthenticationEntryPoint entryPoint;

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Collections.singletonList(authenticationProvider));
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilter(){
        JwtAuthenticationTokenFilter filter = new JwtAuthenticationTokenFilter();
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(new JwtSuccessHandler());
        return filter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/rest/**").authenticated().and().exceptionHandling().authenticationEntryPoint(entryPoint)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        http.headers().cacheControl();
    }
}

I have custom classes for user details and token as well.


Q: Count of an NSMutable Array of Objects that is in an NSMutable Array of Objects returns 0 I have an array of NSObjects (mapArray), and the object being focused on is at position 0 (MAIN_MAP). In each NSObject, there is a NSMutableArray called moonGateArray (has @property and @synthesize) to which I add another NSObject called Moongate. However, I keep getting zero as the count for moonGateArray. Any answers for why that is?
Code:
for (int i = 0; i < 8; i++) {
    [[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] addObject:[Moongate new]];
}
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:0] setPosition:9 :3];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:1] setPosition:16 :8];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:2] setPosition:11 :6];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:3] setPosition:16 :13];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:4] setPosition:13 :10];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:5] setPosition:3 :1];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:6] setPosition:3 :12];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:7] setPosition:22 :17];
NSLog(@"%i",[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] count]);

A: You probably haven't initialized either mapArray or moonGateArray thats why you are getting 0 count. In objective-c calling count on nil object doest not give any exception but instead returns 0.
hope that helps!

A: However for your count=0, this is straight forward you missed to alloc/init any of the array you used.
Are you creating a 2D array or 3D array?
It is creating confusion to get your logic?
Edit:
if your MAIN_APP is always 0, why you need an array, a simple object or instead of storing in 2D array you could have used dictionary. However the entire logic I can guess.
And I would like to add one more thing about your naming conventions... Name suffix or prefix your variable with Array, Button etc. you can use "maps", "moonGates", all plural symbolizes its gonna to be an array.

A: Most likely you haven't properly initialize your arrays. Make your like easier and change your code a bit to make it easier to read and easier to debug. You don't get points for writing highly nested method calls. It makes your life harder. Split the code up to make things easier.
Change this:
for (int i = 0; i < 8; i++) {
    [[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] addObject:[Moongate new]];
}

to this:
// replace "SomeMapClass" with your actual class name
SomeMapClass *mainMap = mapArray[MAIN_MAP];
NSMutableArray *moonArray = mainMap.moonGateArray;
for (int i = 0; i < 8; i++) {
    [moonArray addObject:[Moongate new]];
}

Now you can run this code in the debugger or add NSLog statements and verify each step of the process.
Is mapArray properly initialized?
Is moonArray property initialized?
Remember, simply defining a property doesn't actually create the object. You still need to initialize it.


Q: ReactNative nested render functions. Question regarding `this` between objects and functions Here is my confusion:
     constructor(props) {
    super(props);
  }

  hookNav(){
    console.log("work");
  }

  renderItem({ item, index }) {
    return (
      <TouchableOpacity style={{ margin: 9 }} onPress={this.hookNav}>
        <View
          style={{
            flex: 1,
            minWidth: 170,
            maxWidth: 223,
            height: 280,
            maxHeight: 280,
            borderRadius: 10,
          }}
        >
          <ImageBackground
            source={{
              uri: "https://picsum.photos/170/223",
            }}
            style={{ flex: 1 }}
            imageStyle={{ borderRadius: 10 }}
          >
            <Text
              style={{
                color: "white",
                position: "absolute",
                bottom: 20,
                right: 10,
                fontWeight: "bold",
                textShadowColor: "black",
                textShadowOffset: { width: -1, height: 1 },
                textShadowRadius: 10,
              }}
            >
              Topic
            </Text>
          </ImageBackground>
        </View>
      </TouchableOpacity>
    );
  }

  render(){
    return (
      <View style={{ marginBottom: 80, backgroundColor: "white" }}>
        <Header
          centerComponent={{ text: "test", style: { color: "orange" } }}
          rightComponent={{ icon: "add", color: "orange" }}
        />
        <FlatList
          numColumns={2}
          onEndReachedThreshold={0}
          onEndReached={({ distanceFromEnd }) => {
            console.debug("on end reached ", distanceFromEnd);
          }}
          contentContainerStyle={styles.list}
          data={[
            { key: "a" },
            { key: "b" },
            { key: "c" },
            { key: "d" },
            { key: "e" },
            { key: "f" },
          ]}
          renderItem={this.renderItem}
          ListHeaderComponent={
            <Text
              style={{ padding: 10, fontWeight: "bold" }}
            >
              Your Topics
            </Text>
          }
        />
      </View>
    );
  }
}

in this code above, when navigating to this page an error is immediately thrown that this.hookNav is undefined.
However, when I put the hookNav function inside of a state object, like so
constructor(props) {
    super(props);
    state = {
      hookNav : function() {
       console.log("work please");
      }
    }
  }

and in onPress inside of renderItem
const { hookNav} = this.state;
    return (
      <TouchableOpacity style={{ margin: 9 }} onPress={hookNav}>

This works as intended.
It is my understanding that render already has access to the component’s state via this. If renderItem can access the state object, through this, why can it not access this.hookNav() directly? Why does the function need to be encapsulated in an object for this to work?
Thanks.

A: It's because the value of this inside any Javascript function depends on how that function was called.
In your non-working example, this.hookNav is inside of the renderItem method. So it will adopt the this of that method - which, as I just said, depends on how it is called. Further inspecting your code shows that the renderItem method isn't called directly by your component but passed as a prop (called renderItem) of the FlatList component. Now I don't know how that component is implemented (I've never used React Native), but almost certainly it calls that function at some point - and when it does, it can't be in the context of your component. This is because FlatList can't possibly know where that function prop is coming from, and when it calls it, it will be treated as an "ordinary" function, not in the context of any particular object. So its this context won't be your component instance, as intended, but will simply be the global object - which doesn't have any hookNav method.
This problem doesn't happen in your second example because you simply access the function as part of this.state - there is no passing of a method, like the renderItem in the previous example, which depends on an internal this reference. Note that this won't be the case if your hookNav refers to this inside it.
Such problems with this context are very common in React, but fortunately there are two general solutions which will always fix this:

*

*Bind methods in your component's constructor. If the constructor, in the first example, includes the statement this.renderItem = this.renderItem.bind(this);, then it would work fine. (Note that this is recommended in the official React docs.) It's the "best" solution technically (performance is slightly better than in the other option) - but does involve quite a bit of boilerplate if you have lots of methods which need such binding.

*Use arrow functions to define the methods instead. Instead of renderItem({ item, index }) {...}, write it as renderItem = ({ item, index }) => {...}. This works because arrow functions adopt the this of their lexical scope, which will be the class itself - so in other words this will always refer to the component instance, as you almost always want.
Don't worry if this is confusing - the behaviour of the this keyword in JS is a common stumbling block for beginners to JS, and often enough for those more experienced too. There are a number of good explanations online which demystify it, of which I can especially recommend this one.

A: You have to bind the method in to this of your class. One way to do so will be like below.
constructor(props){
  super(props);
  this.renderItem = this.renderItem.bind(this);
}


Q: linux - Bash Terminal not allowing usage of scripts even if terminal is at current directory of script itself So,I had Fedora installed in my computer,since Windows gave me no choice last time.
Then after I installed Fedora,I learned that Fedora was actually Linux - only modified,and thus,I wanted to try out the programming language that it has - BASH.
And my search for tutorials went on,and I found one.And it tole me to do something like:
#!/bin/bash
echo Hello World.

Then,I wanted to try it out,so I saved it as testscript.sh and then,opened Terminal,and this happened.
[JRGarcia@localhost ~]$ ./testscript.sh
bash: ./testscript.sh : command not found

So,I thought to myself: "That just ain't right!"
And then,on went my rampant rage across my room,and everything I have is destroyed right now.
What do I have to do? I saw some videos on tutorials and that method worked fine for them.BTW,I saved the script in the /home/JRGarcia,which is what Terminal uses as a starting directory.

A: If you have the x permission on the script and cannot execute it, it may be because you mounted the current partition with the option noexec. See explanation in manpage of mount
You can verify this by running the mount command without any arguments.

A: $ cat > testscript.sh
#!/bin/bash
echo Hello World.
^D
$ chmod +x testscript.sh
$ ./testscript.sh         #=> Hello world.

Works fine.


Q: Error when adding ext.grid.panel into ext.form.panel I have this grid and form panels. I want to add a grid of data into the form panel and still have buttons from the form panel.
      myGrid= Ext.create('Ext.grid.Panel',{
            layout: {
                type: 'fit'
            },

            id: 'gridId',
            title: null,
            store: myDataStore,
            columns: [{
                header: 'header 1',
                dataIndex: 'index_1',
                width: 120
            }, {
                header: 'header 2',
                dataIndex: 'index_2',
                width: 120
            }, {
                header: 'header 3',
                dataIndex: 'index_3',
                width: 120
            }],
            stripeRows: true
        })

        formPanel= Ext.create('Ext.form.Panel',{
            id:'panelId',

            items:[myGrid],
            buttons: [{
                 // cancel, save, other buttons
            }]
        })

But I get this error
HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy

what do I do wrong?

A: You forgot semicolons after your Ext.create() config.
Seems to work just fine here. I made a fiddle
http://jsfiddle.net/WGgR8/1/


Q: Is there an [embed] alternative for Flash only (not flex)? Ok we all know that you can embed assets with Flex using the [embed] code.
But is there anyway to achieve something similar to this when working with only Flash?
For example:
I need to create a class (that contains certain assets) that needs to be used in the Flash IDE, but I don't want to have to drop all the assets into the library for every Flash file that happens to use the class.

A: Are you looking for this? http://adobe.com/devnet/flash/articles/embed_metadata.html

A: Hope this will helpful for you.
http://www.adobe.com/devnet/flex/articles/actionscript_blitting.html
http://blog.nightspade.com/2010/02/01/embedding-asset-at-compile-time-in-pure-as3-project/
http://www.bit-101.com/blog/?p=853


Q: How to set a cron expression of current date + 14 days I am looking for a cron expression which will help in setting the cron job for current date + 14 days. This is a repeated exercise which will take place whenever a new code is deployed into dev environment and then use the current date of dev will used to schedule the trigger for prod after 14 days.
Example : This a BAMBOO CLI Command to set scheduled triggers in a Bamboo Plan.
--action addEnvironmentTrigger  --deploymentProject "Deploy ZDEPLOY4774565-BASE"  --environment "QA"  --type "Scheduled"  --description "scheduled trigger"  --schedule "1 0 0 ? * *"
Now once the dev deployment is successfully completed , then it will create a scheduled trigger for prod to be deployed after 14 days .so every time dev is deployed . I need to use the current date of dev .

A: Following cron expression will run 14 days once
0 5 */14 * * /your/command/

If you like to run only once from current date  on 20th September 2018
0 0 20 9 ? 2018  /command

WARNING: The year column is not supported in standard/default implementations of cron.

A: Run a cron-job every 14 days starting from day X
If you want to do this, have a look at this answer.
Run a cron-job only ones 14 days after day X
If you want to do this, there are a few options you have. Assume that day X is today (2018-09-06), then I give you the following options:
# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed
  0  0  6  9  *   [[ `date '+\%Y'` == "2018" ]] && sleep 1209600 && command1
  0  0  20 9  *   [[ `date '+\%Y'` == "2018" ]] && command2
  0  0  *  *  *   /path/to/daytestcmd 14 && command3

*

*The first option here is simply checking if the year is correct. If so, sleep for 14 days and then execute command1

*The second option is by computing the day itself and execute the script on that day. Again, you have to check manually for the correct year.

The third option is much more flexible for your purpose. The idea is to create a script called daytestcmd which does the check for you. The advantage of this script is that you only need to update one line in the script to change the test and never change the cronjob. The script would look something like:
#/usr/bin/env bash
# Give reference day
reference_day="20180906"
# Give the number of days to await execution (defaults to zero)
delta_days="${1:-0}"
# compute execution day
execution_day=$(date -d "${reference_day} + $delta_days days" "+%F")

[[ $(date "+%F") == "$execution_day" ]]

So, the next time you want to wait 14 days, just update the script and change the variable reference_day.
note: the OP updated the question. The above script can also be adjusted where reference_day is obtained via a set of commands, for example to retrieve the day of dev deployment. Imagine get_dev_deployment_day is a command which returns that day, then you just need to update
reference_day=$(get_dev_deployment_day)


Q: Custom css for paging in codeigniter I need a little help here,
I want using paging CodeIgniter.
Here my piece code for showing the paging.
    $this->load->library("pagination");
    $config = array();
    $key = $this->input->get_post('qfront');
    $config["base_url"] = base_url() . "source/";
    $config["total_rows"] = $this->fetch_count($key)->count;
    $config["per_page"] = 10;
    $choice = $config["total_rows"] / $config["per_page"];
    $config["uri_segment"] = 2;
    $config["num_links"] = round($choice);
    $config['full_tag_open'] = '

';
    $config['full_tag_close'] = '

';

    $config['first_link'] = '« First';
    $config['first_tag_open'] = '
';
    $config['first_tag_close'] = '
';

    $config['last_link'] = 'Last »';
    $config['last_tag_open'] = '
';
    $config['last_tag_close'] = '
';

    $config['next_link'] = 'Next →';
    $config['next_tag_open'] = '
';
    $config['next_tag_close'] = '
';

    $config['prev_link'] = '← Previous';
    $config['prev_tag_open'] = '
';
    $config['prev_tag_close'] = '
';

    $config['cur_tag_open'] = '
';
    $config['cur_tag_close'] = '
';

    $config['num_tag_open'] = '
';
    $config['num_tag_close'] = '
';
    $this->pagination->initialize($config);
    $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
    $data["results"] = $this->fetch_result($config["per_page"], $page, $key);
    $data["links"] = $this->pagination->create_links();
    $data["key"] = $key;
    $this->load->view("page", $data);

in my view :
<?php echo $links; ?>

And what I got is

How can I make like <-prev 1 2 3 4 5 . . . 200 next->
Is it possible? Or maybe a little nice css

A: In the $config array passed into the pagination initialize() method, you can set the number of links to display on either side of the current page with num_links:
$config['num_links'] = 2;

From the CI user guide:

The number of "digit" links you would like before and after the selected page number. For example, the number 2 will place two digits on either side, as in the example links at the very top of this page.

That should get you closer to exactly what you want. I don't know the exact HTML generated by this library, so if you post it maybe someone can give you a CSS solution. You could also look into extending the CI pagination library to suit you needs (check out "Extending Native Libraries").


Q: Clean map periodically I have a A class managing a map.
class A {
 public:
  A() {}
  void addElem(uint8_t a, const B& b) {
    std::lock_guard<std::mutex> lock(_mutex);
    auto result = _map.emplace_hint(_map.end(), a, b);
    _deque.push_back(std::make_pair(result, time(nullptr)));
  }
  void cleanMap() {
    std::lock_guard<std::mutex> lock(_mutex);
    _map.erase(_deque.front().first);
    _deque.pop_front();
  }
 private:
  std::map<uint8_t, B> _map;
  std::deque<std::pair<std::map<uint8_t, B>::iterator, time_t>> _deque;
  std::mutex _mutex;
};

As I add a lot of elements in my map, I want to periodically clean it by removing elements that were first inserted.
if (difftime(time(nullptr), _deque.front().second > EXPIRY)) {
  cleanMap();
}

The following code is crashing at some point when I try to pop element from deque:
double free or corruption (fasttop): 0x00007fffdc000900 ***

Is the above code makes sense ? If yes, where could be the error ? And if not, how can I clean periodically a map ?

A: You have problems when you add the elements with the same key.
When emplace_hint is called with the key which exists, you push on deque duplicated iterators (emplace_hint returns the iterator to already existing element map::emplace_hint).
When deque and map are cleared, you call map::erase but it accepts only valid and dereferenceable iterators. So when erase is called for the duplicated iterator (map::erase), the code crashes because this item was deleted in previous erase call.


Q: Uploadify onComplete not firing I am using Yii framework with uploadify. The upload works perfectly but the onComplete event gets not fired..
It seems that the main problem of most of the users is that the .php file does not return anything and so flash does not know when the .php script has finished. But my script does echo "OK" at the end, so this is not the problem.
My Code:
$('#element').uploadify({
    'uploader' : 'index.php?page=upload',
    'swf'      : 'javascript/uploadify.swf',
    onComplete : function(event, queueID, fileObj, response, data) {
        alert(event); alert(queueID); alert(fileObj); alert(response); alert(data);
    },
});

My PHP Code looks like:
//Upload things
echo 'OK';

The upload works perfectly, but the onComplete event is not fired. I tried to remove all upload things, so that the php file looks like:
echo 'OK';

but that also does not work.
Thanks for your help!


Q: Jinja2 template if/else statement In a jinja2 template file, I'm attempting to find a string in a server hostname, then apply the settings I want based on what it found. Here is what I have. This works, however, everything is getting the developmenthosts setting.
{% if 'dev' or 'tst' or 'test' or 'eng' in ansible_hostname %} {{ developmenthosts }} {% else %} {{ productionhosts }} {% endif %}
Any help would be great, and I'm fairly new using jinja2 templates.

A: Try the following, using regex_search the if/else can be written in shorter and cleaner format.
"{{ developmenthosts if ( ansible_hostname|regex_search('dev|tst|test|eng') ) else  productionhosts }}"

Example:
---

- name: Sample playbook
  connection: local
  #  gather_facts: false
  hosts: localhost
  vars:
   developmenthosts: MYDEVHOST
   productionhosts: MYPRODHOST
  tasks:
  - debug:
      msg: "{{ ansible_hostname }}"
  - debug:
      msg: "{{ developmenthosts if ( ansible_hostname |regex_search('dev|tst|test|eng') ) else  productionhosts }}"


Q: Upload ALAsset URL images to the server I am trying to access iPhone's photo album photo images through ALAssetsLibrary and upload(send) the images to my server. I am being successful accessing the photo album and get the asset URL of each images, via the following code:
    - (void)viewDidLoad
{
    [super viewDidLoad];

    void (^assetEnumerator)(struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if(result != NULL) {
            NSLog(@"See Asset: %@", result);
            [assets addObject:result];
            // Here storing the asset's image URL's in NSMutable array urlStoreArr
            NSURL *url = [[result defaultRepresentation] url];
            [urlStoreArr addObject:url];
        }
    };

    void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) =  ^(ALAssetsGroup *group, BOOL *stop)
    {

        if(group != nil) {
            [group enumerateAssetsUsingBlock:assetEnumerator];
        }
        [self.activity stopAnimating];
        [self.activity setHidden:YES];
    };
    assets = [[NSMutableArray alloc] init];
    library = [[ALAssetsLibrary alloc] init];
    [library enumerateGroupsWithTypes:ALAssetsGroupAlbum
                           usingBlock:assetGroupEnumerator
                         failureBlock: ^(NSError *error) {
                             NSLog(@"Failure");
                         }];

    urlStoreArr = [[NSMutableArray alloc] init];
}

    -(void) UploadImagesToServer
{

for (int i=0; i<[urlStoreArr count]; i++)

{

       // To get the each image URL here...

        NSString *str = [urlStoreArr objectAtIndex:i];
        NSLog(@"str: %@",str);

        // Need to upload the images to my server..

    }

}

I want to upload the images which i got from the device asset's URL to my server. Could someone please advise how can i program it for sending the images to the server using this case?
Thank you!

A: you could use the below SO post code for uploading images to server.
How can I upload a photo to a server with the iPhone?
upload image from iphone to the server folder


Q: How to use socket.io and Express.js with IISNode I have setup a windows 2012 r2 server with IIS, IISNode and Rewrite module.
This all seems the work just fine, simple applications with Express also seem to work well.
But when I add socket.io to the application, I get stuck. I get following Error:
*

GET http://mywebsiteadress/socket.io/socket.io.js net::ERR_ABORTED

*
I use IIS version 8.5.96, express version 4.16.2 and socket.io version 2.0.4.
Server:
let app = require('express')(),
    server = require('http').Server(app),
    io = require('socket.io')(server);

server.listen(process.env.PORT);

app.get('/',(req,res)=>{
    res.sendFile(__dirname + '/index.html');
})

io.on('connection',socket=>{
    socket.emit('test','working');
});

EDIT:
I changed
io = require('socket.io')(server);

to:
io = require('socket.io')(server,{
        path: '/SocketIO/socket.io'
    });

And now i'm getting this error:
polling-xhr.js:264 GET http://mywebsiteadress/socket.io/?EIO=3&transport=polling&t=M6RHmTd 404 (Not Found)
i.create @ polling-xhr.js:264
i @ polling-xhr.js:165
o.request @ polling-xhr.js:92
o.doPoll @ polling-xhr.js:122
r.poll @ polling.js:118
r.doOpen @ polling.js:63
r.open @ transport.js:80
r.open @ socket.js:245
r @ socket.js:119
r @ socket.js:28
r.open.r.connect @ manager.js:226
r @ manager.js:69
r @ manager.js:37
r @ index.js:60
(anonymous) @ (index):12

Client:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Socket IO Test Page</title>
</head>
<body>
    <script src='socket.io/socket.io.js'></script>
    <script>
        let socket = io.connect()

        socket.on('test',data => {
            console.log(data);
        })
    </script>
</body>
</html>

Web.config:
<configuration>
    <system.webServer>

        <handlers>
            <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
        </handlers>

        <rewrite>
            <rules>
                <rule name="LogFile" patternSyntax="ECMAScript">
                    <match url="socket.io"/>
                    <action type="Rewrite" url="index.js"/>
                </rule>
            </rules>
        </rewrite>

    <webSocket enabled="false"/>

    </system.webServer>
</configuration>

What am I doing wrong? I have searched the internet and this forum, and tried a lot of things, but none seem to solve it for me.
I can't seem to find documentation on setting up Socket.io with IISNode?
I hope someone can help me.
Kind regards

A: Looks like your rewrite rule is wrong. Did you forget to add ".+" after your url attribute?
 <rule name="SocketIO" patternSyntax="ECMAScript">
     <match url="socket.io.+"/>
     <action type="Rewrite" url="server.js"/>
 </rule>


Q: Select options won't display when parent div is shown after being hidden I have a select box that is nested inside three divs as such:

                   Name:
                   <select name="ddlName" id="ddlName">
                    <option value="Name1">Name1</option>
                    <option value="Name2">Name2</option>
                    <option value="Name3">Name3</option>
                   </select>

              ...

         ...

    ...

The CSS:
#entry
{
    position:absolute;
    width:527px;
    height:364px;
    left:69px;
    top:214px;
    z-index:2;
    display:none;
}

The following jquery code is to show/hide the entry div based on clicking certain buttons:
$("document").ready(function() {
    $("#addButton").live("click", function(event) {
        $("#entry").show();
    })
    $("#closeEntry").live("click", function(event) {
        $("#entry").hide();
    })
})

The problem is that when I first click the add button, it shows the entry div and the select box works fine. After I click the close button and click the add button again, the select box will not let me select another option. It works fine in firefox but not ie7.

A: Found that it has something to do with jQuery UI CSS file. When I exclude it, the works. When I added an effect to the hide() and show() function, then it worked properly.