text:
Q: Access denied when sending data with UdpClient I am trying to create a small Application which reads data from the Serial-/Com-Port and broadcasts the data to my network using port 15000.
Everything works fine on Windows and Linux (using Mono) but I get a Socket Exception on macOS with the following message: Access denied
I tried to run my Application with elevated permissions:

sudo mono ./SerialMonitor.exe

But that doesn't work too.
Is there any way to get rid of that exception? And why does it work without any issues on Windows and Linux?
Here is my code:
using System;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SerialMonitor
{
    class MainClass
    {
        static SerialPort mSerial = new SerialPort();
        static String[] mSerialPorts;
        static UdpClient mNetwork;
        static IPEndPoint mIP;

        static String mData = "";

        public static void Main(string[] args)
        {
            mNetwork = new UdpClient();
            mIP = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 15000);

            mSerialPorts = SerialPort.GetPortNames();

            Console.WriteLine("Select a serial port:");
            if (mSerialPorts.Length == 0)
            {
                Console.WriteLine("No serial ports available!");
                return;
            }
            for (int i = 0; i < mSerialPorts.Length; i++)
            {
                Console.WriteLine(i + 1 + ": " + mSerialPorts[i]);
            }
            Console.Write("Selection: ");
            int selection = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Selected port: " + mSerialPorts[selection - 1]);

            mSerial.PortName = mSerialPorts[selection - 1];
            mSerial.BaudRate = 9600;
            mSerial.NewLine = "\r\n";
            mSerial.Open();
            mSerial.DiscardInBuffer();

            Console.WriteLine("\nData:");

            while (true)
            {
                try
                {
                    MainClass.mData = mSerial.ReadLine();
                    Console.WriteLine(MainClass.mData);

                    byte[] bytes = Encoding.ASCII.GetBytes(MainClass.mData);
                    mNetwork.Send(bytes, bytes.Length, mIP);
                }
                catch(SocketException ex)
                {
                    Console.WriteLine("\nNETWORK ERROR: " + ex.Message);
                    Console.Read();
                    return;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\nERROR: " + ex.Message);
                    Console.Read();
                    return;
                }
            }
        }
    }
}

I am using Visual Studio Community 2017 for Mac
Version 7.1 (build 1297)
Mono 5.2.0.215 (d15-3/da80840) (64-bit)
Project configuration:
.NET Framework 4.6.1
x86

A: If you want to send broadcast messages across your local subnet (or broadcasts in general) you have to enable broadcasts on your socket with:
mNetwork.EnableBroadcast = true;

Reference:
https://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient(v=vs.110).aspx
http://answers.unity3d.com/questions/248494/socket-exception-access-denied.html


text:
Q: Não consigo remover um item do banco de dados Estou tentando remover um item do banco de dados, porém não ta removendo.
        <form action="removelicita.php" method="post">
            <input type="hidden" name="id" value="<?=$licitacao['id']?>">
            <button type="button" class="btn btn-danger">Remover</button>
        </form>

Acima o trecho de código onde chamo a ação de exclusao.
Abaixo o código da exclusão:
<?php

require_once("conexao.php");

$id = $_POST["id"];

$query = "delete from insereLicitacao where id = $id";

if(mysqli_query($conexao,$query)){
    header("Location: listalicitacao.php");
    die();
} else {
    echo "Erro ao remover licitação";
}

A: Mude o atributo type da tag button para que o formulário seja submetido
<button type="submit" class="btn btn-danger">Remover</button>

Referência:
https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/button

redpajama_set_name: RedPajamaStackExchange


text:
Q: News feed imagecreatefromjpg() error in batch I'm pulling a news feed and doing batch imagecreatefromjpg() in a loop but I'm getting this error.

Warning: imagecreatefromjpeg(): php_network_getaddresses: getaddrinfo
  failed: Name or service not known in
  /home4/index.php on line 90

It works fine when I just do one image but in a loop, it errors out. Should there be a onComplete handler of some sort for each image, maybe it's doing it too fast?
I'm just grabbing the average color of each feed image.
$filename = $inimage;
$image = imagecreatefromjpeg($filename);
$width = imagesx($image);
$height = imagesy($image);
$pixel = imagecreatetruecolor(1, 1);
imagecopyresampled($pixel, $image, 0, 0, 0, 0, 1, 1, $width, $height);
$rgb = imagecolorat($pixel, 0, 0);
$color = imagecolorsforindex($pixel, $rgb);
$image_r = $color['red'];
$image_g = $color['green'];
$image_b = $color['blue'];

thanks.


text:
Q: How do I *save* the results of an angular material modal dialog? I have a component which opens a modal dialog to let the user input two dates. I would then like to save those two dates to a db model behind the component, but I am having trouble wrapping my head around when and where to obtain those results.
To be clear: I can currently see the dialog result as two dates in my main component's template, but I would like to know, in...some method...in my main component, when the dialog is closed and the dates are no longer nulls -- so I can save them to the DB.
My main component template has a button with an onClick event:
<mat-icon title="Get Dates" (click)="onClickGetDates(appt)">flag</mat-icon> Result from dialog: {{ dateRangeArray }}

The main component implements the onClick event:
onClickGetDates(appt) {
    this.dialogService
      .confirmDateRange('Get Dates', 'Enter two dates:',
        appt.beginDate, appt.endDate)
      .subscribe(res => this.dateRange = res);
.
.
// I would like to now save the dateRange result to my database, but at this point, result is [null,null], so the code below does nothing (except null out the dates):
appt.beginDate = dateRange[0];
appt.endDate = dateRange[1];
this.apptdata.updateAppt(appt);
}

Here is confirmDateRange, defined in a Dialog Service, which actually displays the dialog:
public confirmDateRange(title: string, message: string, begin: Date, end: Date): Observable<boolean> {
    let dialogRef: MatDialogRef<ConfirmDialogComponent>;

    dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.componentInstance.title = title;
    dialogRef.componentInstance.message = message;
    dialogRef.componentInstance.beginDate = begin;
    dialogRef.componentInstance.endDate = end;

    return dialogRef.afterClosed();
  }

And the dialog component:
export class ConfirmDialogComponent implements OnInit {

  public title: string;
  public message: string;

  public beginDate: Date;
  public endDate: Date;

  constructor(public dialogRef: MatDialogRef<ConfirmDialogComponent>) { }

