text:
Q: Suggest Java Swing Component libraries I'm currently looking for a Java Swing all-in-one professional component pack to create good-looking UIs, charts, reports and so on. Surprisingly, after a couple of hours of googling all I was able to find is JIDE. Even though it looks sexy, I need more alternatives to choose from. Are there any recommendations? Thanks.

A: Have a look at SwingX:

*

*http://www.swinglabs.org/

*https://swingx.dev.java.net/
For charts, look at JFreeChart. For reports, look at JasperReports or Eclipse BIRT.

A: SwingZx
Simple swing component lib with cool buttons.

A: Have a look at this lib: swing-components MIT license


text:
Q: asp.net mvc tinymce usage? scripts

html
@using (Html.BeginForm("_AddPost", "Posts", FormMethod.Post, new { id = "form_post" }))
{

          <input type="file" name="File" id="File" />

         @Html.LabelFor(model => model.PostTypeId)

          @Html.DropDownListFor(model => model.PostTypeId, ViewBag.PostTypes as SelectList, "--- Haber Tipi ---", new { @class = "custom_select" })

          @Html.ValidationMessageFor(model => model.PostTypeId)

      ...

           @Html.LabelFor(model => model.Body)

           @Html.TextAreaFor(model => model.Body, new { @class = "custom_textarea" })

           @Html.ValidationMessageFor(model => model.Body)

           @Html.LabelFor(model => model.AuthorId)

           @Html.DropDownListFor(model => model.AuthorId, ViewBag.Authors as SelectList, "--- Yazarlar ---", new { @class = "custom_select" })

           @Html.ValidationMessageFor(model => model.AuthorId)

            @Html.LabelFor(model => model.IsActive)

            @Html.CheckBoxFor(model => model.IsActive)

            @Html.ValidationMessageFor(model => model.IsActive)

             <input type="submit" value="Ekle" class="button_gray" />

}

model
public class PostViewModel
{
    public int Id { get; set; }

    ...

    [Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
    [Display(Name = "Haber İçerik")]
    [AllowHtml]
    public string Body { get; set; }

    ...

    [Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
    [Display(Name = "Haber Tipi")]
    public Nullable<int> PostTypeId { get; set; }

    [Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
    [Display(Name = "Yazar")]
    public Nullable<int> AuthorId { get; set; }

    [Display(Name = "Kategori")]
    public Nullable<int> CategoryId { get; set; }

    ...

    [Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
    [Display(Name = "Yayında")]
    [DefaultValue(true)]
    public bool IsActive { get { return true; } set { } }

    public HttpPostedFileBase File { get; set; }
}

when I post view tinymce editor content,it does not bind to model property. Other properties bind, ony tinymce not.
I mean in controller action
model.Title         // is my expected
model.Description   // is my expected
model.Body          // null

controller
public ActionResult _AddPost()
{
    using (NewsCMSEntities entity = new NewsCMSEntities())
    {
        // following lines are true. I can see dropdownlist values...
        ViewBag.PostTypes = new SelectList(entity.PostTypes.ToList(), "Id", "Name");
        ViewBag.Authors = new SelectList(entity.Authors.ToList(), "Id", "Name");
        ViewBag.Categories = new SelectList(entity.Categories.ToList(), "Id", "Name");

        return PartialView(new PostViewModel());
    }
}

[HttpPost]
public ActionResult _AddPost(PostViewModel viewModel)
{
    Posts post = new Posts();
    post = AutoMapper.Mapper.Map<PostViewModel, Posts>(viewModel);
    PostImages postImage = new PostImages();
    HttpPostedFileBase file = viewModel.File;

    using (NewsCMSEntities entity = new NewsCMSEntities())
    {
        if (ModelState.IsValid)
        {
             // add post to db
        }
        else
        {
            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                     Console.WriteLine(error);
                     // error message model.Body is null
                }
        }
   }

All model properties are my expected only Body property is not. What am I missing?
Thanks...

A: The trick with TinyMCE is that it replaces the textarea with an iframe. In case of standard POST, the TinyMCE handles the updating of the original textarea by itself, but when you put AJAX into play you need to do it by yourself. It can be done in beforeSerialize callback of jQuery Form Plugin which you are using:
$(function () {
    $('#form_post').ajaxForm({
        beforeSerialize: function($form, options) { tinyMCE.triggerSave(); },
        beforeSubmit: ShowRequest,
        success: SubmitSuccesful,
        error: AjaxError
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: WordPress Notice: Undefined variable: post in C: Consider:
<?php
    /*
        Portfolio 2 Columns
    */
?>

<?php
    get_header();
?>

    <?php
        $terms = get_terms("tagportfolio");
        $count = count($terms);
        echo '
';

            echo '
All
';

            if ( $count > 0 ){

                foreach ( $terms as $term ) {

                    $termname = strtolower($term->name);
                    $termname = str_replace(' ', '-', $termname);
                    echo '
' . $term->name .
                         '
';
                }
            }
            echo "
";
        ?>

        <?php
            $loop = new WP_Query(array('post_type' => 'project', 'posts_per_page' => -1));
            $count =0;
        ?>

            <?php
                if ( $loop ) :

                    while ( $loop->have_posts() ) : $loop->the_post();
            ?>

            <?php
                        $post = '';

                        $terms = get_the_terms($post->ID, 'tagportfolio' );

                        if ( $terms && ! is_wp_error( $terms ) ) :
                            $links = array();

                            foreach ( $terms as $term )
                            {
                                $links[] = $term->name;
                            }
                            $links = str_replace(' ', '-', $links);
                            $tax = join( " ", $links );
                        else :
                            $tax = '';
                        endif;
            ?>

            <?php
                        $infos = get_post_custom_values('_url');
            ?>

                        <li class="portfolio-item <?php echo strtolower($tax); ?> all">

<a href="<?php the_permalink() ?>"><?php the_post_thumbnail('project-large'); ?>

<a href="<?php the_permalink() ?>"><?php the_title(); ?>

<a href="<?php the_permalink() ?>"><?php echo get_the_excerpt(); ?>

<a href="<?php echo $infos[0]; ?>" target="_blank">Live Preview → <a href="<?php the_permalink() ?>">More Details →

            <?php
                    endwhile; else:
            ?>

Sorry, no portfolio entries for while.

            <?php
                endif;
            ?>

I'm getting these notices when debug is true for WordPress code above:

Notice: Undefined variable: post in C:....php on line 50
Notice: Trying to get property of non-object in C:....php on line 50

Line 50 is:  $terms = get_the_terms($post->ID, 'tagportfolio' );
How can I resolve this issue and get rid of the notice?

A: Remove the line with $post = '';. $post is a global variable.
Then you tried to access the $post property ID:
$terms = get_the_terms($post->ID, 'tagportfolio' );

This is why you are getting Undefined variable: post in C:

A: You can try the following way.
Here it is:
global $wp_query;
$post = $wp_query->post;


text:
Q: Can't figure out how to correctly check if there is an appointment in between times with Carbon and Laravel This might be much simpler than i think it is, but i've scratched my head around it for a while now. Probably too long, and stuck with the same wrong solutions to get outside my own head.
So i could use some help.
I'm constructing an appointment system, and lets say that an appointment is 1 hour long. Between 12-13. I can make sure that no appointments are started during that time. But, my problem is. If i create an appointment and that is 2 hours long. Then, right now someone can book it at 11.30, since it will finish at 13.30. Which obviously shouldn't be possible, because there is an appointment in between.
I will supply my current code below, and hope that some of you, hopefully smarter for me can see, what probably is an easy solution. I have removed all my testcode, since they have not shown any promise.
        $intervals = CarbonInterval::minutes('15')->toPeriod($start, $end);
        foreach ($intervals as $time) {
            $this_time = Carbon::parse($time)->tz('Europe/Stockholm');
            $current_mission_end_from_time = Carbon::parse(roundToNearestMinuteInterval($this_time->addMinutes($current_mission_length)));

            if ($busy_between->isNotEmpty()) {
                foreach ($busy_between as $busy) {
                    if ($time->between($busy['start'], $busy['end'])) {
                        $busy_times->add($time->format('H:i'));
                    }
                }
            }
        }

In the end, all non-possible times will be saved to $busy_times, then i will run this code to show any free times.
            foreach ($intervals as $time) {
                if (!$busy_times->contains($time->format('H:i'))) {
                    $free_times->add($time->format('H:i'));
                }
            }

UPDATE
Here is the solution code added to the above, from the correct answer below, if anyone else wonders.
            if ($busy_between->isNotEmpty()) {
                foreach ($busy_between as $busy) {
                    if ($time->between($busy['start'], $busy['end'])) {
                        $busy_times->add($time->format('H:i'));
                    }

                    $exitingAppointment = CarbonPeriod::create($busy['start'], $busy['end']);
                    $appointmentTentative = CarbonPeriod::create($time, $current_mission_end_from_time);

                    if ($exitingAppointment->overlaps($appointmentTentative)) {
                        $busy_times->add($time->format('H:i'));
                    }
                }
            }

A: Use Carbon\CarbonPeriod::overlaps:
$exitingAppointment = \Carbon\CarbonPeriod::create('2023-02-26 12:00', '2023-02-26 13:00');
$appointmentTentative = \Carbon\CarbonPeriod::create('2023-02-26 11:30', '2023-02-26 13:30');

if ($exitingAppointment->overlaps($appointmentTentative)) {
    echo "No: overlaps with existing appointment\n";
} else {
    echo "All good\n";
}


text:
Q: Error CS0246 The type or namespace name 'JsonDeserializer' could not be found (RestSharp v107) I get an error (after update RestSharp - v107) on the following line:
var contacts = new JsonDeserializer().Deserialize<List<Contact>>(response);
Error  CS0246  The type or namespace name 'JsonDeserializer' could not be found (are you missing a using directive or an assembly reference?)
using NUnit.Framework;
using RestSharp;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Net;

namespace ContactBook.ApiTests
{
public class ContactBookApiTests
{
    const string ApiBaseUrl = "URl/api";
    RestClient client;

    [SetUp]
    public void Setup()
    {
        this.client = new RestClient(ApiBaseUrl);
    }

    [Test]
    public void Test_ListContacts_CheckForSteveJobs()
    {
        // Arrange
        var request = new RestRequest("/contacts", Method.Get);

        // Act
        var response = this.client.ExecuteAsync(request);

        // Assert
        Assert.That(response.Status, Is.EqualTo(HttpStatusCode.OK));
        var contacts = new JsonDeserializer().Deserialize<List<Contact>>(response);
        Assert.That(contacts.Count, Is.GreaterThan(0));
        var firstContact = contacts[0];
        Assert.That(firstContact.firstName, Is.EqualTo("Steve"));
        Assert.That(firstContact.lastName, Is.EqualTo("Jobs"));
    }
    }

A: try this
 var response = this.client.ExecuteAsync(request).Result;

  //or better

var response = this.client.Execute(request);
....

 var contacts = JsonSerializer.Deserialize<List<Contact>>(response.Content);

A: var response = this.client.ExecuteAsync(request);

As the name suggests, this function returns Task<RestResponse>. You need to await the call.
There's also no need to explicitly deserialize the response, RestSharp will do it for you.
public async Task Test_ListContacts_CheckForSteveJobs() {
    var request = new RestRequest("/contacts", Method.Get);
    var response = await client.ExecuteAsync<Contact[]>(request);
    var contacts = response.Data;

    // Assert
    Assert.That(response.Status, Is.EqualTo(HttpStatusCode.OK));
    Assert.That(contacts.Count, Is.GreaterThan(0));
    var firstContact = contacts[0];
    Assert.That(firstContact.firstName, Is.EqualTo("Steve"));
    Assert.That(firstContact.lastName, Is.EqualTo("Jobs"));
}


text:
Q: having an image thumbnail size exactly across browser I'm trying to come up with a script that will have a number of thumbnails across (in width) the browser. I want it to be able to be flush and not have gaps on the sides. The thumbnails should always be the same size, and I'm guessing that the only way is the change the spacing between each image. But can someone help me out? Let me know if my question is unclear.
EDIT: here's an example: http://www.beautyineverything.com/
Thank you!

A: Something like this?
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>

    <title>sandbox</title>
    <meta http-equiv='content-type' content='text/html; charset=UTF-8'/>

        <?php
            for ( $n = 10; $n < 30; ++$n) {
                $backgroundColor = '#' . sprintf('%02x%02x%02x', $n * 8, $n * 8, $n * 8);
                echo "

";
            }
        ?>

Resizing images could be written in a bit smarter way so that instead of 223+223+223+223+223+223+223+216 they would be 223+222+222+222+222+222+222+222. For this, width of each column should be calculated individually, so that widths of columns vary only by 1px max.

A: This might sound primitive but tables were designed for something like this only.
one solution is to have a table and put your images as background-image of the cells. (or put it inside and give it a height and width 100%) Its is easy to keep control over the cell size and margins/padding.. that is why they were so popular for structural stuff.
Before ruling the idea out, do note that (apart form the fact that i HATE to use tables for designing and positioning stuff, but do not hesitate to use it for what it was meant to be) making tables will reduce the amount of code to be written. use css to size the cells and table. use inline to put background image. no js functions wat-so-ever.
please drop a comment if you disagree of if i am missing something :)


text:
Q: Android: help Text Watcher , List compare .logical error with afterTextChanged facing problem in searching and displaying the list using text watcher.
it is a simple search operation in the List.
firstly the data is retrieved from the .txt line by line.
first word of string is stored in the list content and now i want to perform search operation on this content list and display the result in listview
here is the code
enter code here

package com.android;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.TextView;

public class MyListDemoActivity extends ListActivity {
    /** Called when the activity is first created. */
    TextView tv;
    // final String[] values=new String[]{"android","Windows",
    // "ios","BlackBerry","Java",".Net","WebOS", "Ubuntu", "Windows7"};
    //String[] content;
    List<String> content ;

    AutoCompleteTextView actv;
    List<String> arr_sort;
    ArrayAdapter<String> adapter;
    ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String line = " ";
        LineNumberReader linenoreader = null;
        StringTokenizer stringtokanixer = null;
        content=new ArrayList<String>();
        lv=(ListView)findViewById(android.R.id.list);

        try {

            InputStream istream = getResources().openRawResource(R.raw.hihihi);
            InputStreamReader streamreader = new InputStreamReader(istream);

            linenoreader = new LineNumberReader(streamreader);
            linenoreader.mark(15);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }// try catch ends here

        Log.v("getting", "working");

        for (int i = 0; i < 6; i++) {
            try {
                line = linenoreader.readLine();
            } catch (IOException e) {

                e.printStackTrace();
            }
            Log.v("getting", line);
            stringtokanixer = new StringTokenizer(line);

            String st=stringtokanixer.nextToken();
            content.add(st);
        }// for ends here

                    adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,content);
        //          setListAdapter(adapter);

                    lv.setAdapter(adapter);
                    tv= (TextView)findViewById(R.id.textView1);

                    actv=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
                    actv.addTextChangedListener(new TextWatcher() {
                        int len=0;
                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count,
                                int after) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            // TODO Auto-generated method stub

                            len=actv.getText().length();

                            for(int i=0;i<content.size();i++)
                            {
                                if(len<=content.get(i).length())
                                {
                                    if(actv.getText().toString().equalsIgnoreCase((String) content.get(i).subSequence(0, len)))
                                    {

                                        arr_sort.add(content.get(i));

                                    }

                                }

                            }

                            adapter=new ArrayAdapter<String>(MyListDemoActivity.this,android.R.layout.simple_list_item_1,arr_sort);
                            setListAdapter(adapter);
                        }
                    }); // text watcher class ends here

    }// on create ends here
    public void onListItemClick(ListView ls,View v, int position,long id) {
      tv.setText(content.get(position));

      //tv.setText(content[position]) // in case of string

    }// endsd here onListItemClick(
}

here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=" " >

      </AutoCompleteTextView>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
         >
    </ListView>

</LinearLayout>

here is txt file
joke happy
hota happy okgame
ok happy okgame
asitis happy
okgame happy
oktested happy happy

i guess there is logical error in afterTextChanged but cant figure it out.

A: You don't need to recreate adapter. And you should trim strings whan compare tham. Small fixes (it works :)):
public class MyListDemoActivity extends ListActivity {
/**
 * Called when the activity is first created.
 */
TextView tv;
// final String[] values=new String[]{"android","Windows",
// "ios","BlackBerry","Java",".Net","WebOS", "Ubuntu", "Windows7"};
//String[] content;
List<String> content;

AutoCompleteTextView actv;
List<String> arr_sort = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView lv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String line = " ";
    LineNumberReader linenoreader = null;
    StringTokenizer stringtokanixer = null;
    content = new ArrayList<String>();
    lv = (ListView) findViewById(android.R.id.list);

    try {

        InputStream istream = getResources().openRawResource(R.raw.hihihi);
        InputStreamReader streamreader = new InputStreamReader(istream);

        linenoreader = new LineNumberReader(streamreader);
        linenoreader.mark(15);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }// try catch ends here

    Log.v("getting", "working");

    for (int i = 0; i < 6; i++) {
        try {
            line = linenoreader.readLine();
        } catch (IOException e) {

            e.printStackTrace();
        }
        Log.v("getting", line);
        stringtokanixer = new StringTokenizer(line);

        String st = stringtokanixer.nextToken();
        content.add(st);
    }// for ends here
    arr_sort.addAll(content);
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arr_sort);
    //          setListAdapter(adapter);

    lv.setAdapter(adapter);
    tv = (TextView) findViewById(R.id.textView1);

    actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
    actv.addTextChangedListener(new TextWatcher() {
        int len = 0;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
            arr_sort.clear();
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            len = actv.getText().toString().trim().length();

            for (int i = 0; i < content.size(); i++) {
                if (len <= content.get(i).length()) {
                    if (actv.getText().toString().trim().equalsIgnoreCase((String) content.get(i).subSequence(0, len))) {

                        arr_sort.add(content.get(i));

                    }

                }

            }

            adapter.notifyDataSetChanged();
        }
    }); // text watcher class ends here

}// on create ends here

public void onListItemClick(ListView ls, View v, int position, long id) {
    tv.setText(content.get(position));

    //tv.setText(content[position]) // in case of string

}// endsd here onListItemClick(

}

A: solved
im working on icecream sandwitch...
it  worked with this code...
public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                    arr_sort = new ArrayList<String>();