  ngOnInit() {
  }

And the dialog's template:

{{ title }}

{{ message }}

<mat-form-field>
  <input matInput [matDatepicker]="beginDatePicker" placeholder="Beginning" [(ngModel)]="beginDate">
  <mat-datepicker-toggle matSuffix [for]="beginDatePicker"></mat-datepicker-toggle>
  <mat-datepicker #beginDatePicker></mat-datepicker>
</mat-form-field>

<mat-form-field>
  <input matInput [matDatepicker]="endDatePicker" placeholder="Ending" [(ngModel)]="endDate">
  <mat-datepicker-toggle matSuffix [for]="endDatePicker"></mat-datepicker-toggle>
  <mat-datepicker #endDatePicker></mat-datepicker>
</mat-form-field>

<button type="button" mat-raised-button
        (click)="dialogRef.close([beginDate, endDate])">OK</button>

<button type="button" mat-button
        (click)="dialogRef.close()">Cancel</button>

After clicking OK in the dialog, I can see the resultant array with the two dates in the main component's template like this: Result from dialog: {{ dateRangeArray }}. Trying to access the same result in onClickGetDates is 'too soon' and the result is a null array...So, where/when is the proper place to see that result in my main component?
I feel like I'm mis-using the dialog's AfterClose() event, and that I should be able to retrieve results just after that event is fired, but I'm still too green with Angular to realize what I'm doing wrong.

A: Try this
onClickGetDates(appt) {
    this.dialogService
      .confirmDateRange('Get Dates', 'Enter two dates:',
        appt.beginDate, appt.endDate)
      .subscribe(res =>
      {this.dateRange = res;
//Set the appt's properties inside the subscribe
appt.beginDate = this.dateRange[0];
appt.endDate = this.dateRange[1];
this.apptdata.updateAppt(appt);
});

A:                 Use @Output() to send dates from inner component to outer component and implement a function that call on Ok button and emit that data from that function like :
                `@Output() response =  new EventEmitter()<any>;

                onOkClicked()
                {
                this.response.next({beginDate : beginDate , endDate: endDate});
                this.dialogRef.close();
                }

                onCancelClicked()
                {
                this.dialogRef.close();
                }

                confirmDateRange(title: string, message: string,appt): Observable<boolean> {
                let dialogRef: MatDialogRef<ConfirmDialogComponent>;

                dialogRef = this.dialog.open(ConfirmDialogComponent);
                dialogRef.componentInstance.title = title;
                dialogRef.componentInstance.message = message;
                dialogRef.componentInstance.beginDate = appt.begin;
                dialogRef.componentInstance.endDate = appt.end;
                dialogRef.componentInstance.response.subscribe(res : any => {
                appt.begin = res.beginDate;
                appt.end = res.endDate;
                });

              }

           onClickGetDates(title:string , message :string , appt) {
           this.confirmDateRange(title,message,appt);
            }
                `


text:
Q: Obtain all combinations for regex substitution of overlapping pattern My goal is to obtain all the possible substitution for all overlapping patterns of a given regex.
Normally when I want to obtain a substitution with regex I do the following
import re

re.sub(pattern='III', repl='U', string='MIIII')

and I would obtain the following output:
MUI

As stated in the documentation the substitution is done only on the leftmost match in case of overlap, but what I need is to obtain all the possible substitutions, which in this case are:
MUI
MIU

My goal is using it also for complex regex patterns like the following
re.sub(pattern="M(.*)$", repl="M\\1\\1", string='MIU')
MIUIU

I didn't find any solutions natively in the python standard library

A: One of the way to implement this is to search for pattern (using re.search()) until no match pattern found and replace just single occurrence of pattern (using re.sub() with count  argument) slicing string every iteration to skip previous match.
import re

source = "MMM123"
pattern = re.compile("M(.*)$")
replacement = r"M\1\1"

last_start = 0
temp = source
while match := pattern.search(temp):
    print(source[:last_start], pattern.sub(replacement, temp, 1), sep="")
    last_start += match.start() + 1
    temp = source[last_start:]


text:
Q: Force.com IDE error 'NotAfter' Any idea what's causing this error?

It's happening on both the Force.com IDE and the Force.com plugin for Eclipse, on Windows XP 32 bit. Strangely it's ONLY happening for one particular environment (EE Production). All other production / sandbox environments are working fine.
I've googled the sh*t out of it with no joy. Any help appreciated as this is holding up a pretty major deployment.
Thanks

A: Check your local system clock?
If there's clock skew between you and salesforce it could possibly cause issues with authentication tokens, I know it does with a number of authentication systems (like Kerberos) and I wouldn't be surprised if your sessionId was viewed as "expired" on your local system.


text:
Q: How to read elements of an array? I am taking data from serial port using these commands:
char buf [256];
char a [256];
memset (&buf, '\0', sizeof buf);

/* *** READ *** */
if (n < 0)
{
    std::cout << "Error reading: " << strerror(errno) << std::endl;
}

/* Print what I read... */
std::cout << "" << buf;
int sa=0;
printf("Gelen Data : \n");

for(sa=0;sa<15;sa++){
    printf("::%0.2X",buf[sa]);
}

and this is my data:
::02::03::98::00::07::20::16::09::29::16::19::45::C0::00::00::00

I can see data coming using these commands:
for(sa=0;sa<15;sa++){
        printf("::%0.2X",buf[sa]);
}

but I don't use elements of the buf[] array in any equation; for example, I want to use buf[2] in an equation like below:
if(buf[2]==02){
    cout<<"Equality"<<endl;
}

Can anybody help me?

A: You might want to compare them in hexadecimal format.
if( buf[2]==0x02){
      cout<<"Equality"<<endl;
}

A: Can also use a switch statement with hex values, which can have performance improvements, or more likely - if you've a lot of values to work with, make the code more readable.
ie
switch (buf[2]) {
  case 0x02:
    doSomething(); break;
  case 0x04:
    soSomethingelse(); break;
}


text:
Q: button has two actions at the same time Can a button has two actions at  the same time?
1- go to another page
2- reset all inputs in both pages
I am using Intel XDK

function register_event_handlers()
 {

        /* button  Grupp 1 */
    $(document).on("click", ".uib_w_8", function(evt)
    {
        /* your code goes here */
         activate_page("#grupp1");
        document.getElementById("date1").reset();
                 document.getElementById("date2").reset();
                 document.getElementById("dag1").reset();
                 document.getElementById("dag2").reset();
                 document.getElementById("Arbetar1").reset();
                 document.getElementById("Arbetar2").reset();
                 document.getElementById("start1").reset();
                 document.getElementById("start2").reset();
                document.getElementById("slut1").reset();
                 document.getElementById("slut2").reset();
         return false;

    });
 }
 document.addEventListener("app.Ready", register_event_handlers, false);
})();

A: Set the button to run a custom script. In your custom script, just do this
$(document).on("click", "#mybutton", function(evt) {
   //this does the reset
   document.getElementById("date1").reset();
   //this goes to that page
   activate_page("#grupp1");
   return false;
});


text:
Q: SQL Server: What's wrong with this dynamic pivot? I am trying to create a dynamic pivot but it keeps telling me "you must declare the table variable @venta".
Here is the code, what am I doing wrong?
DECLARE @venta TABLE
(
    LAPSO_DOC CHAR(6),
    ID_EXT_ITM CHAR(3),
    ID_TALLA CHAR(6),
    VENTA INT
)

INSERT INTO @venta
VALUES
('201601', 'VER', 'L', '20'),
('201603', 'ROJ', 'XL', '40'),
('201604', 'NEG', 'S', '60'),
('201608', 'BLA', 'M', '80');

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
    SELECT @columns=STUFF ((SELECT DISTINCT'],['+ LAPSO_DOC
    FROM @venta
    GROUP BY '],['+LAPSO_DOC FOR XML PATH('') ),1,2,'')+']'

    SET @sql = 'SELECT
    (
        SELECT LAPSO_DOC,ID_EXT_ITM,ID_TALLA,VENTA
        FROM @venta
)
PIVOT
(
  SUM(CANTIDAD_CAP) FOR LAPSO_DOC IN ('+@columns+')
) AS y;';
EXECUTE (@sql)

A: It is a scope issue.
The table variable is not available to the dynamic sql
Perhaps drop it down to a temp table

A: There are more problems with your query than you expect...
CREATE TABLE #venta (
    LAPSO_DOC char(6),
    ID_EXT_ITM char(3),
    ID_TALLA char(6),
    VENTA int
)

INSERT INTO #venta
    VALUES ('201601', 'VER', 'L', '20'),
    ('201603', 'ROJ', 'XL', '40'),
    ('201604', 'NEG', 'S', '60'),
    ('201608', 'BLA', 'M', '80');

DECLARE @columns nvarchar(max),
        @sql nvarchar(max);
SELECT
    @columns = STUFF((SELECT DISTINCT
        '],[' + LAPSO_DOC
    FROM #venta
    GROUP BY '],[' + LAPSO_DOC
    FOR xml PATH (''))
    , 1, 2, '') + ']'

SET @sql = 'SELECT ID_EXT_ITM,ID_TALLA,' + @columns + '
            FROM #venta
            PIVOT
            (
              SUM(VENTA) FOR LAPSO_DOC IN (' + @columns + ')
            ) AS y;';

EXEC (@sql)

DROP TABLE #venta

*

*As @John Cappelletti stated, you can't use table variable in a dynamic SQL; unless you have a Table type defined in database or move to a Temp table.

*There is error in your logic.  I'm quite not sure what you are trying to achieve, but the above code gives you error-free output.

*You don't have CANTIDAD_CAP column anywhere defined but used in in SQL.

*You are not supposed to SELECT the column LAPSO_DOC
You may better study some online articles on PIVOT - like this and this.

EDIT:
A coding standard

NEVER declare a column name same as table name, and vice versa.


text:
Q: How to check if do_shortcode will be execute directly in a template php file I have a template for a specific taxonomy :
taxonomy-mytaxonomy.php
<?php
defined( 'ABSPATH' ) || exit;

get_header( );
?>

    <?php
    the_archive_description( '
', '
' );

    if ( have_posts() ) {
        $queried_object = get_queried_object();
        $term_slug = $queried_object->slug;
        $shortcode = sprintf( '[my-shortcode attr1="value1" /]',
            $term_slug
        );
        echo do_shortcode($shortcode);
    } else {
        get_template_part( 'no-results', 'search' );
    }
    ?>

<?php get_footer(); ?>

In an other php file I need to check if do_shortcode will be run with my-shortcode tag to enqueue styles and scripts.
public function check_page(){
    global $post;
    if( !empty( $post->post_content ) && has_shortcode( $post->post_content, 'my-shortcode' ) ){
        add_action( "wp_enqueue_scripts", array( $this, "set_scripts" ) );
    }
}

In my case, I cannot use has_shortcode( $post->post_content, 'my-shortcode' ) because it´s not in a post_content but directly inside the template php file.
Soemone has got an idea ?

A: I found a solution.
First of all, the best way seems to not use do_shortcode direclty in the php.
You can know more here.
So...
taxonomy-mytaxonomy.php
<?php
defined( 'ABSPATH' ) || exit;

get_header( );
?>

    <?php
    the_archive_description( '
', '
' );

    if ( have_posts() ) {
        $queried_object = get_queried_object();
        $term_slug = $queried_object->slug;
        $atts = [
            'attr1' => "value1"
        ];
        echo ListCPTShortcode::getCallBack( $atts, null, "my-shortcode" );
    } else {
        get_template_part( 'no-results', 'search' );
    }
    ?>

<?php get_footer(); ?>

To enqueue scripts and styles, I did this
my-theme/functions.php
function my_shortcode_category_load( $content ){
    $current_post = get_queried_object();
    if( !empty( $current_post ) && isset( $current_post->taxonomy ) &&  $current_post->taxonomy === "mytaxonomy" ){
          wp_enqueue_style(...);
          wp_enqueue_script(...);
    }
    return $content;
}
add_filter( "the_content", "my_shortcode_category_load" );


text:
Q: Programmatically modify WIF service configuration in .NET 4.5 Using WIF with .NET 4.5 in MVC4 app with Ninject
Here's the situation - I have a custom ClaimsAuthenticationManager subclass called TenantAccessClaimsAuthenticationManager that does some claims transformation. The TenantAccessClaimsAuthenticationManager needs a IRepository object to be injected into it (using ninject).
The .NET 4.5 impl of WIF suggests that I can stick my custom claims authentication manager in the web.config - however, this approach can only instantiate the object via  a no-args ctor.
The second approach I had is to not have anything int the web.config, but in App_start, get a handle to the WIF configuration and stick in the TenantAccessClaimsAuthenticationManager in RegisterServices
How do I get a handle to the currently application's WIF configuration context?  MSDN docs aren't helping.
Edit: Obviously the problem is that the onServiceConfigurationCreated event is no longer available. What's the best way to do this now

A: The event is still available!
code://System.IdentityModel.Services:4.0.0.0:b77a5c561934e089/System.IdentityModel.Services.FederatedAuthentication/event:FederationConfigurationCreated:System.EventHandler
More specifically, the event is available at FederatedAuthentication.FederationConfigurationCreated. An example implementation is below:
FederatedAuthentication.FederationConfigurationCreated += (sender, e) => {
    e.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager = new MyCustomClaimsAuthenticationManager();
}

There's a blog post at http://dunnry.com/blog/2012/12/20/SettingClaimsAuthenticationManagerProgrammaticallyInNET45.aspx with more information.


text:
Q: Test old commit in Git Repository I currently have a Project(JavaScript) with a bug in it and I am sure that I fixed it sometime ago, now my Question is how to revert to an old commit and check that Version on my localhost.
But I do not want to loose any changes in my git repo I just want to check how the Project look at commit X, how do I manage that.
I am using gitkraken as a gui.

A: *

*Be sure you have no uncommited changes; commit or stash them if necessary

*Create a new branch at your current HEAD (using the Branch button)

*Search the commit you want to take a look at

*Right click the commit, choose Reset <branchname> to this commit > Hard - discard all changes. This will reset the branch you just created to this commit.

*You travelled back in time. Test and check everything you need to. If you want to go back to the present, just check out your original branch.

EDIT:
There's an even easier way!

*

*Be sure you have no uncommited changes; commit or stash them if necessary

*Search the commit you want to take a look at

*Right click the commit, choose Create branch here. Enter a branch name. This will create a branch at this commit.

*Check out the newly created branch by double-clicking.

*You travelled back in time. Test and check everything you need to. If you want to go back to the present, just check out your original branch.

A: If you are unsure when the bug was introduced/fiex you can use the bisect approach of git: https://git-scm.com/docs/git-bisect
git bisect start
git bisect bad COMMIT_KNOWN_TO_FAIL
git bisect good COMMIT_KNOWN_TO_PASS

Then git will select a commit in the middle. You can do your check and depending on the result of your test you call:
 git bisect good

if the test passes and
 git bisect bad

if the test fails.
Then git selects another commit towards the former good if the test failed and towards the **bad* if the test passed.
Since you're looking for when the problem disappeard you might have to switch the meaning of "good" and "bad" when continuing...
when you identified the malicios commit call
git bisect reset


text:
Q: AngularJs execution context (scope) I got a valid code full of callback functions, Callback hell.
Here it is :
app.directive('destinationDirective', function () {
    function destinationController($http, $rootScope, $scope) {
        $scope.getWeather = function (destination) {
            var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + destination.city
                + '&appid=' + $scope.apiKey
                + '&units=metric';
            $http.get(url).then(function success(response) {
                console.log('success', response);
                if (response.data.weather) {
                    destination.weather = {};
                    destination.weather.main = response.data.weather[0].main;
                    destination.weather.temp = response.data.main.temp;
                } else {
                    $scope.message = 'City not found';
                }
            }, function error(error) {
                $scope.message = 'Server error'
            });
        };
    }

    return {
        scope: {
            destination: '=',
            apiKey: '=',
            onRemove: '&'
        },
        templateUrl: './destinationDirective.html',
        controller: destinationController
    };
});

So I try to make it flatter with functions definitions like below, but it's seems the execution context can not resolve my destination variable. I try to bind the execution context and it's still can't resolve. Did AngularJS kind of "tweak" the execution context of the function?
app.directive('destinationDirective', function () {
    function destinationController($http, $rootScope, $scope) {
        $scope.getWeather = function (destination) {
            var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + destination.city
                + '&appid=' + $scope.apiKey
                + '&units=metric';
            $http.get(url).then(success.bind(destination), error);
        };
    }

    function success(response) {
        console.log('success', response);
        if (response.data.weather) {
            destination.weather = {};
            destination.weather.main = response.data.weather[0].main;
            destination.weather.temp = response.data.main.temp;
        } else {
            $scope.message = 'City not found';
        }
    }

    function error(error) {
        $scope.message = 'Server error'
    }

    return {
        scope: {
            destination: '=',
            apiKey: '=',
            onRemove: '&'
        },
        templateUrl: './destinationDirective.html',
        controller: destinationController
    };
});

I also tried:
$http.get(url).then(angular.bind(this, success, destination), error);

and:
$http.get(url).then(success.bind(this, destination), error);

But now I got the content of the destination and lose the response of the API
EDIT ABOUT SUPPOSED DUPLICATION: My problem is unique because the subject is about angular context when defined multiples functions on a controller, I find a solution and I will post it right now.

A: The trick here is to define a "private member attribute" for the "class" destinationController like below. The functions look back on the previous execution context and find the desired attribute. Not an evidence before I asked the question from my classic OOP background (Java, C# and PHP) when I had to reformat some callbacks hell like it was originally.
app.directive('destinationDirective', function () {
    function destinationController($http, $rootScope, $scope) {
        var _destination;

        $scope.getWeather = function (destination) {
            _destination = destination;
            var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + destination.city
                + '&appid=' + $scope.apiKey
                + '&units=metric';
            $http.get(url).then(success, error);
        };

        function success(response) {
            if (response.data.weather) {
                _destination.weather = {};
                _destination.weather.main = response.data.weather[0].main;
                _destination.weather.temp = response.data.main.temp;
            } else {
                $rootScope.message = 'City not found';
            }
        }

        function error(error) {
            $rootScope.message = 'Server error'
        }
    }

    return {
        scope: {
            destination: '=',
            apiKey: '=',
            onRemove: '&'
        },
        templateUrl: './destinationDirective.html',
        controller: destinationController
    };
});


text:
Q: Unable to Run Python Code in Terminal Visual studios code(EntryNotFound Unable to read file) FilenotFoundError
Currently trying to run some python code on vscode but I got this error also for some reason I'm not getting any output in the terminal, can't type anything in it either what should I do?
NoTerminalOutputInVScode
launcherTimedOut
I tried to debug my python file and vsc would return this.
launch.json
This be what my launch.json file looks like.


text:
Q: get a property value of an individual jena api I have my class Alert which contain as individual
Alert_1
Alert_2
Alert_3

and each individual has properties witch contains values
for example
Alert_1 :
      hasanalyser : analyser546
      hastime: 10
      hasdatainfo: difficult

I can now get all individuals but I can not get those (hasanalyser, hastime and hasdatainfo)  values
Here is my code and it works. How I can get what I want please?
owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");

OntModel model = owlModel.getOntModel();

OWLNamedClass theAlert = owlModel.getOWLNamedClass("Alert");
Collection CAlerte = theAlert.getInstances();

int nombreAlerte =CAlerte.size();
String[ ] list_alerte=new String[ nombreAlerte ];
OWLIndividual[ ] idorg=(OWLIndividual[ ]) CAlerte.toArray(new OWLIndividual[ 0 ]);
for(int j=0;j< nombreAlerte;j++){
    list_alerte[ j ]=idorg[ j ].getName();
}

System.out.println(" le nombres des alerte est:"+nombreAlerte);
OntModel inf1 = ModelFactory.createOntologyModel();
for(int k=0;k< nombreAlerte;k++){
    System.out.println(" \n"+list_alerte[k]);
}

Here it display my
Alert_1
Alert_2
Alert_3

How to get their properties?

UPDATE:
Thanks for your answer, it doesn't work yet.  I tried now to do like you said
    JenaOWLModel owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");
    OntModel model = owlModel.getOntModel();

    ArrayList<Resource> results = new ArrayList<Resource>();

    ExtendedIterator  individuals = model.listIndividuals();
    while (individuals.hasNext()) {
        Resource individual = (Resource) individuals.next();
        results.add(individual);
    }

    for(int i = 0; i < results.size(); i++)
    {
      System.out.println("individual number " + i + " = " + results.get(i));//here it display my individual

      Individual ind = model.getIndividual(results.get(i).toString());
      Property hasTime = model.createProperty( "file:///D:/base_connaissance.owl#hasanalyser" );
      RDFNode time = ind.getPropertyValue( hasTime );
      System.out.println("property value of hasanalyser "+time);

At the end it displays all names of my individuals, and after each individual it display property value of hasanalyser NULL.
where is the problème please

A: IT WORK NOW , i can get now all properties of all individuals thanks lot , now what it doesnt work is HOW to add an individual and add properties to this individual and insert it into my "base_connaissance.owl"  if you can help me i realy appreciate it here is the full code witch work perfectly .
static JenaOWLModel owlModel ;
public static void main(String[] args) {

    OntModel model;
    javax.swing.JDialog jDialog1 = new javax.swing.JDialog();
    try{
        String ns="file:///D:/base_connaissance.owl#";
        owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");//  crée  un modele owl  a partir du ficher owl charger
        model = owlModel.getOntModel();
        JOptionPane.showMessageDialog(jDialog1,"chargement du fichier  effectuer avec succé","Information",JOptionPane.INFORMATION_MESSAGE);

        ArrayList<Resource> results = new ArrayList<Resource>();
        ExtendedIterator  individuals = model.listIndividuals();
        while (individuals.hasNext()) {
            Resource individual = (Resource) individuals.next();
            results.add(individual);
        }
        System.out.println("\n");

        for(int i = 0; i < results.size(); i++)
        {
        Individual ind = model.getIndividual(results.get(i).toString());
        System.out.println(""+ind);
        StmtIterator it = ind.listProperties();

        while ( it.hasNext()) {
               Statement s = (Statement) it.next();

            if (s.getObject().isLiteral()) {

                System.out.println(""+s.getLiteral().getLexicalForm().toString()+" type = "+s.getPredicate().getLocalName());

                }

            else    System.out.println(""+s.getObject().toString().substring(53)+" type = "+s.getPredicate().getLocalName());

                 }
        System.out.println("\n");
            }

    }
    catch(Exception e){
        JOptionPane.showMessageDialog(jDialog1,
                "error",
                "Information",
                JOptionPane.INFORMATION_MESSAGE);
    }
}

A: I'm not clear from your code how you are using Jena models.  The OntModel called model does not appear to be used, nor does the InfModel called inf1.  OWLIndividual is not a Jena class, but a Protégé one.  The question asks about using the Jena API, however, so the rest of this answer assumes that you can get the Individuals that you are interested in, not the OWLIndividuals.
Jena's Individuals have a method getPropertyValue that returns the value of a property for the individual.  You should be able to do something like this:
Individual alert1 = ...;
String hasTimeURI = "...";
Property hasTime = model.createProperty( hasTimeURI );
RDFNode time = alert1.getPropertyValue( hasTime );

The additional code you posted is printing null probably because the IRI for the property is incorrect.  File-based IRIs are not very good identifiers;  URIs are supposed to be universal identifiers, and something that includes a file path almost certainly isn't going to be universal.  Without seeing your data, we cannot know what the proper IRI for the property should be.  However, if you do something like this, you should be able to get enough information to determine what the property IRI should be.
Individual ind = model.getIndividual(results.get(i).toString());
// Check whether ind is null.
System.out.println( "ind: "+ind );
// Iterate over all the statements that have ind as subject.
StmtIterator it = ind.ListProperties();
while ( it.hasNext() ) {
  System.out.println( it.next() );
}


text:
Q: С помощью каких технологий можно сделать локальный сервер на питоне? У меня есть приложение на Реакт, а точнее на typesctipt, в котором можно сохранять картинки и музыку.
Проблема в том, что насколько я понимаю, файлы музыки нельзя сохранять локально в браузере. Поэтому хотелось бы сделать свой сервер, в котором я смогу хранить все файлы, которые мне нужны.
Мне бы хотелось сделать его на Питон - с помощью каких технологий можно это сделать?

A: Вот пример из документации по aiohttp, дополненный для самодостаточности:
from aiohttp import web
import os

async def form(request):
    return web.Response(text="""
        <form action="/store/mp3" method="post" accept-charset="utf-8"
          enctype="multipart/form-data">
        Mp3
        <input id="mp3" name="mp3" type="file" value=""/>
        <input type="submit" value="submit"/>
        </form>""", content_type='text/html')

async def store_mp3_handler(request):
    reader = await request.multipart()

    # /!\ Don't forget to validate your inputs /!\

    # reader.next() will `yield` the fields of your form

    field = await reader.next()
    assert field.name == 'mp3'
    filename = field.filename
    # You cannot rely on Content-Length if transfer is chunked.
    size = 0

    with open(os.path.join('mp3/', filename), 'wb') as f:
        while True:
            chunk = await field.read_chunk()  # 8192 bytes by default.
            if not chunk:
                break
            size += len(chunk)
            f.write(chunk)

    return web.Response(text='''
        {} sized of {} successfully stored in
        /mp3/'''.format(filename, size),
        content_type='text/html')

os.makedirs('mp3/', exist_ok=True)

app = web.Application()
app.add_routes([web.static('/mp3', 'mp3/', show_index=True)])
app.add_routes([web.get('/', form)])
app.add_routes([web.post('/store/mp3', store_mp3_handler)])

web.run_app(app)

Установить aiohttp:
python3 -m pip install aiohttp

А просто раздать папку на питоне можно без кода и дополнительных библиотек
python3 -m http.server


text:
Q: MySQL - order results by result of arithmetic/functional calls on two columns I would like to return results based on the field 'score' and an arithmetic operation on 'time'. Here's what I would like to do:
select id, score from questions order by MIN(0, (10 - (time - 'now')/(60*60))) + score;

I am trying to order results based on score and based on some measure related to the number of hours that have passed since a row was logged. How can I do this?

A: select id, score, MIN(0, (10 - (time - 'now')/(60*60))) + score AS sort
from questions order by sort;

This can get your sorted results without dealing with stored procedures, multiple queries, etc
select id, score FROM (select id, score, MIN(0, (10 - (time - 'now')/(60*60)))
+ score AS sort from questions order by sort ) AS t;

You can go a step further to eliminate the unneeded column in your final results.


text:
Q: Creating Maven Web Service on Tomcat I created a Maven web application which name is "aa3" on Netbeans. I choose Tomcat server which Netbeans installed. And then I added a web service class. A warning appeared, it says:

I choose Yes.
Then I run my project but it did not work.
Outputs are:
aa3
cd /home/ekcdr/NetBeansProjects/aa3; JAVA_HOME=/usr/lib/jvm/java-7-oracle /home/ekcdr/netbeans-7.3/java/maven/bin/mvn -Dnetbeans.deploy=true -Dnetbeans.deploy.clientUrlPart=/NewWebService package
Scanning for projects...

------------------------------------------------------------------------
Building aa3 1.0-SNAPSHOT
------------------------------------------------------------------------

[dependency:copy]

[resources:resources]
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
skip non existing resourceDirectory /home/ekcdr/NetBeansProjects/aa3/src/main/resources

[compiler:compile]
Compiling 1 source file to /home/ekcdr/NetBeansProjects/aa3/target/classes

[resources:testResources]
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
skip non existing resourceDirectory /home/ekcdr/NetBeansProjects/aa3/src/test/resources

[compiler:testCompile]
No sources to compile

[surefire:test]
No tests to run.
Surefire report directory: /home/ekcdr/NetBeansProjects/aa3/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[war:war]
Packaging webapp
Assembling webapp [aa3] in [/home/ekcdr/NetBeansProjects/aa3/target/aa3-1.0-SNAPSHOT]
Processing war project
Copying webapp resources [/home/ekcdr/NetBeansProjects/aa3/src/main/webapp]
Webapp assembled in [79 msecs]
Building war: /home/ekcdr/NetBeansProjects/aa3/target/aa3-1.0-SNAPSHOT.war
WEB-INF/web.xml already added, skipping
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 8.208s
Finished at: Fri May 24 19:06:43 EEST 2013
Final Memory: 16M/132M
------------------------------------------------------------------------
NetBeans: Deploying on Apache Tomcat 7.0.34.0
    profile mode: false
    debug mode: false
    force redeploy: true
Starting Tomcat process...
Waiting for Tomcat...
Tomcat server started.
Undeploying ...
OK - Undeployed application at context path /aa3
In-place deployment at /home/ekcdr/NetBeansProjects/aa3/target/aa3-1.0-SNAPSHOT
Deployment is in progress...
deploy?config=file%3A%2Ftmp%2Fcontext6381208068383234000.xml&path=/aa3
FAIL - Deployed application at context path /aa3 but context failed to start
The module has not been deployed.
See the server log for details.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:210)
    at org.netbeans.modules.maven.j2ee.ExecutionChecker.performDeploy(ExecutionChecker.java:178)
    at org.netbeans.modules.maven.j2ee.ExecutionChecker.executionResult(ExecutionChecker.java:130)
    at org.netbeans.modules.maven.execute.MavenCommandLineExecutor.run(MavenCommandLineExecutor.java:212)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)

Apache Tomcat 7.0.34.0 Log
May 24, 2013 4:50:15 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServletContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:536)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1462)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:792)
    at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1445)
    at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:860)
    at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:357)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