                    len = actv.getText().length();

                    for (int i = 0; i < content.size(); i++) {
                        if (len <= content.get(i).length()) {
                            if (actv.getText()
                                    .toString()
                                    .trim()
                                    .equalsIgnoreCase(
                                            (String) content.get(i).subSequence(0,
                                                    len))) {

                                arr_sort.add(content.get(i));
                                Log.v("infor loop afterTextChanged", s.toString());
                            }

                        }

                    }

        //          adapter.notifyDataSetChanged();

                    adapter = new ArrayAdapter<String>(MyListDemoActivity.this,
                        android.R.layout.simple_list_item_1, arr_sort);
                    setListAdapter(adapter);

    }


text:
Q: Hiding html elements based on its child class jQuery I have two forms(Login and register) in which one is hidden when the page is loaded(Login form is hidden). Users can toggle between them with a button. When login fails it throws a error and it is shown in login form. The issue is when the page is loaded after login fails it hides the login form and shows the Registers form. Only when the user clicks on login form button it shows the error. I want to show the form which has error when the page is reloaded.
$(document).ready(function(){
    $('#login_form').hide();
});

This is my login form
<form action="/login" method="post" id="login_form">
 {{csrf_field()}}

has('email') ? ' has-error' : '' }}">
<input type="text" name="email" id="login_email" placeholder="Email"/>
 @if ($errors->has('email'))

  {{ $errors->first('email') }}

 @endif

has('password') ? ' has-error' : '' }}">
  <input type="password" name="password" id="login_pass" placeholder="Password"/>
  @if ($errors->has('password'))

  {{ $errors->first('password') }}

  @endif

   <input type="submit" class="btn" id="login_sbt_btn" value="Login"/>

 </form>

The help-block gets added only when the error is there in the form
This works good but it hides all the form when the page is loaded first.
var $errorField = $('.has-error');
if($errorField) {
    $('form').hide();
    $errorField.closest('form').show();
} else {
    $('#login_form').hide();
}

A: $ returns an array-like object. You have to check the length property like this:
var $errorField = $('.has-error');
if($errorField.length != 0) {
    $('form').hide();
    $errorField.closest('form').show();
} else {
    $('#login_form').hide();
}


text:
Q: PHP OR statement issue when validating file extension I have an issue when using PHP OR statements to validate the extension of the uploaded file. The below code should check the file extension and define an error if it does not equal PNG, JPG, JPEG or GIF.
This is my code:
$file_extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if($file_extension !== "png" || "jpg" || "jpeg" || "gif") {
    $error = 'Thumbnail file must be a PNG, JPG, JPEG or GIF';
}

However it will only work if I define just one file extension, for example:
if($file_extension !== "png") {
    $error = 'Thumbnail file must be a PNG';
}

This will accept PNG files and refuse any others.
What do I need to do to get this code to work as intended?

A: You can't use the OR operator as you want to. You could do something like this:
$file_extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));

if(!in_array($file_extension, array("png", "jpg", "jpeg", "gif"))) {
    $error = 'Thumbnail file must be a PNG, JPG, JPEG or GIF';
}

For more information about in_array() see the manual: http://php.net/manual/en/function.in-array.php

A: Solution 1:
if(!($file_extension == "png" || $file_extension == "jpg" || $file_extension == "jpeg" || $file_extension == "gif")) {
    $error = 'Thumbnail file must be a PNG, JPG, JPEG or GIF';
}

Solution 2:
if($file_extension !== "png" && $file_extension !== "jpg" && $file_extension !== "jpeg" && $file_extension !== "gif")) {
    $error = 'Thumbnail file must be a PNG, JPG, JPEG or GIF';
}