May 24, 2013 4:50:15 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Skipped installing application listeners due to previous error(s)
May 24, 2013 4:50:47 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServletContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1256)
    at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:376)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

May 24, 2013 4:50:47 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Skipped installing application listeners due to previous error(s)

Apache Tomcat 7.0.34.0
May 24, 2013 7:06:47 PM org.apache.catalina.core.AprLifecycleListener init
Using CATALINA_BASE:   /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base
Using CATALINA_HOME:   /home/ekcdr/apache-tomcat-7.0.34
Using CATALINA_TMPDIR: /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/temp
Using JRE_HOME:        /usr/lib/jvm/java-7-oracle
Using CLASSPATH:       /home/ekcdr/apache-tomcat-7.0.34/bin/bootstrap.jar:/home/ekcdr/apache-tomcat-7.0.34/bin/tomcat-juli.jar
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/lib/jvm/java-7-oracle/jre/lib/amd64:/usr/lib/jvm/java-7-oracle/jre/lib/i386::/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
May 24, 2013 7:06:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8084"]
May 24, 2013 7:06:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
May 24, 2013 7:06:48 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2289 ms
May 24, 2013 7:06:49 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
May 24, 2013 7:06:49 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.34
May 24, 2013 7:06:49 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/d1.xml
May 24, 2013 7:06:49 PM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base /home/ekcdr/NetBeansProjects/d1/target/d1-1.0-SNAPSHOT does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:138)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4906)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5086)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

May 24, 2013 7:06:49 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in resourceStart()
May 24, 2013 7:06:49 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
May 24, 2013 7:06:49 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/d1] startup failed due to previous errors
May 24, 2013 7:06:49 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/aa2.xml
May 24, 2013 7:06:58 PM com.sun.xml.ws.transport.http.servlet.WSServletContextListener parseAdaptersAndCreateDelegate
SEVERE: WSSERVLET11: failed to parse runtime descriptor: java.lang.NoClassDefFoundError: org/glassfish/ha/store/api/BackingStoreException
java.lang.NoClassDefFoundError: org/glassfish/ha/store/api/BackingStoreException
    at com.sun.xml.ws.transport.http.servlet.ServletAdapter.<init>(ServletAdapter.java:95)
    at com.sun.xml.ws.transport.http.servlet.ServletAdapterList.createHttpAdapter(ServletAdapterList.java:77)
    at com.sun.xml.ws.transport.http.servlet.ServletAdapterList.createHttpAdapter(ServletAdapterList.java:53)
    at com.sun.xml.ws.transport.http.HttpAdapterList.createAdapter(HttpAdapterList.java:77)
    at com.sun.xml.ws.transport.http.HttpAdapterList.createAdapter(HttpAdapterList.java:71)
    at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:266)
    at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:152)
    at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:131)
    at com.sun.xml.ws.transport.http.servlet.WSServletContainerInitializer.onStartup(WSServletContainerInitializer.java:65)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5274)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: org.glassfish.ha.store.api.BackingStoreException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 22 more

May 24, 2013 7:06:58 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/aa2] startup failed due to previous errors
May 24, 2013 7:06:58 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/d6_tc_yes.xml
May 24, 2013 7:06:58 PM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base /home/ekcdr/NetBeansProjects/d6_tc_yes/target/d6_tc_yes-1.0-SNAPSHOT does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:138)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4906)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5086)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

May 24, 2013 7:06:58 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in resourceStart()
May 24, 2013 7:06:58 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
May 24, 2013 7:06:58 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/d6_tc_yes] startup failed due to previous errors
May 24, 2013 7:06:58 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/aa1.xml
May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/aa1] startup failed due to previous errors
May 24, 2013 7:07:01 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/deneme1.xml
May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base /home/ekcdr/NetBeansProjects/deneme1/target/deneme1-1.0-SNAPSHOT does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:138)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4906)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5086)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in resourceStart()
May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/deneme1] startup failed due to previous errors
May 24, 2013 7:07:01 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/ROOT.xml
May 24, 2013 7:07:01 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/a1.xml
May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base /home/ekcdr/NetBeansProjects/a1/build/web does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:138)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4906)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5086)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in resourceStart()
May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
May 24, 2013 7:07:01 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/a1] startup failed due to previous errors
May 24, 2013 7:07:01 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/manager.xml
May 24, 2013 7:07:02 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/aa3.xml
May 24, 2013 7:07:02 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/aa3] startup failed due to previous errors
May 24, 2013 7:07:02 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/deneme2.xml
May 24, 2013 7:07:02 PM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base /home/ekcdr/NetBeansProjects/deneme2/build/web does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:138)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4906)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5086)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

May 24, 2013 7:07:02 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in resourceStart()
May 24, 2013 7:07:02 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
May 24, 2013 7:07:02 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/deneme2] startup failed due to previous errors
May 24, 2013 7:07:02 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8084"]
May 24, 2013 7:07:02 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
May 24, 2013 7:07:02 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 13561 ms
May 24, 2013 7:07:03 PM org.apache.catalina.util.LifecycleBase stop
INFO: The stop() method was called on component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/aa3]] after stop() had already been called. The second call will be ignored.
May 24, 2013 7:07:03 PM org.apache.catalina.startup.HostConfig deleteRedeployResources
INFO: Undeploying context [/aa3]
May 24, 2013 7:07:03 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /home/ekcdr/.netbeans/7.3/apache-tomcat-7.0.34.0_base/conf/Catalina/localhost/aa3.xml
May 24, 2013 7:07:04 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/aa3] startup failed due to previous errors

What is the problem in my project?

A: You need to copy ha-api.jar to your Tomcat/lib regardless if your project is bundled with jaxb-api or not (Mine is).


text:
Q: Upload file to an IIS server with AJAX using HTML and JavaScript I want to be able to upload an image file (.png, .jpg, etc..) to my web-server (running IIS Server with ASPX) using nothing but HTML and AJAX.
Here's the code:
<form id="personal-details-form" name="detailsfrm" method="POST" action="/ASPX/verifyPersonalDetails" enctype="multipart/form-data" novalidate>

  <input id="profile-pic-input" name="pfpinput" type="file" accept="image/png, image/jpeg"
         onchange="readImage(this);" style="display: none" />