Solution 3:
$ext = array('png', 'jpg', 'jpeg', 'gif');
if(!in_array($file_extension, $ext)) {
    $error = 'Thumbnail file must be a PNG, JPG, JPEG or GIF';
}

Solution one is based on the negation of alternatives. This is the same as solution two (which is the sum of negated). These two solutions are equal in sense of logic, but...
Solution 3 is of course better. That is because, each time in the future You will need to check the extension, the array of extensions will be available to You. And writing everytime, the same if with the same "constants" is wrong, and future improvements are difficult.

In that case, try to declare array of possible extensions at the beginning of your script, in your config class, or in CONSTANTS (left it to you), and every time you need to check the file extensions, just check the in_array. And in the future, if you need additional extensions, or decide that for example gif is not useful anymore, just change this one array. Every other line of code should stay as it is.

A: I have 2 solutions for you
First Solution :
<?php
    $file_extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if($file_extension !== "png" ||
    $file_extension !== "jpg" ||
    $file_extension !== "jpeg" ||
    $file_extension !== "gif") {
        $error = 'Thumbnail file must be a PNG, JPG, JPEG or GIF';
    }
?>

Second Solution :
<?php
    $file_extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if(!in_array($file_extension, array('png','jpg','jpeg','gif'))) {
        $error = 'Thumbnail file must be a PNG, JPG, JPEG or GIF';
    }
?>


text:
Q: How to build a testing class I'm currently creating a program for a specific specification. I have completed the first task, and to prove it runs correctly i'm required to "write a simple class called PizzaBuild which contains a main method which demonstrates this working."
Does anyone have any tips on doing this, because i've no idea how to do it unless i literally copy all the code into the one class, but that'd defeat the purpose.
Thanks a lot.

A: If your two classes are in the same project, you can write the new class as if it has visibility of the other.
ie)
Pizza p = new Pizza();
and then exercise it
System.out.println(p.pepperoni);  or something
Otherwise, as people have mentioned above, you can import the file and then use it the same way.

A: You've written a class that you say works. Since we don't know it's name, for our purposes, we'll call it MyClass.  MyClass also has some methods which, when used, demonstrates that MyClass works properly.
public class PizzaBuild
{
    public static void main(String[] args)
    {
        MyClass mine = new MyClass();

        mine.method1();

        mine.method2();

        // and so on
    }
}


text:
Q: Let $A$ be a non-singular matrix such that $3ABA^{-1}+A=2A^{-1}BA$ then determine whether $A+B$ and $ABA^{-1}-A^{-1}BA$ are singular or non-singular Let $A$ be a non-singular matrix such that $$3ABA^{-1}+A=2A^{-1}BA$$ then determine whether $A+B$ and $ABA^{-1}-A^{-1}BA$ are singular or non-singular.
My Attempt:
If I put $A=I$ then both $A+B$ and $ABA^{-1}-A^{-1}BA$ are singular. But I am not able to generate a proper way to prove

A: \begin{align}
A+B&= A(I+A^{-1}B)=(I+BA^{-1})A\\
(A+B)(2A)&=A(I+A^{-1}B)(2A)\\
(A+B)(2A)&=A(2A+2A^{-1}BA)\\
&=A(2A+3ABA^{-1}+A)\\
&=A^2(3I+3BA^{-1})\\
&= 3A^2(I+BA^{-1})\\
2(I+BA^{-1})A^{2}&=3A^{2}(I+BA^{-1})\\
2^n\det(I+BA^{-1})&=3^n\det(I+BA^{-1})
\end{align}
Hence $I+BA^{-1}$ is not invertible which implies that $A+B$ is not invertible.

\begin{align}
ABA^{-1}-A^{-1}BA &= \frac13 \left(3ABA^{-1}-3A^{-1}BA \right)\\
&=\frac13(-A-A^{-1}BA)\\
&= -\frac13(I+A^{-1}B)A
\end{align}
Since $I+A^{-1}B$ is singular, $ABA^{-1}-A^{-1}BA$ is singular as well.

A: Instead of trying to evaluate it for a particular case of $A$, try solving the equation for $A+B$ and $ABA^{-1}-A^{-1}BA$.


text:
Q: Is there a simple proof for the behaviour of this solution? Let $0 <s \le 1$, and suppose that $0 <b \le a$ satisfy
$$ ab=s,a+b=1+\sqrt{s}.$$
Then $a \ge 1$.
I have a proof for this claim (see below), but I wonder if there are easier or alternative proofs.

In particular, my proof is based on explicit computation of $a,b$ in terms of $s$ (solving the quadratic). Can we avoid that?

The proof:
We have $a+\frac{s}{a}=1+\sqrt s$, or
$$ a^2-(1+\sqrt s)a+s=0,$$
which implies (since we assumed $a \ge b$) that
$$ a=\frac{1}{2}(1+\sqrt s+\sqrt{1+2\sqrt s-3s}).$$
Thus, $a \ge 1$ iff $$\sqrt s+\sqrt{1+2\sqrt s-3s} \ge 1 \iff \\
1+2\sqrt s-2s+2\sqrt s \sqrt{1+2\sqrt s-3s} \ge 1 \iff \\ \sqrt s-s+\sqrt s \sqrt{1+2\sqrt s-3s} \ge 0 \iff \\
1-\sqrt s+ \sqrt{1+2\sqrt s-3s} \ge 0 \iff \\ \sqrt{1+2\sqrt s-3s} \ge \sqrt s-1.$$
(We passed from the first line to the second line by squaring).
The last inequality clearly holds, since the LHS $\ge 0$, and the RHS is $\le 0$.
(since we assumed $s \le 1$).

A: Hint: $(a-1)(b-1) = ab - a - b + 1  = s - \sqrt{s} \leq 0 $.
Hence, conclude that $ a \geq 1 \geq b $, with equality when $ s = 1$.


text:
Q: Dynamic character generator; Generate all possible strings from a character set I want to make a dynamic string generator that will generate all possible unique strings from a character set with a dynamic length.
I can make this very easily using for loops but then its static and not dynamic length.
// Prints all possible strings with the length of 3

for a in allowedCharacters {
    for b in allowedCharacters {
        for c in allowedCharacters {
            println(a+b+c)
        }
    }
}

But when I want to make this dynamic of length so I can just call generate(length: 5) I get confused.
I found this Stackoverflow question But the accepted answer generates strings 1-maxLength length and I want maxLength on ever string.

A: As noted above, use recursion. Here is how it can be done with C#:
static IEnumerable<string> Generate(int length, char[] allowed_chars)
{
    if (length == 1)
    {
        foreach (char c in allowed_chars)
            yield return c.ToString();
    }
    else
    {
        var sub_strings = Generate(length - 1, allowed_chars);

        foreach (char c in allowed_chars)
        {
            foreach (string sub in sub_strings)
            {
                yield return c + sub;
            }

        }
    }
}

private static void Main(string[] args)
{

    string chars = "abc";

    List<string> result = Generate(3, chars.ToCharArray()).ToList();

}

Please note that the run time of this algorithm and the amount of data it returns is exponential as the length increases which means that if you have large lengths, you should expect the code to take a long time and to return a huge amount of data.

A: Translation of @YacoubMassad's C# code to Swift:
func generate(length: Int, allowedChars: [String]) -> [String] {
    if length == 1 {
        return allowedChars
    }
    else {
        let subStrings = generate(length - 1, allowedChars: allowedChars)

        var arr = [String]()
        for c in allowedChars {
            for sub in subStrings {
                arr.append(c + sub)
            }
        }

        return arr
    }
}

println(generate(3, allowedChars: ["a", "b", "c"]))

Prints:

aaa, aab, aac, aba, abb, abc, aca, acb, acc, baa, bab, bac, bba, bbb, bbc, bca, bcb, bcc, caa, cab, cac, cba, cbb, cbc, cca, ccb, ccc

A: While you can (obviously enough) use recursion to solve this problem, it quite an inefficient way to do the job.
What you're really doing is just counting. In your example, with "a", "b" and "c" as the allowed characters, you're counting in base 3, and since you're allowing three character strings, they're three digit numbers.
An N-digit number in base M can represent NM different possible values, going from 0 through NM-1. So, for your case, that's limit=pow(3, 3)-1;. To generate all those values, you just count from 0 through the limit, and convert each number to base M, using the specified characters as the "digits". For example, in C++ the code can look like this:
#include <string>
#include <iostream>

int main() {
    std::string letters = "abc";
    std::size_t base = letters.length();
    std::size_t digits = 3;

    int limit = pow(base, digits);

    for (int i = 0; i < limit; i++) {
        int in = i;
        for (int j = 0; j < digits; j++) {
            std::cout << letters[in%base];
            in /= base;
        }
        std::cout << "\t";
    }
}

One minor note: as I've written it here, this produces the output in basically a little-endian format. That is, the "digit" that varies the fastest is on the left, and the one that changes the slowest is on the right.


text:
Q: Is there a way for me to combine these 3 methods into just 1? Basically, I have 3 delegate methods that have almost the exact same code except for 1 line in each and the parameters. I realize that I can encapsulate a lot of the code to make 3 or 4 lines of code in each method, but I'm wondering if there's a way to create just 1 method.
Also, the methods being called on tempData have the same method name as the delegate methods below, but they are actually different methods.
- (void)addElement:(NSString *)currentElement FromKeyboard:(NSString *)name {

    UIView *tempView;
    NSMutableArray *tempViewList;
    EquationData *tempData;

    if ([name isEqualToString:@"leftEqCellKeyboard"]) {
        tempData = leftData;
        tempViewList = leftEqViewList;
        tempView = equationCell.leftView;
    }

    if ([name isEqualToString:@"rightEqCellKeyboard"]) {
        tempData = rightData;
        tempViewList = rightEqViewList;
        tempView = equationCell.rightView;
    }

    [tempData addElement:currentElement]; // different

    if ([tempViewList count] != 0)
        [self clearViewsStoredIn:tempViewList];
    [self setUpView:tempView fromArray:tempData.equation toArray:tempViewList];
}

- (void)changeState:(NSString *)stateName FromKeyboard:(NSString *)name {

   UIView *tempView;
    NSMutableArray *tempViewList;
    EquationData *tempData;

 if ([name isEqualToString:@"leftEqCellKeyboard"]) {
        tempData = leftData;
        tempViewList = leftEqViewList;
        tempView = equationCell.leftView;
    }

    if ([name isEqualToString:@"rightEqCellKeyboard"]) {
        tempData = rightData;
        tempViewList = rightEqViewList;
        tempView = equationCell.rightView;
    }

    [tempData changeState:stateName]; // different

    if ([tempViewList count] != 0)
        [self clearViewsStoredIn:tempViewList];

       [self setUpView:tempView fromArray:tempData.equation toArray:tempViewList];

}

- (void)changeCharge:(NSString *)chargeIncrease FromKeyboard:(NSString *)name {

    UIView *tempView;
    NSMutableArray *tempViewList;
    EquationData *tempData;

if ([name isEqualToString:@"leftEqCellKeyboard"]) {
        tempData = leftData;
        tempViewList = leftEqViewList;
        tempView = equationCell.leftView;
    }

    if ([name isEqualToString:@"rightEqCellKeyboard"]) {
        tempData = rightData;
        tempViewList = rightEqViewList;
        tempView = equationCell.rightView;
    }
    [tempData changeCharge:chargeIncrease]; // different

    if ([tempViewList count] != 0)
        [self clearViewsStoredIn:tempViewList];

    [self setUpView:tempView fromArray:tempData.equation toArray:tempViewList];

}