// JS
function readImage(input) {
    document.getElementById("personal-details-error").innerHTML = "";
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#profile-pic').attr('src', e.target.result);
            $('#profile-pic-check').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
    }
}

function clearImage() {
    document.getElementById("personal-details-error").innerHTML = "Invalid image.";
    document.getElementById("profile-pic-input").value = "";
}

$("#personal-details-form").submit(function (e) {
    e.preventDefault();
    $(".form-field").addClass("used");
    document.getElementById("personal-details-error").innerHTML = ""; // Remove errors
    if (document.getElementById("personal-details-form").checkValidity()) {
        $.ajax({
            type: "POST",
            url: "../ASPX/verifyChangeDetails.aspx",
            data: $("#personal-details-form").serialize(),
            success: function (data) {

            },
        });
    }
});

if (Request.Files["pfpinput"] != null) {
    HttpPostedFile MyFile = Request.Files["pfpinput"];
    Response.Write(MyFile);
} else {
    Response.Write("Nope!");
}

I've heard that enctype="multipart/form-data" works, but clearly doesn't in my case...
What should I do in order for my AJAX code to upload the image file?

A: Turns out I needed a FormData object, and add a file onto it, along with other things, since I was using AJAX.
var formData = new FormData(document.detailsfrm);
formData.append("pfpinput", document.detailsfrm.pfpinput.files[0]);


text:
Q: unexpected behavior of rep() in R I'm trying to create a vector in R using the rep() function
p <- .9
n <- 100
rep(8,n*(1-p)^2) # expect 8

What is causing the unexpected behavior?

A: The reason for this is in the comments to the question. A workaround is using:
rep(8, round(n*(1-p)^2))

A: Condensing the comments. The second argument of rep should be an integer. From the help page: ?as.integer, we know that real numbers are truncated towards zero. So
n*(1-p)^2

is passed to
as.integer(n*(1-p)^2)

which is equal to 0.


text:
Q: How to remove
* list items and make the remaining ones change their position and id? Tricky question and far too advanced for my level (js student).
Lets say I use the append method to generate
 items inside an
, and I need each one of those li items to have a unique id, so I thought to get the amount of
 (length) items I generated by saying this : var index = document.getElementById("ol1").getElementsByTagName("li").length+1; and use this number to create unique id's for every item I generate by doing this: li.id="li"+index; so the first one I generate becomes #li1 (since the amount of li items is one), the next one #li2 and so on. *btw, is it the right approach to do this?
Now lets say I want to remove #li1, then #li2 would replace it in position 1 of the list, but its id will still be #li2 since it has gotten it already.
For example what I ultimately want is when I remove #li1, then #li2 becomes #li1, #li3 becomes #li2, #li4 becomes #li3.....and so on.
What would be the right logic approach to do such a gimmick?

function append() {

  var index = document.getElementById("ol1").getElementsByTagName("li").length + 1;

  var ol = document.getElementById("ol1");
  var li = document.createElement("li");

  li.id = "li" + index;
  li.innerHTML = (`LIST ITEM <input value=this is id: #li${index}><button class=remove id= button${index} onclick=remove${index}()>REMOVE</button>`);
  ol.append(li)

}

function remove1() {
  var rem = document.getElementById("li1");
  rem.remove();
}

function displayIndex() {
  var index = document.getElementById("ol1").getElementsByTagName("li").length;

  alert(index);
}
#li1 {
  color: red;
}

#li2 {
  color: green;
}

#li3 {
  color: blue;
}

ol button {
  color: red;
  visibility: hidden;
}

#button1 {
  color: red;
  visibility: visible;
}

  <button id="btn1" onclick="append()">Append</button>
  <button id="btn2" onclick="displayIndex()">Index</button>

A: First off:
There are no "right" approaches. Only working implementations. How it is achieved might differ from developer to developer, and as long as it works, it should be considered the "right" way (however, not necessarily the most efficient or optimized or any other way).
One way would be to use a remove() function that re-assigns the ID's of the remaining
s (after the removal, obviously) as a side-effect.

function removeItemOf(list, listItem) {
  if (!list.contains(listItem)) return;

  listItem.remove();
  indexItemsOf(list);

  // For displaying the removed ID on-screen
  document.querySelector('div').append(
    document.createElement('br'),
    document.createTextNode(`Removed <li> with id '${listItem.id}'`)
  );
}

function indexItemsOf(list) {
  for (var i = 0; list.children[i]; ++i) {
    list.children[i].id = (list.id || list.tagName) + '-li' + i;

    // For displaying the
's ID on-screen
    list.children[i].textContent = `With ID '${list.children[i].id}'`;
  }
}

var list = document.querySelector('ol');

indexItemsOf(list);
setTimeout(() => {
  removeItemOf(list, list.children[0]);
}, 2000);
setTimeout(() => {
  removeItemOf(list, list.children[1]);
}, 4000);

However, re-assigning a previously used ID makes it not unique to one element, as it now identifies another element it hasn't identified before. For environments where this would be important (e.g. relying on an element to reference certain other elements, or to have a certain event-listener, etc.), re-using an ID would break the environment.
To circumvent this problem, one could keep track of how many unique items a list had over its entire lifetime, and create the next item with an ID using that amount, and then increase the amount by one.
Here is an example:

var list = document.querySelector('ol');
list.uniqueItems = 0;

// Here: Using Event-Delegation for removing a

list.addEventListener('click', function(evt) {
  if (evt.target.classList.contains('btn-delete'))
    evt.target.closest('li').remove();
});

document.querySelector('button').addEventListener('click', function() {
  var item = document.createElement('li');
  item.id = 'li-' + list.uniqueItems;
  item.textContent = `Has the ID '${item.id}' `;

  var btnDelete = document.createElement('button');
  btnDelete.classList.add('btn-delete');
  btnDelete.textContent = 'Delete Item';

  item.append(btnDelete);
  list.append(item);

  list.uniqueItems++;
});
<button>New Item</button>

A: You can just loop through each list item after your remove one and regenerate the IDs for each.

ol = document.getElementById("ol1");

function indexLIs(){
  i = 1;
  ol.querySelectorAll("li").forEach(function(li){
     id = "li" + i;
     li.setAttribute("id",id);
     li.querySelector("input").value = "this is id: #" + id;
     i++;
  });
}

function append() {

  var index = document.getElementById("ol1").getElementsByTagName("li").length + 1;

  var li = document.createElement("li");

  li.id = "li" + index;
  li.innerHTML = (`LIST ITEM <input value=this is id: #li${index}><button class=remove id= button${index} onclick=remove${index}()>REMOVE</button>`);
  ol.append(li)

}

function remove1() {
  var rem = document.getElementById("li1");
  rem.remove();
  indexLIs();
}

function displayIndex() {
  var index = document.getElementById("ol1").getElementsByTagName("li").length;

  alert(index);
}
#ol1 li:nth-child(1) {
  color: red;
}

#ol1 li:nth-child(2) {
  color: green;
}

#ol1 li:nth-child(3) {
  color: blue;
}

ol button {
  color: red;
  visibility: hidden;
}

#button1 {
  color: red;
  visibility: visible;
}

  <button id="btn1" onclick="append()">Append</button>
  <button id="btn2" onclick="displayIndex()">Index</button>

A: Your approach is fine. It would be easier for you to keep counting from the last element without changing the other elements even if you remove an element. In that situation use a global variable and initialize it with the length of your initial list. Something like that should do the work:
var index = 1; // or the index you wish to start from
function append(){

var ol = document.getElementById("ol1");
var li = document.createElement("li");

  li.id="li"+index;
  li.innerHTML = (`LIST ITEM <input value=this is id: #li${index}><button class=remove id= button${index} onclick=remove${index}()>REMOVE</button>`);
  ol.append(li);
  // now we will increment our index for the next iteration
  index++;

}

Hope this was useful.


text:
Q: set multiselect lookup column using jquery I have a Multi select Look up column which as you all know is a control with two list boxes and "Add or Remove" Buttons.
The user populates the right-hand side of the control with some values by clicking the Add button; I have saved those selected values into array. Now the user changes an option in a cascading dropdown which actually populates this multi select lookup column.
Normally in this scenario, the default values are loaded into the left-hand side of the look up with the right-hand "Responsibility selected values" being blank. What I want to do is to load the right-hand listbox with the values stored in array.
I am open to a solution which is based on both jQuery and JavaScript Client Object Model. I haven't been successful so far. :( Please help.
 var newarry = new Array();
 $("[title='System']").change(function() {
     var responsibilityval = "";
     if (newarry.length > 0) {
         $.each(newarry, function(i) {
             if (newarry[i] != '') {
                 alert(newarry[i]);
                 var mySelect = $("[title='Unit']");
                 mySelect.prepend("<option value='0'>Before Apples</option>");
             }
         });
     }
 });

I tried other options like but it didn't work
var mySelect = $("[title='Unit']");
mySelect.val(1)

Javascript object model sample
 function getWebSiteData() {
     clientContext = new SP.ClientContext.get_current();
     if (this.clientContext != undefined && clientContext != null) {

         var webSite = clientContext.get_web();
         oList = webSite.get_lists().getByTitle("Add New User");
         $.urlParam = function(name) {
             var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
             return results[1] || 0;
         }
         var itemid = parseInt($.urlParam('ID'));
         oListItem = oList.getItemById(itemid);
         var listinfo = new SP.ListItemCreationInformation();
         var item = oList.addItem(listinfo);
         var fields = ['Responsibility'];
         $(fields).each(function() {
             var fieldName = this;
             var field = $("#" + fieldName);
             var fieldValue = field.val();
             var entries = [];
             var newitem = new SP.FieldLookupValue();
             newitem.set_lookupId(1);

             entries.push(newitem);
             item.set_item(fieldName, entries);

         });
         item.update();
         oList.update();
         clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
     }
 }

 function success(sender, args) {
     alert('success');
 }

 function failed(sender, args) {
     alert("failed. Message:" + args.get_message());
 }

A: I use this function to set multi-select lookups
//Sets the default value(s) of a multi-select lookup
function SetMultiSelectLookup(fieldName, values)
{
    $.each(values, function(){
        $("select[title='" + fieldName + " possible values'] option:contains(" + this + ")")
                .remove()
                .appendTo($("select[title='" + fieldName + " selected values']"));
    });
    return false;
}

A: I'm using SP OnPrem 2016 and this is working for me. The key is knowing how to set the hidden field that stores that values for the field.
The SetMultiSelectLookup function is totally generic.
In my case I am setting default Language Direction, so the values J>E means Japanese>English, etc. This is the Title field of my lookup list.
//setup default values where values = lookup id's
var defaultVals = [];
defaultVals.push(2);
defaultVals.push(3);

//call function to set multi valued lookup field
SetMultiSelectLookup('My Field Name', defaultVals);

function SetMultiSelectLookup(fieldName, values){
        //add values to a multivalued select lookup field
        //fieldname = Title (display name) of the field
        //values = an array of lookup values, can be # or text
        try{
            var hiddenVal = '';
            //process each desired lookup value
            $.each(values, function(){
                //loop through all possible options and look for a match to the desired value
                var allOptions = $("select[title='" + fieldName + " possible values'] option");
                for (var i = 0; i < allOptions.length; i++) {
                    var currOption = allOptions[i];
                    //in this case 'this' is the # of the lookup value we passed in
                    if(currOption.value == this){
                        //add option to the selected values field
                        $("select[title='" + fieldName + " selected values']").append(currOption);
                        //setup value for hidden field, format:
                        //  2|tJ>E
                        //  1|tE>C|t3|tE>J    //add extra '|t' between entries
                        //  2|tJ>E|t1|tE>C|t3|tE>J    //add extra '|t' between entries
                        var newVal = currOption.value + '|t' + currOption.text;
                        if(hiddenVal == ''){
                            hiddenVal = newVal;
                        } else {
                            hiddenVal = hiddenVal + '|t' + newVal;  //insert extra '|t' between entries
                        };
                    };
                };
            });

            //add to hidden field that stores the values; if we don't do this then the record won't save
            if(hiddenVal != ''){
                //the hidden field starts with the fieldname without spaces and ends with _MultiLookup
                var hiddenFieldPrefix = fieldName.replace(/ /g, '');
                $("input[id^='" + hiddenFieldPrefix + "'][id$='_MultiLookup']").val(hiddenVal);
            };
            return;
       }
       catch(err){
            alert(err.message);
       };
};


text:
Q: logstash IllegalStateException? I am trying to execute this command: aymenstien@aymenstien-VPCEH2Q1E:/usr/share/logstash$ ./bin/logstash -f /home/aymenstien/Bureau/fb.conf
here is the config file:
input { file { path => "/home/aymenstien/Bureau/mydoc/*" start_position => beginning codec => json sincedb_path => "/home/aymenstien/Bureau/mydoc/postj1.sincedb" } } output { stdout { codec => rubydebug } elasticsearch { hosts => "localhost:9200"; index => "fbpost" document_type => "post" timeout => 30 workers => 1 } }

I am getting this error:

aymenstien@aymenstien-VPCEH2Q1E:/usr/share/logstash$ ./bin/logstash -f
  /home/aymenstien/Bureau/fb.conf  WARNING: Could not find logstash.yml
  which is typically located in $LS_HOME/config or /etc/logstash. You
  can specify the path using --path.settings. Continuing using the
  defaults Could not find log4j2 configuration at path
  /usr/share/logstash/config/log4j2.properties. Using default config
  which logs errors to the console [FATAL] 2018-07-05 12:47:56.496
  [main] runner - An unexpected error occurred!
  {:error=>#,
  :backtrace=>["/usr/share/logstash/logstash-core/lib/logstash/settings.rb:448:in
  validate'",
  "/usr/share/logstash/logstash-core/lib/logstash/settings.rb:230:in
  validate_value'",
  "/usr/share/logstash/logstash-core/lib/logstash/settings.rb:141:in
  block in validate_all'", "org/jruby/RubyHash.java:1343:ineach'",
  "/usr/share/logstash/logstash-core/lib/logstash/settings.rb:140:in
  validate_all'",
  "/usr/share/logstash/logstash-core/lib/logstash/runner.rb:279:in
  execute'",
  "/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/clamp-0.6.5/lib/clamp/command.rb:67:in
  run'",
  "/usr/share/logstash/logstash-core/lib/logstash/runner.rb:238:in
  run'",
  "/usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/clamp-0.6.5/lib/clamp/command.rb:132:in
  run'", "/usr/share/logstash/lib/bootstrap/environment.rb:73:in
  '"]} [ERROR] 2018-07-05 12:47:56.554 [main] Logstash -
  java.lang.IllegalStateException: Logstash stopped processing because
  of an error: (SystemExit) exit

A: Try using --path.settings /usr/share/logstash/config along with the config file.
The issue is that logstash is not able to find the settings directory(Config folder ) path.
Updated command:
./bin/logstash -f /home/aymenstien/Bureau/fb.conf --path.settings /usr/share/logstash/config


text:
Q: Simplify WCF configuration I have a bunch of self-hosted WCF services. Everything's working fine but I'm look for ways to normalize/simplify the resultant config. I've simplified it as much as possible, but I'm still not happy. Currently, my config looks like this:
<system.serviceModel>
    <bindings>
        <netTcpBinding>
            <binding name="BindingConfiguration" ...>
                ...
            </binding>
        </netTcpBinding>
    </bindings>

    <behaviors>
        <serviceBehaviors>
            <behavior name="ServiceBehavior">
                 ...
            </behavior>
        </serviceBehaviors>
    </behaviors>

    <services>
        <service behaviorConfiguration="ServiceBehavior" name="Name1">
            <endpoint address="net.tcp://localhost:8080/name1" binding="netTcpBinding" bindingConfiguration="BindingConfiguration" contract="Contract1">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
        </service>
        <service behaviorConfiguration="ServiceBehavior" name="Name2">
            <endpoint address="net.tcp://localhost:8080/name2" binding="netTcpBinding" bindingConfiguration="BindingConfiguration" contract="Contract2">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
        </service>
        ...
    </services>
</system.serviceModel>

In all, I have 6 services so it's repetitive. Ideally, I'd like:

*

*To specify "localhost:8080" only once and share between all services, and only specify the difference ("name1" or "name2")

*Specify the identity information only once and share between all service definitions

To my first point, I've aware of base addresses, but that only works at the service level, not across separate services. To my second point, I've tried moving the identity information into an endpoint behavior, but that doesn't appear to be supported.
Is there anything I can do to simplify this config? Or is my only option to switch to a code-based configuration approach?

A: Unfortunately, as you noticed yourself - the base address concept is only on a per-service level - so if you have lots of endpoints for a given service, then you can use it.
The only option you really would have is to use some other means of configuring your base address, and then use that to create the service endpoints in code. If you self-host your service, you could do this in your host code, before you call ServiceHost.Open() - if you host in IIS, you would have to create your own custom ServiceHostFactory which does all this setup, and then use that custom service host factory to create your service hosts in IIS.
Both is doable with a manageable effort - question is whether that's worth the trouble for you, but we can't decide that in your place ...


text:
Q: Populate dropdown value looping thru a set of links I want to loop thru the a's inside a div and populate the option value of the select box just above it with the href value of the a in the order it appears using jQuery
This is my code

    Sort by:
    <select name="sort" id="sort" class="custom_select">
        <option value="">Make</option>
        <option value="">Year of Manufature</option>
        <option value="">Price</option>
    </select>
    MakeYear of
    ManufaturePrice

I tried this but it is not working
$(document).ready(function () {
    $('div.results_filter > a').each(function (n) {
        $("#sort > options" + n).val($(this).text());
    });
})

Any help is appreciated. Please don't ask me why this awkward method. :)

A: You have to create new option element for each one and append them to the select.
var sort = $("#sort");
$("div.results_filter > a").each(function() {
    var option = $("<option>").attr("value",$(this).attr("href")).text($(this).text());
    sort.append(option);
});

http://jsfiddle.net/stwRW/


text:
Q: Merge multiple array .map into a single one I have a array of javascript objects
var arr =  [
        {
          query_result_id: 25,
          author_email: 'john@example.com'
        },
       {
          query_result_id: 28,
          author_email: 'eric@example.com'
        },
  ]

I am using .map to enter new values on each javascript object
arr
        .map( s => s["status"] = "dev")
        .map( s => s["customer_id"] = customerId)
        .map( s => s["email_nb"] = emailId)
        //and so on for about 10 new key/values

the output is:
 var arr =  [
            {
              query_result_id: 25,
              author_email: 'john@example.com',
              status: dev,
              customer_id: 45,
              email_nb: 45
            },
           {
              query_result_id: 28,
              author_email: 'eric@example.com',
              status: dev,
              customer_id: 78,
              email_nb: 56
            },
      ]

Is it possible in javascript to not chain 10 .map but instead one single operation to make it cleaner and maybe even more performant/faster ?

A: when you intend to keep the same values inside the array you shouldn't use map.
map is intended to recreate a new array with values depending on source array. What you want to do is to apply a function on each element that's what forEach is made for
here's how you can do it using foreach :

let customerId = "customerId"
let emailId = "emailId"

var arr =  [{query_result_id: 25,author_email: 'john@example.com'},
            {query_result_id: 28,author_email: 'eric@example.com'}]

arr.forEach( s => {
  s["status"] = "dev"
  s["customer_id"] = customerId
  s["email_nb"] = emailId
})

console.log(arr)

A: For each object, you can create a new object by re-using the old one's properties/values using the spread operator, and adding the other properties/values to this new object literal:
arr = arr.map(s => (
  {...s, status : "dev", customer_id : customerId, email_nb : emailId}
));

A: Yes it is possible, for example like this:
arr.map(s => {
         s["status"] = "dev";
         s["customer_id"] = customerId;
         s["email_nb"] = emailId;

         return s;
    });

Always keep in mind, that this:
arr.map(x => x + 1);

Is just a shorthand for this:
arr.map(x => {
   return x + 1;
});

A: Also, you don't have to chain map for every change you are making to your data.  Do all of the all of the changes in the body of the map's callback, and then return the object.
let data = arr.map(entry => {
    entry["something"] = otherData["something"];
    entry["something else"] = otherData["something-else"];
    // etc. for all of the keys
    // now the entry is entirely transformed, you can return it
    return entry;
})


text:
Q: How can I center the bullet points in an HTML list? I have the following HTML and CSS on a client's website:

OWNER OCCUPIED LOAN PROPERTY

INVESTMENT LOAN

FIRST HOME BUYER

REFINANCING

ul.new {
    text-align: center;
}

I'd like to center the bullet points. Can you help me do that please? Thanks.

A: If you add list-style-position: inside; into the .new, like this:
ul.new {
  list-style-position: inside;
  text-align: center;
}

It will center the list as well as the bullets. However, I don't know if this is how you would like them to be centered, or if you want the bullets to be aligned together. I'll leave an example so you can see.

A: please add Below Css and Check your output.
i think you want that.
ul.new {
    list-style-position: inside;
    margin: 0 auto;
    position: relative;
    text-align: left;
    width: 400px;
}


text:
Q: Red border around a  In Aura Lightning, I want to control when to show a red border on a
<lightning:input>

This way I can indicate to the user when there is invalid input.
This example shows what it would look like using regular HTML https://www.lightningdesignsystem.com/components/input/

A: I figured out a way to do it.
    <aura:renderIf isTrue="{!v.isError}">

                * Input Label

                <lightning:input label=" Use the format 1d 12h 30m - d=days, h=hours, m=minutes" type="text" value="{!v.userInputTime}" aura:id="userInputTime" onchange="{!c.onDurationChanged}" placeholder="1d 12h 30m"/>

Enter a value.

        </aura:renderIf>
        <aura:renderIf isTrue="{!not(v.isError)}">
            <lightning:input label=" Use the format 1d 12h 30m - d=days, h=hours, m=minutes" type="text" value="{!v.userInputTime}" aura:id="userInputTime" onchange="{!c.onDurationChanged}" placeholder="1d 12h 30m"/>
        </aura:renderIf>


text:
Q: Why do I keep receiving badge notifications from my old unused profile? A moment ago, I noticed I got a gold badge related to this question. I clicked on it and I found it is related to another profile of mine I did not use for ages as I have no idea which email and password I used for it.
But I am not supposed to see that badge on my present profile. Is not this a bug?
Note that I asked in the past to merge that profile to my current one but I have not received any answer.
Here is the screenshot:

Note that I do not receive any other notifications except the ones of the same nature (badges). If someone comments on one of my posts on the other profile, I won't receive any notification here.


text:
Q: Android ListView additional items markered error I have list view with 78 items, in my activity file I descripe onClick Function realization
lv.setOnItemClickListener(new ListView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            Log.d("Click from activity", "win");
            if(!checkedContacts.contains(clearContacts.get(arg2))){
                checkedContacts.add(clearContacts.get(arg2));
                arg1.setBackgroundColor(R.color.selectedItem);
            } else {
                checkedContacts.remove(clearContacts.get(arg2));
                arg1.setBackgroundColor(Color.WHITE);

            }

        }
    });

So when I clicked on item it change color. But if I scroll down my listView, other elements every 10 times will have new color. checkedContacts array have right values but, visualization wrong

A: The problem is that listviews recycle the views that are out of the screen so this way you are not saving the row status. When you get the row out of the screen it will be deleted and when it comes back again it will be refilled in your adapter again.
You may solve this, for example, using your checkedContacts var and make it accesible from your adapter so, if the position given in getViewfunction of your adapter you can check if the row has been checked and then youn can change the background color. If the user rotate the screen you may save this var in onSaveInstanceState in your activity to recover them later.
Hope it helps :)


text:
Q: Publish Windows Form application to ftp location I'm using Visual Studio trying to publish my win form app to ftp location so that the users can download it using a link, and later my app could notify the users to update their application.
I have a shared windows website host, I just created a ftp user with full control over a sub-domain. I can access the sub domain successfully using filezill.
but after many hours I can't publish my test win form app. It give me this error
Failed to connect to 'ftp://eee.aaa.com/' with the following error:

Unable to create the Web site 'ftp://eee.aaa.com'.  Request denied for policy reasons.

what I've been missed?


text:
Q: OpenGL batching and disabling objects I'm combining the vertex data that has the same format in a single VBO, assigning  vertex attributes based on a material that these object use and rendering them with a single glDrawArrays() call.
It is all working out great until I have to disable some objects (say object1) from being rendered at runtime. Is this even possible, assuming I've already set up all the vertex attributes and stuff? Would it be better not to use batching at all, and have vbo/vao per object (then, if an object's disabled, just don't call glDraw*() on it) ?

A: Batching requires putting all of your data in one buffer, but batching is not limited to that. Batching is about reducing the number of draw calls. Putting your data in one buffer is necessary for that, but not sufficient.
Putting all of your vertex data in one buffer alone has performance advantages, relative to having to switch buffers and vertex formats. You don't need to go all the way to batching everything into a single draw call to improve performance over using a buffer for each individual object.
In OpenGL, as discussed in this video, the primary cost of multiple draw calls isn't the draw call itself. It's the state changes you usually do between draw calls.
You've put your vertex data in the same buffer, and you must have managed to eliminate stage changes between objects if you could render everything with one draw call. At that point, you've already gained most of the performance you're going to. Accept that and move on to other lower-hanging fruit.