A: (Perhaps you should check out http://codereview.stackexchange.com)
The "different" part is always of the form [tempData doSomethingOn:aString];, so you can parametrize with the selector "doSomethingOn:":
-(void)doSomethingOnString:(NSString*)parameter
              withSelector:(SEL)selector
              fromKeyboard:(NSString*)name
{
    // The common parts before

    [tempData performSelector:selector withObject:parameter];

    // The common parts after
}

-(void)addElement:(NSString *)currentElement FromKeyboard:(NSString *)name {
    [self doSomethingOnString:currentElement
                 withSelector:@selector(addElement:)
                 fromKeyboard:name];
}

// etc.

See also:

*

*-performSelector:withObject:

*The "Selector" concept in Objective-C


text:
Q: I want to compute specific field in my db depends on ID_number This is my model
public function total_late()
    {

        $query = "SELECT sum(late_deduction) as late_deduction FROM tbl_dtr";
        $result = $this->db->query($query);
        return $result->row()->late_deduction;
    }

This the image of the database:

This is the image of my table:

This is my another model for my table in view
function get_faculty_payroll($limit, $start, $string = "", $orderField, $orderDirection)
    {
       $this->db->group_start()
                        ->where('tbl_employee' . '.department_id', 3)
                ->group_end()
                ->group_start()
                        ->or_like('first_name', $string)
                        ->or_like('last_name', $string)
                ->group_end()
                ->join('tbl_employee_department', 'tbl_employee.department_id = tbl_employee_department.department_id')
                ->join('tbl_rates', 'tbl_employee.ID_number = tbl_rates.ID_number')
                ->limit($limit, $start)
                ->order_by($orderField, $orderDirection);
       $query = $this->db->get('tbl_employee');
       return $query->result();
    }

This is my table:

A: Try This,
public function total_late()
{
  $query = "SELECT sum(late_deduction) as late_deduction FROM tbl_dtr where ID_number = 'C-08011'";
  $result = $this->db->query($query);
  return $result->row()->late_deduction;
}

A: Your Controller
public function total_late()
{
    $retRes=$this->modelname->total_late($ID_number);
}

Your model
public function total_late($ID_number)
{

    $query = "SELECT sum(late_deduction) as late_deduction
              FROM tbl_dtr WHERE ID_number = '$ID_number'";
    $result = $this->db->query($query);
    return $result->row()->late_deduction;
}

However, this code is better, as it handles parameters safely, and avoids SQL injection vulnerabilities:
$stmt = $this->db->prepare("
    SELECT sum(late_deduction) as late_deduction
    FROM tbl_dtr WHERE ID_number = ?
");

$stmt->execute(array($ID_number));


text:
Q: Using a thread as a GameLoop What I need to do is have a loop that I can stop if I want... I made a new thread and named it GameLoop I want this to do all of my bitmap X and Y changes but when I tryed to run what I have nothing moves, It just sends me a picture. Heres my code, what did I do wrong?
 public GamePage(Context context, AttributeSet attrs)
    {
        super(context, attrs);
            //other code here
            Thread gameThread = new Thread(new GameLoop());
            gameThread.start();
    }

public class GameLoop implements Runnable
{
    public void run()
    {
        try {
            Thread.sleep(speed);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.d("LoopRunning", "The Game Loop Is Running!");

        switch ((int)possition)
        {
        case 0:
            if (counter < 110) {SunY --; counter++;}
            if (counter >= 110 && counter < 240) {SunY --; SunX ++; counter++;}
            if (counter >= 240 && counter < 360) {SunY -= 0.5; SunX ++; counter++;}
            if (counter >= 360 && counter < 662) {SunY -= 0.333; SunX ++; counter++;}
            if (counter >= 662 && counter < 1004) {SunY += 0.333; SunX++; counter++;}
            if (counter >= 1004 && counter < 1104) {SunY += 0.5; SunX++; counter++;}
            if (counter >= 1104 && counter < 1224) {SunY ++; SunX++; counter++;}
            if (counter >= 1224 && counter < 1345) {SunY ++; counter++;}
            break;

        case 1:
            if (ZombieX < canvasWidth/2 + 300) ZombieX += 10;

            if (counter2 < 110) {MoonY --; counter2++;}
            if (counter2 >= 110 && counter2 < 240) {MoonY --; MoonX ++; counter2++;}
            if (counter2 >= 240 && counter2 < 360) {MoonY -= 0.5; MoonX ++; counter2++;}
            if (counter2 >= 360 && counter2 < 662) {MoonY -= 0.333; MoonX ++; counter2++;}
            if (counter2 >= 662 && counter2 < 1004) {MoonY += 0.333; MoonX++; counter2++;}
            if (counter2 >= 1004 && counter2 < 1104) {MoonY += 0.5; MoonX++; counter2++;}
            if (counter2 >= 1104 && counter2 < 1224) {MoonY ++; MoonX++; counter2++;}
            if (counter2 >= 1224 && counter2 < 1345) {MoonY ++; counter2++;}
            break;
        }
    }
}

A: Use two nested while loops as so:
@Override public void run() {
    while (gameShouldRun) {
        while (iterateGame) {
            // do game stuff
        }
    }
}

Also, run is not looped by default. If you want the game to loop until stopped, you will need a while loop in the run method.


text: Q: Streamfield UI missing on edit page after upgrade to Wagtail 2.0.2 after upgrading one of our Wagtail sites to Wagtail 2.0.2, Django 2.0.13, Python 3 we've found some pages when editing don't display the Streamfield part, in the source there is just an empty UL element. There's no Javascript console or server error, so I'm a bit lost how to debug, or work out why it's happening on just some pages. Has anyone experienced this? Thanks


text:
Q: I wanted to select unique records from FOUR result arrays of FOUR select queries fired on same database table I'd Fired four search queries on same database table in php
results are stored in arrays as
$data['res1'],
$data['res2'],
$data['res3'],
$data['res4'],
How to find Unique records from this FOUR arrays..

A: This is the working Answer for my Question..
$data['res5'] = array_merge_recursive ( $data['res1'] , $data['res2'] , $data['res3'] , $data['res4'] );
$data['res5'] = array_map ( "unserialize" , array_unique ( array_map ( "serialize" , $data['res5'] )));
Thank You...


text:
Q: Append defs tag and use it within SVG in D3.js I am grouping 3 circles together within defs tags so they can be seen in an SVG. I have been also been recommended to use the use tag so I can see this shape that is defined within defs and recreate it anywhere within the SVG. I am creating them and appending them to data using D3.js. However, My problem is when I use the use tag, it seems to me that I am creating a new SVG every time I want to display the shape that is in the defs tag. My questions are: Is there anyway to use the defs tag without using the use tag? The second question is: How can I display that shape within the defs tag many times within only one SVG without creating an SVG every time. Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
</head>
<body>
<div id ="mainSVG">
<svg id = "packSVG" width = "1160" height = "620" style = "outline: thin solid black"
version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<symbol id= "mySymbol">
    <circle cx="200" cy="70" r="25" fill="red" />
    <circle cx="170" cy="80" r="20" fill="red" />
    <circle cx="230" cy="80" r="20" fill="red" />
    </symbol>
</defs>
</svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var dataset = [20, 60, 90, 120];
var display = d3.select("body").select("#mainSVG").select("#packSVG").selectAll("use")
  .data(dataset).enter().append("use")
  .attr("xlink:href","#MySymbol")
  .attr("transform", function (i) { i+=50; return "translate(" + i + "," + i + ")";});
</script>
</body>
</html>

Could anyone please help with this issue? Thank you very much in advance.

A: You can define the circle group using  using g element as shown below and there is no need for creating multiple svg. JSFiddle
HTML
<svg id="mainSVG" width="600" height="500">
   <defs>
    <g id="mySymbol">
        <circle cx="200" cy="70" r="25" fill="red" />
        <circle cx="170" cy="80" r="20" fill="red" />
        <circle cx="230" cy="80" r="20" fill="red" />
    </g>
  </defs>
</svg>

Javascript code
var dataset = [20, 60, 90, 120];

var display = d3.select("body")
   .select("#mainSVG")
   .selectAll("use")
   .data(dataset)
   .enter()
   .append("use")
   .attr("xlink:href","#mySymbol")
   .attr("transform", function (i) { i+=50; return "translate(" + i + "," + i + ")";});

Note that there typo in your code. The id mySymbol is misspelled as MySymbol while creating use elements.


text:
Q: Validating multiple textboxes with multiple checks I have multiple textboxes in a groupbox, and can successfully cycle through them all. However the checkNumbers sub fails to recognise blank/null entries, and also non-numeric characters. The correctValidation boolean should return true if all the criteria are met (no blanks/nulls, and must be a number between 1-20). Any thoughts on how to solve this would be appreciated.
Private Sub checkNumbers()

Try
            For Each txt As TextBox In Me.gbTechnical.Controls.OfType(Of TextBox)()
                If txt.Text <> "" And IsNumeric(txt.Text) And (Integer.Parse(txt.Text) >= 1 And Integer.Parse(txt.Text) <= 20) Then
                    correctValidation = True
                Else
                    correctValidation = False
                    MsgBox("Please ensure all numbers are between 1 and 20")
                    Exit Sub
                End If
            Next

Catch ex As Exception
            MessageBox.Show("General: Please ensure all numbers are between 1 and 20")
        End Try

    End Sub

A: I would use Integer.TryParse and then >= 1 AndAlso <= 20. You could use this LINQ query:
Dim number As Int32
Dim invalidTextBoxes =
    From txt In gbTechnical.Controls.OfType(Of TextBox)()
    Where Not Integer.TryParse(txt.Text, number) OrElse number < 1 OrElse number > 20
Dim correctValidation = Not invalidTextBoxes.Any()

Note that you should almost always use AndAlso instead of And and OrElse instead of Or since those operators are Is short-circuiting boolean operators. This can be more efficient and - more important - can prevent errors. Consider this:
Dim text = ""
If txt IsNot Nothing And txt.Text.Length <> 0 Then text = txt.Text

This fails if txt is nothing since the second condition is evaluated even if the first already was evaluated to false which causes a NullReferenceException at txt.Text.

A: if you only want a number value, why don't you try to use NumericUpDown. You can also set the Minimum and Maximum in property or use
NumericUpDown1.Maximum = 20

so, there won't be a need to do checkNumbers.
Or is there any reason that you have to use textbox??


text:
Q: How to get soci::rowset in sql query I have a table with a column name and age.
And I am trying to get all name as
soci::session& sql_session(conn->Session());
soci::rowset<std::string> rs = sql_session.prepare << select name from Person;
std::vector<std::string> plist;
std::copy(rs.begin(), rs.end(), plist.begin());

But my program crashes at std::copy.
Seems like both the containers(source and destination) are not same for std::copy.
can we do this using ORM, how?

A: If you need to read only strings it is not to use rowset, in that case you don't need to copy:
const size_t namesLimit = 100;
std::vector<std::string> plist(namesLimit);
soci::session sql_session(...); // connection details
sql_session << "select name from Person;", into(plist);

Of course if you need to get all names without hardcoding limit you can use earlier:
size_t namesLimit ;
sql_session << "select count(*) from Person", into(namesLimit);


text:
Q: devise/activeadmin can't create user from admin panel I cannot create Users or Posts when logged into my Rails app's activeadmin panel. I've got a pretty straightforward custom Devise registrations controller handling signup:
class Users::RegistrationsController < Devise::RegistrationsController
  def create
    @user = User.new(sign_up_params)
    respond_to do |format|
      if @user.save
        UserMailer.new_user(@user).deliver_now
        AdminMailer.new_user_waiting_for_approval(@user).deliver_now
        format.html { redirect_to root_path }
        flash[:success] = "You're signed up! We'll notify you when your account has been approved."
      else
        redirect_to root_path
      end
    end
  end

  private
    def sign_up_params
      params.require(:user).permit(:firstname, :lastname, :email, :password, :password_confirmation)
    end
end

Here's my AdminUser model:
class AdminUser < ActiveRecord::Base
  devise :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable

  after_create { |admin| admin.send_reset_password_instructions }
  def password_required?
    new_record? ? false : super
  end
end

When I hit save, the page reloads with entered data still intact. Console readout is:
Started POST "/admin/users" for ::1 at 2017-03-21 09:25:22 -0700
Processing by Admin::UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"LpGfS1Y+241vEIRQ+TW78SzM/+J7GnjRHAyt7Ll0ez4WYWc60/HpODJOsVg0spmpd1haTpSiNxQHOJfZlMh+sA==", "user"=>{"email"=>"j@h.com", "encrypted_password"=>"[FILTERED]", "reset_password_token"=>"[FILTERED]", "reset_password_sent_at(1i)"=>"[FILTERED]", "reset_password_sent_at(2i)"=>"[FILTERED]", "reset_password_sent_at(3i)"=>"[FILTERED]", "reset_password_sent_at(4i)"=>"[FILTERED]", "reset_password_sent_at(5i)"=>"[FILTERED]", "remember_created_at(1i)"=>"", "remember_created_at(2i)"=>"", "remember_created_at(3i)"=>"", "remember_created_at(4i)"=>"", "remember_created_at(5i)"=>"", "current_sign_in_at(1i)"=>"", "current_sign_in_at(2i)"=>"", "current_sign_in_at(3i)"=>"", "current_sign_in_at(4i)"=>"", "current_sign_in_at(5i)"=>"", "last_sign_in_at(1i)"=>"", "last_sign_in_at(2i)"=>"", "last_sign_in_at(3i)"=>"", "last_sign_in_at(4i)"=>"", "last_sign_in_at(5i)"=>"", "current_sign_in_ip"=>"", "last_sign_in_ip"=>"", "firstname"=>"a", "lastname"=>"b", "provider"=>"", "uid"=>"", "oauth_token"=>"", "approved"=>"0", "website"=>"i.com", "is_admin"=>"0"}, "commit"=>"Create User"}
Unpermitted parameters: encrypted_password, reset_password_token, reset_password_sent_at(1i), reset_password_sent_at(2i), reset_password_sent_at(3i), reset_password_sent_at(4i), reset_password_sent_at(5i), remember_created_at(1i), remember_created_at(2i), remember_created_at(3i), remember_created_at(4i), remember_created_at(5i), current_sign_in_at(1i), current_sign_in_at(2i), current_sign_in_at(3i), current_sign_in_at(4i), current_sign_in_at(5i), last_sign_in_at(1i), last_sign_in_at(2i), last_sign_in_at(3i), last_sign_in_at(4i), last_sign_in_at(5i), current_sign_in_ip, last_sign_in_ip, provider, uid, oauth_token
   (0.3ms)  BEGIN
  User Exists (0.5ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = 'j@h.com' LIMIT 1
  User Exists (0.4ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = 'j@h.com' LIMIT 1
   (0.2ms)  ROLLBACK
  AdminUser Load (0.3ms)  SELECT  "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = $1  ORDER BY "admin_users"."id" ASC LIMIT 1  [["id", 2]]
  Rendered /Users/mkeable/.rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-85ab3f5961e1/app/views/active_admin/resource/new.html.arb (297.8ms)
Completed 200 OK in 312ms (Views: 304.5ms | ActiveRecord: 1.7ms)

Why do I get two User Exists? Am certain the User doesn't exist.


text:
Q: Access Angular directive/component instances in Protractor test I have an Angular application. In Angular unit tests (karma / jasmine) I can access component instances and directives via ComponentFixture / DebugElement.
Is that somehow also possible when running an e2e test via Protractor?

A: getDebugNode(domElement) can be used to get debug element inside the application, because it should be imported from @angular/core.
ng.probe(domElement) is global and can be used to get debug element outside the application.
Component instance is available on debug element as debugElement.componentInstance. As for directive instances and other providers, debugElement.injector(SomeClass) can be used to access them, as explained in this answer.


text:
Q: Swift - AVFoundation - Inspect Video Dimensions/Aspect Ratio I have an iOS app which at the moment simply plays a video using AVFoundation from the user's library. What I would like to do is to set the orientation of the device based on the aspect ratio of the video. If it is a portrait video, I would like to set the orientation to portrait, if standard 16:9 or 4:3, then of course landscape, so that the screen doesn't end up with a lot of wasted space in black bars either side of the video.
I figured I could determine the aspect ratio and thus the orientation by getting the dimensions of the video:
if width > height:
    landscape
else:
    portrait

However, this is proving more difficult than I had imagined. I have an AVPlayer object and initially looked into its metadata property, but this apparently doesn't seem to be the sort of metadata I am after. Then I found that AVPlayer.presentationSize can have the info I'm looking for but when I printed that out - right before calling play() - to have a look at it I got the following: Optional((0.0, 0.0))
Short of looking into how I can parse the video file headers myself to try to access this info, is there anywhere in the APIs where this is exposed to me? Googling comes up with a lot of info about how to specify the size of a video when capturing one, but not much if anything about this particular problem.

A: You can ask the underlying asset for its size:
let asset = player.playerItem.asset
let videoTrack = asset.tracks(withMediaType: .video).first!
let naturalSize = videoTrack.naturalSize
let transform = videoTrack.preferredTransform
let size = naturalSize.applying(transform)


text:
Q: Displaying a limited portion of a css sprite as background in a form input element I have a form input-field (a search bar) and I'm using a sprite sheet of icons as a background to the input field.
Is there a way to set the image sprite as the input field background, but limit the viewable space of the background/sprite to avoid sprite bleeding? Ideally without editing the sprite image itself.
Here is the desired result: http://i.imgur.com/y1xu6RS.png
And the current result I'm getting: http://i.imgur.com/UruNhfj.png
The input field has the desired padding and image sprite. However, I get sprite bleeding due to the closeness of the images in the sprite vs the input field size. Is there a way to fix this using CSS alone?
My input field css is roughly:
#search-field{
            padding-left: 50px; /*numerical values aren't exact*/
            background: url("images/icon_sprite.png") 5px -15px;
            background-repeat: no-repeat;
            background-color: #fff;
}


text:
Q: Ca't install my own syslog's syslog-startup.conf via Yocto I was trying to create a new syslog-startup.conf by creating a busy-box%.bbappend having the following in it:
FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"
SRC_URI += "\
    file://syslog-startup.conf \
"

do_install_append() {
    install -m 0644 ${WORKDIR}/syslog-startup.conf ${D}${sysconfdir}/syslog-startup.conf
}

FILE_${PN} += "\
    ${sysconfdir}/syslog-startup.conf \
"

My syslog-startup.conf is the same as the default one except i have it logging to a file instead of a buffer on system startup instead of my having to go in and change it manually. I never have this work. I always have the default .conf file installed on system startup. I should mention that I'm also having the same issue when i try to update another of my system files: /etc/fstab which also doesn't work and i end up with default file installed.

*

*Why am I not able to change/append to system files?

*Is there a better way to do this?

*Is there a way to find out if my .bbappend file got executed at all?

A: I had to alter the syslog-startup.conf for a different reason. How I managed to do it was by adding the below line in my busybox_%.bbappend
FILESEXTRAPATHS_prepend := "${THISDIR}/files:"

I added the modified syslog-startup.conf inside a folder called files. Where you place the file is upto you. Yocto will replace the default file with the file provided by the .bbapend file. So all you will have to do is point to the file in your busybox_%.bbapend file


text:
Q: Haskell "could not deduce" error I have the following code:
class Coll c e where
    map :: (e1 -> e2) -> c e1 -> c e2
    merge :: (e -> e -> e) -> e -> c e -> e
    sum :: (Num e) => c e -> e
    sum = merge (+) 0

So far so good. But then I have:
    sumMap :: (Num e2) => (e1 -> e2) -> c e1 -> e2
    sumMap f c = (merge (+) 0) (map f c)

Compiling gives an error:

Could not deduce (Coll c e2) arising from a use a 'merge' from the context (Coll c e) [...] Possible fix: add (Coll c e2) to the context of the type signature for sumMap [...]

So I replace sumMap :: (Num e2) => (e1 -> e2) -> c e1 -> e2 with sumMap :: (Num e2, Coll c e2) => (e1 -> e2) -> c e1 -> e2, but then it gives another error:

Could not deduce (Coll c e0) arising from a use of 'map' from the context (Coll c e) [...] Possible fix: add a type signature that fixes these type variable(s) [...]

I'm confused, so I comment out the definition for sumMap, and run :t (merge (+) 0) . (map (* 2)), which gives me [...] :: (Num c, Coll c1 c, Coll c1 e) => c1 c -> c. Ignoring how it mangled my variables' names, Coll c1 e is bizarre; e is not even used in the definition!, so why is it there!? Anyways, then I run ((merge (+) 0) . (map (* 2))) [1,2,3,4], which successfully returns 20. What's going on here? Why does this function work only when I don't try to tie it to a name?

A: Your problems stems from the way you defined your Col class. In particular, the class definition includes both types c and e. This means that you can have different instances for different types of elements—presumably not what you want. Instead, you want to have a single instance for each possible c that works with any type of element at all.
It would be better to write the class as:
class Coll c where
  map :: (e1 -> e2) -> c e1 -> c e2
  merge :: (e -> e -> e) -> e -> c e -> e
  sum :: Num e => c e -> e
  sum = merge (+) 0

Now each individual instance only depends on c, not the type of its elements.
I suspect that you wrote class Coll c e where because you wanted to ensure that c was a collection of elements. (Like writing C<E> in Java.) However, this is unnecessary in Haskell: a type variable like c can stand in for parameterized types with no other annotation. The type system will figure out that c takes a parameter by the way you use it in the signatures for map, merge and so on.
Since this is unnecessary, class Coll c e means that the class is based on two different type variables, which don't even have to be related. This means that, to figure out which instance to use, the type system needs to know the specific type for both the collection and its elements, and in your specific case it does not have enough information to do this. If you just leave e out of the class definition, it should not be a problem.


text:
Q: extract list or tuple inside string I am getting input from an external device connected via Ethernet, and it is passing several values of string type e.g. value = '(2,2)\n'. I would like to assign these values to a list or tuple variable  e.g. final_value = (2,2).
The code I am using is the following:
import socket
sock = socket.socket()
value =sock.recv(buffersize=2048)
formatted_value = eval(value)

I read that the eval function I am using at this moment  to get the list is not a very safe approach, as the external device could pass a dangerous script. So, I would like to know if there is any alternative, similar to the function int(), which can be used to get an integer from a string.

A: Use ast module literal_eval method for a safer eval
import ast
formatted_value = ast.literal_eval(value)

A: If you know the input contains a tuple
from ast import literal_eval as make_tuple
make_tuple(value)

A: Well to give the alternative approach you can do.
s = '(2, 2)\n'
s = s.strip()
if s.startswith('(') and s.endswith(')'):
    tup = tuple(int(i) for i in s[1:-1].split(','))
    print(tup)

Or if you want a list
s = '(2, 2)\n'
s = s.strip()
if s.startswith('(') and s.endswith(')'):
    lst = [int(i) for i in s[1:-1].split(',')]
    print(lst)


text:
Q: Send Email with event.ics I read few example for sending email with attachment of event.ics file, where user can open the file and it will add event to their outlook Celander.
Question is it possible to use link or content inside the email body instead the attachment file?
I'm looking something similar to the link that can be done for Google,
<a href="https://calendar.google.com/calendar/r/eventedit?..... target="_blank">Add to Google Calendar

A: You can either put a link to an ICS file in the email, or have it as an attachment. There's no way to make it inline or a URL that doesn't involve a server.


text:
Q: How is determined the shape of the wings of an airplane? My understanding of the reason why a plane fly is summarized by the following figure: because the upper part of the wing is curved, the air above the wing has to flow faster than the wing below. This induces a force that lift the wing.

My question is:

*

*How is the exact shape of the wing determined?

*What is the "optimal" curve for a wing? By "optimal", I mean the best lift.

*How would the answer (shape of the wing) differ if we were looking for optimization of other parameters like stability.
PS: I am definitely not a physicist. If the question is too naive, please help to improve it.

A: A modern airfoil is designed on the basis of the desired pressure distribution over the chord length of both sides. In some cases, only a single angle of attack is relevant while in others the airfoil must be a compromise of the pressure distributions over a range of angles and flap deflections.
Two parameters can be used to tailor the desired pressure distributions:

*

*Relative thickness: Any body needs to displace air when it travels through it. This displacement causes supervelocities on both sides and extra drag (called wave drag) at supersonic speed. For better structural efficiency, a thicker airfoil is better, while a supersonic wing needs to be as thin as practical. Typical cases range from 22% at the root of WWII bombers over 13% for a modern airliner root all the way down to the 4% of a supersonic delta wing.

*Local camber: Positive local camber spreads the pressures on the lower and the upper side of an airfoil apart, such that is shows higher pressure on the lower and lower pressure on the upper side. This pressure difference is the source of lift.
Now it might seem that we ideally create a lot of suction on the upper surface while maximizing the pressure on the bottom surface, and that is indeed what an airliner wing with flaps extended for landing tries to do, but a few limitations exist.

*

*Pressure recovery: Once the flow leaves the airfoil at the trailing edge, its pressure should have returned to its ambient value. A big suction area on the rear-facing part of the airfoil will cause drag, so the area of low pressure should extend only over the forward and mid part of the chord length. The pressure gradient cannot be too steep in order to avoid flow separation. Separation makes further pressure recovery impossible and is very drag-intensive. The maximum pressure gradient at the desired maximum operating angle of attack therefore limits the minimum pressure over the forward part of the airfoil.

*Maximum local Mach number: Lower pressure means higher speed (the total energy of the flow is constant, and pressure is equivalent to potential energy), and since the flow behaves differently once it crosses into the supersonic realm, the minimum pressure can also be limited by the maximum local Mach number where recompression is still possible without causing a drag-intensive shock.

*Positive wing thickness: Sometimes reaching the theoretical optimum is prevented by the fact that the upper side of the airfoil must be above the lower side contour.
Please follow the links if you want to know more - here I could only scratch the surface.

A: There are lots of answers on this site regarding "how is lift produced" etc. but this post asks about the determination of a typical wing profile, so it might be appropriate to follow through on that aspect.

*

*Determine the chord (length from wing leading edge to the trailing edge).

*Decide on your camber line, for a flat bottom surface wing, this is the shape of the curved upper surface. As in the comments above this parameter is determined by the use to which the aircraft is to be put and may involve camber on the lower wing surface.  In general, the faster the speed of your aircraft, the less camber thickness you need.
The first picture shows a Sopwith Camel c. 1915  with thick cambered wings and the  bottom image is of an almost camberless winged F105 60 years later.

From here on physics is replaced by engineering, and a good source for basic principles is NASA Aircraft Design, from which my few comments are taken.


text:
Q: QT showstatus tip is shown only after mouse leave the window and return I have a mainwindow and I'm trying to show in statusarea message when user is trying open file that don't exist.
void MainWindow::onOpenClicked(){
    if(QFile(ui->lineEditCapture->text()).exists()){
        // allow opening for analyze
    }else{
        setStatusTip("Can't open file, check if the file name is correct");
    }
}

The problem is that the statustip is shown only after the mouse pointer leaves the window and return.
Also when I do
setStatusTip("Can't open file, check if the file name is correct");

in constructor then the statustip is shown right away.
What could be wrong?
EDIT:
It looks like if I do setStatusTip in slot then it's not working as it should, however if the setStatusTip is in normal method then it works as expected.

A: Use the showMessage function instead of the setStatusTip. This way you can control how long the message will be displayed:

If timeout is 0 (default), the message remains displayed until the
  clearMessage() slot is called or until the showMessage() slot is
  called again to change the message.

if (statusBar())
    statusBar()->showMessage("Can't open file, check if the file name is correct");


text:
Q: Prove isomorphism of fundamental groups Hei, guys! I'm having some problem solving the next exercise:
Let $f: M -> N$ be a homeomorphism. Define a map $f*:π_1 (M, x_0) → π_1 (N, f(x_0 ))$
such that $f*([\gamma])=[f∘\gamma]$. Show that $f*$ is an isomorphism. Check that the map is well-defined.
Any suggestions?

A: We just need to prove that the fundamental group satisfies two properties below.

*

*If $\text{id}:(M,x_0)\to(M,x_0)$, then $\text{id}_*=\text{id}:\pi(M,x_0)\to\pi(M,x_0)$.

*If $f:(L,x_0)\to(M,y_0)$, $g:(M,y_0)\to(N,z_0)$, then $(g\circ f)_*=g_*\circ f_*:\pi(L,x_0)\to\pi(M,z_0)$.
So if $f$, $g=f^{-1}$ are homeomorphism, then
$$\text{id}=\text{id}_*=(f\circ g)_*=f_*\circ g_*$$
$$\text{id}=\text{id}_*=(g\circ f)_*=g_*\circ f_*$$
Now we get the conclusion.
Actually the proof is based on the theory of functor: http://en.wikipedia.org/wiki/Functor.

If you want prove it by the homotopy, I shall give the next theorem.

Theorem Suppose $f$, $g:M\to N$ are continuous, and $H$ is the homotopy map between them. For any $q\in X$, let $h$ be the path in $Y$ from $f(q)$ to $g(q)$ defined by $h(t)=H(q,t)$. Now we have an isomorphism between $\pi(X,f(q))$ and $\pi(Y,g(q))$.

You can find clue in the Lee's book: Introduction to Topological Manifold, P164.


text:
Q: My terminal loads with junk text. How can I remove this? declare -x SHLVL="1"
declare -x SSH_AGENT_PID="1411"
declare -x SSH_AUTH_SOCK="/run/user/1000/keyring/ssh"
declare -x TERM="xterm-256color"
declare -x USER="nishan"
declare -x VTE_VERSION="6003"
declare -x WINDOWID="71303171"
declare -x XAUTHORITY="/home/nishan/.Xauthority"
declare -x XDG_CONFIG_DIRS="/etc/xdg/xdg-xubuntu:/etc/xdg:/etc/xdg"
declare -x XDG_CURRENT_DESKTOP="XFCE"
declare -x XDG_DATA_DIRS="/usr/share/xubuntu:/usr/share/xfce4:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/usr/share"
declare -x XDG_GREETER_DATA_DIR="/var/lib/lightdm-data/nishan"
declare -x XDG_MENU_PREFIX="xfce-"
declare -x XDG_RUNTIME_DIR="/run/user/1000"
declare -x XDG_SEAT="seat0"
declare -x XDG_SEAT_PATH="/org/freedesktop/DisplayManager/Seat0"
declare -x XDG_SESSION_CLASS="user"
declare -x XDG_SESSION_DESKTOP="xubuntu"
declare -x XDG_SESSION_ID="c2"
declare -x XDG_SESSION_PATH="/org/freedesktop/DisplayManager/Session0"
declare -x XDG_SESSION_TYPE="x11"
declare -x XDG_VTNR="7"

I am using Xubuntu 20.04 LTS version, freshly installed and updated. Since a recent update, every time I open terminal this text appears inside. I have to clear it using the clear command. I want to get rid of this as it's very annoying.

A: I got the answer from How do I restore .bashrc to its default?
Make a copy of current bashrc file
/bin/cp ~/.bashrc ~/my_bashrc

Copy system default bashrc
/bin/cp /etc/skel/.bashrc ~/

Tell system to use copied bashrc file immediately
. ~/.bashrc


text:
Q: sed script append to lines starting with? I'm trying to write a basic sed script, I want to append to lines that start with SSID:. Here is what I'm trying now:
#!/bin/sed -f

/^SSID:/ s/*/},\n{/

With the following input:
SSID:                                   '2KLIC Guests'
BSSID:                                  F0:9F:C2:21:03:BA
MODE:                                   Infrastructure
FREQ:                                   2437 MHz
RATE:                                   16 MB/s
SIGNAL:                                 100
SECURITY:                               WPA2
ACTIVE:                                 yes
SSID:                                   'CBMS-2.4GHz'
BSSID:                                  10:BE:F5:25:FD:60
MODE:                                   Infrastructure
FREQ:                                   2412 MHz
RATE:                                   16 MB/s
SIGNAL:                                 0
SECURITY:                               WPA WPA2
ACTIVE:                                 no
SSID:                                   'CIK1000M_AC2.4G_3714'
BSSID:                                  D0:60:8C:03:DB:B4
MODE:                                   Infrastructure
FREQ:                                   2422 MHz
RATE:                                   16 MB/s
SIGNAL:                                 0
SECURITY:                               WPA2
ACTIVE:                                 no

I also tried escaping the :. Can someone explain what I'm doing wrong here?

A: To just substitute the whole line,
s/^SSID:.*/},\n{/

If you wanted to keep some or all of the SSID line's contents, then try capturing in the initial regex.
s/^\(SSID:.*\)/\1\n},\n{/

A: Your sed expression:
/^SSID:/ s/*/},\n{/

This is almost correct, but * will match a literal * (since it's the first character in the regular expression).
Using your way of addressing the line that you'd like to modify:
/^SSID:/s/^/},\n{/

This would find any line beginning with the string SSID: and would substitute in },\n{ at the start of those lines.
Note that this requires GNU sed to interpret the escape sequence \n as a newline in the replacement text.
With non-GNU sed, you would write
/^SSID:/s/^/},\
{/

or, if you did this from the command line with a shell like bash that understands $'...' as a "C string":
sed '$/^SSID:/s/^/},\\\n{/'

(the \\\n is for an escaped \ followed by \n)


text:
Q: Powershell compare-object but ignore specific character? Thanks to another user on here, I was able to discover Powershell Compare-Object.
The code I'm using is straight forward and here it is:
$array = Compare-Object $(Get-Content $Source1) $(Get-Content $Source2)
$array | where {$_.SideIndicator -eq "<="} | Format-Table -Property InputObject -AutoSize -HideTableHeaders | Out-File -Width 512 -Encoding utf8 NoMatchA.txt
$array | where {$_.SideIndicator -eq "=>"} | Format-Table -Property InputObject -AutoSize -HideTableHeaders | Out-File -Width 512 -Encoding utf8 NoMatchB.txt

The files I am comparing are hash + filepath that looks like this test Input SourceA:
0004250736cc617f596b24d69c52a1276ea7f81cd5f7c7e49458894987d02538 D:\Documents\Server\DBackupServer\snapraid\Archive\authors.txt
5a10fd71a62ca272908ded8a7f20826722c0fc67da22256accb42159baa13af2 D:\Documents\Server\DBackupServer\snapraid\Archive\copying.txt
d3d868c751b91c5bd5105db5b9c4f35429fe85a6405bf7fa073d969a0f24a4bc D:\Documents\Server\DBackupServer\snapraid\Archive\history.txt
a1ca63b535996640ac4c5ae0fb91998ebcb495928a637d8d8f71508573c289bd D:\Documents\Server\DBackupServer\snapraid\Archive\install.txt
62f9bfd975bc0773be108b20467d6ece969e06e033b5ae51fb56597d09800000 D:\Documents\Server\DBackupServer\snapraid\Archive\readme.txt

SourceB:
0004250736cc617f596b24d69c52a1276ea7f81cd5f7c7e49458894987d00000 E:\Documents\Server\DBackupServer\snapraid\Archive\authors.txt
06d99bb9e6b9c0f57828b29a465a769628da86faca48a104fbdd3263d85eda4d E:\Documents\Server\DBackupServer\snapraid\Archive\backup_snapraid.bat
5a10fd71a62ca272908ded8a7f20826722c0fc67da22256accb42159baa13af2 E:\Documents\Server\DBackupServer\snapraid\Archive\history.txt
a1ca63b535996640ac4c5ae0fb91998ebcb495928a637d8d8f71508573c289bd E:\Documents\Server\DBackupServer\snapraid\Archive\install.txt
62f9bfd975bc0773be108b20467d6ece969e06e033b5ae51fb56597d098969f3 E:\Documents\Server\DBackupServer\snapraid\Archive\readme.txt

But I want it to ignore the drive letter so I can compare two files from two different sources. Right now I run the hash log file through a for /f command in a batch file to remove the drive letter, but that can take a long time for large amount of entries.
Is there any way for compare-object to ignore the drive letter? The : is a unique identifier for the drive letter (although eventually want to get it to work with UNC preceding \\) and it should always be in the same position considering the hash, so maybe that could help.
I tried using the Split() command and while I can split the object based on a space character, I'm not sure how I can implement that into the compare-object.
I tried using: get-content $Source1 | foreach {$_ -replace "D:", ""} | Set-Content "$Source1a" and that took just as long as the batch file...
Thanks for any help.
EDIT: Thank you everyone so far for the assistance. I haven't had a chance to test the one proposal yet, should get to that tomorrow.
In any case, to clarify I was looking for three file outputs:

*

*File in A not in B - same output format as the input (hash + filepath/name) but only comparing file name/path, to identify files that are in Source A not in Source B.

From Test INPUT above, result output would be "FileAnotInB.txt":
5a10fd71a62ca272908ded8a7f20826722c0fc67da22256accb42159baa13af2 D:\Documents\Server\DBackupServer\snapraid\Archive\copying.txt

*File in B not in A - same output format as the input (hash + filepath/name) but only comparing file name/path, to identify files that are in Source B not in Source A.

From Test INPUT above, result output would be "FileBnotInA.txt":
06d99bb9e6b9c0f57828b29a465a769628da86faca48a104fbdd3263d85eda4d E:\Documents\Server\DBackupServer\snapraid\Archive\backup_snapraid.bat

*Hash not matching - same output format as the input (hash + filenamepath) but only comparing hash, to identify mismatched hash, preferably outputting both sourceA and SourceB on top of each other for simple comparison:

From Test INPUT above, result output would be (notice 00000 replaced at end of hash for testing) "FailedHashes.txt":
0004250736cc617f596b24d69c52a1276ea7f81cd5f7c7e49458894987d02538 D:\Documents\Server\DBackupServer\snapraid\Archive\authors.txt
0004250736cc617f596b24d69c52a1276ea7f81cd5f7c7e49458894987d00000 D:\Documents\Server\DBackupServer\snapraid\Archive\authors.txt
62f9bfd975bc0773be108b20467d6ece969e06e033b5ae51fb56597d09800000 E:\Documents\Server\DBackupServer\snapraid\Archive\readme.txt
62f9bfd975bc0773be108b20467d6ece969e06e033b5ae51fb56597d098969f3 E:\Documents\Server\DBackupServer\snapraid\Archive\readme.txt

It looks like response from JosefZ may do this, or at least I can adapt it to do this. I'll have to test to see, but wanted to edit to clarify and thank for the help!

A: The following code snippet shows a possible way how-to ignore the drive letter:
Compare-Object $((Get-Content $Source1) -replace "\s[A-Z]\:\\", ' \') $((Get-Content $Source2) -replace "\s[A-Z]\:\\", ' \')

… is there a simple way also with compare-object and/or where-object to spit out a file that showed where file names matched, but had
  mismatched hash files? That's ultimately what I'm aiming for is three
  files: Files in source A not in B. Files in Source B not in A. And
  then same filenames/paths but with mismatched hash?

I am not sure whether such a trichotomy is well-defined as described in above supplementary requirement. However, here's my attempt to solve it (slightly changed variable and file names):
$sourcePath = 'D:\PShell\DataFiles'
$utf8     = 'utf8'     # $utf8 = 'Default'  # debugged using Default
$sourceA  = "$sourcePath\1558327A.txt"
$sourceB  = "$sourcePath\1558327B.txt"
$contentA = (Get-Content -Path $SourceA)
$contentB = (Get-Content -Path $SourceB)
$array = Compare-Object -ReferenceObject  $(
            $contentA -replace "\s[A-Z]\:\\", ' \')  -DifferenceObject $(
            $contentB -replace "\s[A-Z]\:\\", ' \')
$arrNotInB = $array | Where-Object {$_.SideIndicator -eq "<="} # |    Select-Object -ExpandProperty InputObject #|
$arrNotInA = $array | Where-Object {$_.SideIndicator -eq "=>"} # |    Select-Object -ExpandProperty InputObject #|

# Files in Source B not in A.
$arrNotInA |
    Select-Object -ExpandProperty InputObject |
    Where-Object {
        -not ($arrNotInB -match [regex]::Escape($($_ -split '\s', 2)[1]))
    } | Out-File -Width 512 -Encoding $utf8 -FilePath "$sourcePath\NotInA.txt"
# Files in source A not in B.
$arrNotInB |
    Select-Object -ExpandProperty InputObject |
    Where-Object {
        -not ($arrNotInA -match [regex]::Escape($($_ -split '\s', 2)[1]))
    } | Out-File -Width 512 -Encoding $utf8 -FilePath "$sourcePath\NotInB.txt"
# And then same filenames/paths but with mismatched hash
(
$arrNotInB |
    Select-Object -ExpandProperty InputObject |
    Where-Object {
        ($arrNotInA -match [regex]::Escape($($_ -split '\s', 2)[1]))
    } | ForEach-Object {
        $auxHash, $auxPath = $_ -split '\s', 2
        $contentA | Where-Object {
            ($_ -replace "\s[A-Z]\:\\", ' \') -match [regex]::Escape("$auxHash $auxPath")
        }
    }
),(
$arrNotInA |
    Select-Object -ExpandProperty InputObject |
    Where-Object {
        ($arrNotInB -match [regex]::Escape($($_ -split '\s', 2)[1]))
    } | ForEach-Object {
        $auxHash, $auxPath = $_ -split '\s', 2
        $contentB | Where-Object {
            ($_ -replace "\s[A-Z]\:\\", ' \') -match [regex]::Escape("$auxHash $auxPath")
        }
    }
) | Out-File -Width 512 -Encoding $utf8 -FilePath "$sourcePath\NotMatchHash.txt"

A: Sample Data:
# --- SourceA --    --- SourceB --
# --------------    --------------
# 123 c:\123.txt    123 c:\123.txt  <-- FullMatch
# 456 c:\456.txt    789 c:\789.txt  <-- NoMatch
# 0ab c:\0ab.txt    0ab d:\0ab.txt  <-- Hash + RelPathMatch

Create Sample Files:
@'
123 c:\123.txt
456 c:\456.txt
0ab c:\0ab.txt
'@ | Set-Content A.txt
@'
123 c:\123.txt
789 c:\789.txt
0ab d:\0ab.txt
'@ | Set-Content B.txt

The following could be reduced to an Import-Csv operation if you have control over cration of the source files:
Function Import-Log ($Path) {
   Get-Content $Path | ForEach{
      $_ -match '(^.+ )[A-Za-z]\:\\(.+$)' | out-null
      [PSCustomObject]@{
         Full    = $matches[0]
         NoDrive = $matches[1] + $matches[2]
      }
   }
}

With the above function defined:
$oA = Import-Log A.txt
$oB = Import-Log B.txt

$NoMatches = Compare-Object $oA $oB -Property NoDrive
$AnotB     = $NoMatches | ? SideIndicator -like '<='
$BnotA     = $NoMatches | ? SideIndicator -like '=>'
$HashMatch = Compare-Object $oA $oB -Property Full, NoDrive | ? NoDrive -notIn $NoMatches.NoDrive

Results:
PS C:\> $NoMatches

NoDrive     SideIndicator
-------     -------------
789 789.txt =>
456 456.txt <=

PS C:\> $AnotB

NoDrive     SideIndicator
-------     -------------
456 456.txt <=

PS C:\> $BnotA

NoDrive     SideIndicator
-------     -------------
789 789.txt =>

PS C:\> $HashMatch

full           NoDrive     SideIndicator
----           -------     -------------
0ab d:\0ab.txt 0ab 0ab.txt =>
0ab c:\0ab.txt 0ab 0ab.txt <=


text:
Q: Writing a modification for multiple versions of the original application I am writing a modification for a specific version of a Java application. I modify the existing code and add my own special code into it.
Now, when the original Java application gets an update with major codebase changes and I would like my modification to be available for that new version, it would be really hard and time consuming for me to copy all of my own code and update all changes that I made to the original source code. When I code a new feature, I will then have to copy the whole feature for multiple versions of the original application.
My goal is to support multiple versions simultaneously, but I am wondering if there is a simpler (or more efficient) way of doing this so I keep my own code in a common location and only adapt some other parts of the code.
Thanks in advance!

A: There is no simple solution.
You forked an application, the original developers know nothing of your fork, and regardless, even if they did they are not required to do anything to maintain compatibility.
If your fork potentially has value to others, you should lobby to contribute it to the original project, and become a contributor on that project.  Otherwise, it will be up to you to diff every new version of the base against the previous version and then adjust your code to deal with any incompatibilities introduced by the new version.


text:
Q: Combination > Advanced Timeline causes "ReferenceError: Highcharts is not defined" Steps To Replicate

*

*Download HIGHCHARTS 4.1.9 from http://www.highcharts.com/download

*Open index.html.

*Click on Combinations > Advanced timeline.

*The following error is shown in Firebug and no chart is displayed:

ReferenceError: Highcharts is not defined /Highcharts-4.1.9/js/modules/exporting.js Line 24
ReferenceError: Highcharts is not defined /Highcharts-4.1.9/examples/combo-timeline/index.htm Line 280
What I've Tried
I changed the script paths at the end of:
/Highcharts-4.1.9/examples/combo-timeline/index.html

From:
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>

To:
<script src="../js/highstock.js"></script>
<script src="../js/modules/exporting.js"></script>

However, this still produces the error:
ReferenceError: Highcharts is not defined
/Highcharts-4.1.9/examples/combo-timeline/index.htm
Line 280

I changed the reference to jQuery in /combo-timeline/index.htm from:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

to:
<script type="text/javascript" src="../js/jquery-1.11.3.js"></script>

which then produces this error:
ReferenceError: $ is not defined
/Highcharts-4.1.9/examples/combo-timeline/index.htm
Line 204

A: Solution
The JSFiddle demo was working, so I downloaded the following:
https://code.highcharts.com/stock/highstock.js
https://code.highcharts.com/modules/exporting.js
And used the jQuery version used in the fiddle:
jQuery Core 1.9.1

And the chart loads now and there are no errors.


text:
Q: text code before image but still next to eachtoghter how? So I have looked everywhere couldn't find the answer.
Layout of the HTML code:

 text

How you see it on the web:
text---images

Can this be done in css? Also the text and the image can't be swapped becuase on smaller screens the text neet te appear before the image.

A:

text

A:


text:
Q: Get country code from numbers that are different length We know that there are numbers with different length. In Europe we mostly have 9 digits numbers plus country code.
In North America we often find 10 digits numbers.
I am trying to get my head around an idea how to get a country code from a number that may be of different length.
Any ideas? Maybe you know some working libs that can do it?

A: I assume that you are talking about phone number country codes. Country codes are defined by the ITU ( https://en.wikipedia.org/wiki/List_of_country_calling_codes ). The country codes can be 1, 2 or 3 digits. Your only alternative is to have a list of all country codes and parse it from there. Note that there is no overlap; for instance, +44 belongs to the UK, and no country starts with just 4.
UPDATE: The North American Area has 4 digit prefixes, not 1, composed of +1 and a NPA of 3 digit (http://en.wikipedia.org/wiki/North_American_Numbering_Plan). The same rule applies though, in that +1-NPA cannot be repeated. Barbados seems to be +1246, but no other country or region can start with +1246. You can get the list of all NPA from http://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes

A: The key facts:

*

*The country code is always at the start of the number, so it is easy to find no matter the length of the number.

*There is no overlap, as @Luis points out.
A (looks pretty) complete list of country codes is give here. If you sort them by length (shortest first) and run through the list comparing the first n digits with the list entries you will get the answer.
However, if you look at the list you wall see that there are various groups of codes. A more intelligent approach would note that:

*

*All numbers beginning with 1 are US, Canada or other US related places in which case the next three digits tell you which.

*7 is Khazakstan

*Apart from 20, all country codes beginning with 2 are three digits.

*and so on ...

A: Country codes are parsed left-to-right with deterministic endpoints similar to the idea of Huffman coding. ie, if you see a 1 first, stop, it's the US/Canada/related territories. If you see most other numbers besides 7 (Russia/Kazakhstan), keep going. Some of those numbers may terminate on the second value.
The list of country codes is here: http://www.howtocallabroad.com/codes.html
It should be trivial for you to take this and write your own string parser of a phone number in order to determine which country code is present.
(don't forget that if these are numbers from within a particular country, you also have to take that country's exit code into account, which is also on the page I linked)
Edit: Oh, I guess luis covered it. But Jakob is incorrect in his comment about Barbados. Barbados is the same country code as the US; the 246 is its local "area code" within the US/Canada's country code.


text:
Q: Dynamically create list of jpanels swing/java I am attempting to create panel, PluginListPanel (extending JPanel), which will show a list of plugin panels which will respect the preferred height of the plugin's panel, but will force the width. I have a solution, but it is slow and has a weird bug. In the screenshot, there are two such panels, one to the left and one to the right:

I don't know different layout manager systems very well, but I know that the TOP field in the BorderLayout does what I want. So, I came up with this 'recursive' solution:
public PluginListPanel(List<PanelContainer> items) {
    JPanel body = this;
    for (PanelContainer item : items) {
        body.setLayout(new BorderLayout(0, 0));
        JPanel panel = new PluginOnePanel(item);
        body.add(panel, BorderLayout.NORTH);

        JPanel newBody = new JPanel();
        body.add(newBody, BorderLayout.CENTER);
        body = newBody;
    }
}

The problem I encounter is when I scroll, the system responds somewhat slowly, and the colour of the SamplePluginPanels is different (see picture below), even if the number of SamplePluginPanels is as low as 8.
The question is, how can I make this more elegant, not slow down the program and not miscolour the panels?
Any insights are highly appreciated.

A: I think a vertical Box is the answer (actually 2, on both columns):
Box leftBox = Box.createVerticalBox();
Box rightBox = Box.createVerticalBox();

/* put them together */

setLayout(new GridLayout(2,1));
add(leftBox);
add(rightBox);

Also make sure, that the content of the scroll pane implements Scrollable and returns true, to scrollableTracksViewportWidth(). This will force equal widths.


text:
Q: Reconciling Columns VBA I'm looking to create a reconciliation sub which will find a value in Spreadsheet A, Column A and return the corresponding value in Column B i.e. Column A = ID123; Column B = HELLO. The procedure will then find the same value in Spreadsheet B, Column A (in this example, ID123) and return the value in Column B. So ideally, I would like these 2 values to be side by side so that I can do a comparison. All I have so far is code that will return values from Column A but I am unable to return Column B. This is essentially a VLookup, but Vlookups have proven to be very consuming in VBA:
    Sub findCell()

 Dim ETLCell As String
 Dim mifidCell As String
 Dim last_row_A As Long
 Dim last_row_B As Long

 last_row_A = Worksheets("Spreadsheet A").UsedRange.Rows.Count
 last_row_B = Worksheets("Spreadsheet B").UsedRange.Rows.Count

 'Loop which returns the TRN beside each column
 For i = 2 To last_row_A

ETLCell = Worksheets("Spreadsheet B").Columns("B:B").Find(What:=Worksheets("Spreadsheet A").Cells(i, 1).Value)
mifidCell = Worksheets("Spreadsheet A").Cells(i, 1).Value

    Worksheets("Reconciliation").Cells(i, 1).Value = ETLCell

    If ETLCell Is Nothing Then
ETLCell = "BLANK"
    Worksheets("Reconciliation").Cells(i, 2).Value = "False"

    Else
    Worksheets("Reconciliation").Cells(i, 2).Value = "True"

    End If

Next i

End Sub

A: I took a different approach than the one that you took to solve this issue. I tried embedding comments into the code to describe what is happening. Try reviewing it and see if you can incorporate it into your workbook, and write back with questions.
I stored the values from sheet B into a dictionary object for efficient lookup. This type of object holds a unique key, and a corresponding value. Then, I can loop over the Keys in sheet A, looking for them in sheet B, and then adding the values to the reconciliation.
Sub AnalyzeReconciliation()
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet
    Dim shtRecon As Worksheet
    Dim rng1 As Range
    Dim rng2 As Range
    Dim cel As Range
    Dim oDict As Object
    Dim reconRow As Long

    Set sht1 = Worksheets("Worksheet A")
    Set sht2 = Worksheets("Worksheet B")
    Set shtRecon = Worksheets("Reconciliation")

    'I don't like using UsedRange. I find it to be unreliable
    'Define the columns that you need, and find the last row
    'using a method call similar to below
    Set rng1 = sht1.Range("A2:B" & sht1.Range("A" & sht1.Rows.Count).End(xlUp).Row)
    Set rng2 = sht2.Range("A2:B" & sht2.Range("A" & sht2.Rows.Count).End(xlUp).Row)

    'Get a dictionary object holding unique values from sheet 2
    'In my case, column A holds the Id, and column B holds the value
    Set oDict = GetDictionary(rng2, 1, 2)

    reconRow = 0

    'Loop over each cel in sheet 1, column 1
    'Look for the value in column 1 in the sheet 2 dictionary
    'object, and then reconcile
    For Each cel In Intersect(rng1, sht1.Columns(1))
        'Get the next avail row in reconciliation sheet
        reconRow = reconRow + 1
        shtRecon.Range("A" & reconRow).Value = cel.Value

        'Recon column B holds value from sheet 1, column B
        shtRecon.Range("B" & reconRow).Value = cel.Offset(, 1).Value

        'If Id is found in Sheet B dictionary, then take the value
        'otherwise, write "blank" in column C
        If oDict.exists(cel.Value) Then
            shtRecon.Range("C" & reconRow).Value = oDict(cel.Value)
        Else
            shtRecon.Range("C" & reconRow).Value = "BLANK"
        End If
    Next cel
End Sub

'Function stores a range into a dictionary
'Param inputRange takes a range to be stored
'Param idColumn takes the column of the range to be used as the ID
'   e.g. if idColumn = 2, and inputRange("C1:F10"), then column D
'        is used for ID
'Param valueColumn points to the column in range used for the value
Function GetDictionary(inputRange As Range, idColumn As Long, valueColumn As Long) As Object
    Dim oDict As Object
    Dim sht As Worksheet
    Dim cel As Range

    Set oDict = CreateObject("Scripting.Dictionary")
    Set sht = inputRange.Parent

    For Each cel In Intersect(inputRange, inputRange.Columns(idColumn))
        If Not oDict.exists(cel.Value) Then
            oDict.Add cel.Value, sht.Cells(cel.Row, valueColumn).Value
        End If
    Next cel

    Set GetDictionary = oDict
End Function