text:
Q: Where can I get php_mysql.dll for Windows? I just installed Apache 2.2.17, PHP 5.2.14, and MySQL 5.1.51 on Windows XP. Apache is working and is loading PHP properly, but when I try to connect to MySQL, I get "Fatal error: Call to undefined function mysql_connect()". After some googling, I found that I need to load the php_mysql.dll extension, which requires libmysql.dll. I found the libmysql.dll file in the MySQL distribution, but php_mysql.dll is nowhere to be found.
Why is it not included with PHP or MySQL? Where can I find it?

A:
MySQL is no longer enabled by default,
  so the php_mysql.dll DLL must be
  enabled inside of php.ini. Also, PHP
  needs access to the MySQL client
  library. A file named libmysql.dll is
  included in the Windows PHP
  distribution and in order for PHP to
  talk to MySQL this file needs to be
  available to the Windows systems PATH.
  See the FAQ titled "How do I add my
  PHP directory to the PATH on Windows"
  for information on how to do this.
  Although copying libmysql.dll to the
  Windows system directory also works
  (because the system directory is by
  default in the system's PATH), it's
  not recommended.

PHP/MySQL Installation manual

A: The file http://windows.php.net/downloads/releases/php-5.2.14-Win32-VC6-x86.zip as downloaded from http://windows.php.net/download/ does include php_mysql.dll. It's in the "ext" subdirectory.
You'll need to rename php.ini-recommended to php.ini. Then, edit php.ini and make sure that extension_dir is pointing to the correct directory, i.e. the one containing php_mysql.dll, e.g. c:\php\ext. Also, search for the line ;extension=php_mysql.dll and uncomment it to enable the extension.
Lastly, the file libmysql.dll should be available to the Windows system PATH. The easiest way to accomplish that is by adding the directory to which you installed PHP to your PATH.
Remember to restart Apache after making changes to php.ini. Hope this helps!


text:
Q: How to use multiple conditions with SUM, QUERY, & IMPORTRANGE in Google Sheets? I am having an issue where Sheets is giving me errors any time I add more than one condition. It just won't let me no matter what I do. I am try to sum up imported cells from a different sheet based on a couple conditions.
What am I doing wrong here? Should this work based on what is written?
=SUM(
IFERROR(QUERY(IMPORTRANGE("1pgXsD_fAm6Sw0sFkxQWKpZKzKADg2ojVreMDCq2ebqs#gid=384994158", "All SEO Projects!a2:ac"),
  "select Col14 where Col17 contains 'Y'",0))+
IFERROR(QUERY(IMPORTRANGE("1pgXsD_fAm6Sw0sFkxQWKpZKzKADg2ojVreMDCq2ebqs#gid=384994158", "All SEO Projects!a2:ad"),
  "select Col13 where Col30 contains 'N' and where not Col1 contains 'Past Due'",0)),
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return a cell based on certain condition For example I have this in my code:
if (indexPath.section == 2) {
    if ([advisorData sharedInstance].vicePresident == nil) {
        return cell;
    }
     else{
    _advisorCell.positionLabel.text = [NSString stringWithFormat:@"Vice President"];
    _advisorCell.nameLabel.text = [advisorData sharedInstance].vicePresident;
    _advisorCell.emailLabel.text = [advisorData sharedInstance].vpEmail;
    _advisorCell.selectionStyle = UITableViewCellSelectionStyleNone;;
        return _advisorCell;}
    }

I need to return a cell based on a condition. But I get an error -'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'- I don't understand why I keep getting this error because I am returning a cell. I tried without the else statement as well.

A: Most likely you never initialized _advisorCell and it's nil. In that case, all the configuration you're doing does nothing, and you're just returning nil. Alternately, the same might be true for cell.


text:
Q: MySQL Help: How do I automatically update a column? I have a table called cups with the columns item_num, product_name, amount, price, total.
I want to automatically update total = amount * price when I enter a new row with just the item_num, product_name, amount, price.
How do I do this?

A: You can use a generated column:
alter table cups add column total decimal(20, 4)
    generated always as (amount * price);

This calculates the total when the column is used, so it is always up-to-date.

A: Don't worry, you can create a simple query that produce really up-to-date rows result contains common calculation in "total" colum which complemented by sql standard (ISO/IEC). Take a look this one..
select
  item_num,
  product_name,
  amount,
  price,
  (amount * price) as total
from cups


text:
Q: BASH function that handles the exiting of the functions it's called in I have a question regarding bash functions. I'm trying to create a function called "checkexit" that I can call in other functions to check and see if I need to exit that function or not. I wanted to try and use a function to handle this because I don't want to have to use the same code over and over again.
With that said, it's not working because the return command I'm using only exits the function it's currently in and not the function the function "checkexit" is nested inside of.
I know I could take the easy road out and just add this code in wherever I need to but, I wanted to try and find something a little more elegant.
Any help would be greatly appreciated!
Here's the code I have below for the checkexit function:
function checkexit {

if [ -z "$SITEURL" ] || [[ "$SITEURL" != *".whatever.net" ]]; then
    #if exitscript set to yes, exit script
    if [[ "$exitscript" = "YES" ]]; then
        echo "Skipping $SITEURL"
        echo
        exitscript=""
        return
    else
        echo "No Site URL provided. skipping!"
        echo
        return
    fi
fi

if [[ "$exitscript" = "YES" ]] && [[ "$nodownload" = "YES" ]]; then
    echo "Failed to download file, skipping items."
    echo
    exitscript=""
    return
elif [[ "$exitscript" = "YES" ]] && [[ "$noitems" = "YES" ]]; then
    echo "No items to download, skipping items."
    echo
    exitscript=""
    return
elif [[ "$exitscript" = "YES" ]]; then
    echo "Exit script triggered. Skipping $SITEURL"
    echo
    exitscript=""
    return
fi

}

A: In checkexit, make all of your return statements return an error exit, such as return 1.
Then in your calling functions, call it with
checkexit || return

Don't try to manage the caller directly from inside the called function.


text:
Q: display parent and all child side-by-side using SQL Suppose I have a table
 INPUT Table:

 Col1 | Col2
 -----------
   A  |  B
   B  |  C
   C  |  D
   F  |  G
   G  |  H
   I  |  J
   K  | Null

Can we write a SQL query to print an output like this
OUTPUT Table:

Parent | C1 | C2 | C3
----------------------
   A   |  B | C  | D
   F   |  G | H  | Null
   I   |  J | Null Null
   K   | Null Null Null

The approach I would take is using self joins on Table2.Co2 = Table1.Col1
However, I am struggling to append columns side-by-side and the logic on getting the number of columns needed dynamically
And also as a followup question, if we are given the output table, can we write a query to get the input table
can be any sql - oracle , mysql etc
Thank you in advance !

A: You sample data has a simple linear relationship, three deep.  You can handle this with left joins:
select t1.col1 as parent, t2.col2 as c1, t3.col2 as c2, t4.col2 as c3
from t t1 left join
     t t2
     on t2.col1 = t1.col2 left join
     t t3
     on t3.col1 = t2.col2 left join
     t t4
     on t4.col1 = t3.col2
where not exists (select 1 from t tp where tp.col2 = t1.col1);


text:
Q: Build the string dynamically based on the length in c# My aim is to generate a string. which has following conditions.
First i will take an empty string and start building the string based on length.
Example:
I have an empty string "".
In the first step i want to add a string till 8 characters, means first my string is "" then till 8 characters my string should contain the value Hiwor so finally my string will be Hiwor if there is no value empty value should be padded in the string.
In the second step i want to add the string meena till 10 positions , so my final string should be Hiwor   meena. In this way i want to build my string. Ho can i achieve this. Can you please help me.
Sample:
initial string ""
first step adding string Hiwor till 8 positions,
so final string should be Hiwor
second step adding string meena till 10 postions
so final string should be Hiwor   meena  .
Till now i tried like this
 Dictionary<string, Int16> transLine = new Dictionary<string, Int16>();

            transLine.Add("ProductCode", 1);

            transLine.Add("ApplicantFirstName", 12);

            transLine.Add("ApplicantMiddleInitial", 1);

            transLine.Add("partner", 1);

            transLine.Add("employee", 8);

            List<string> list = new List<string>();
            list.Add("grouplife");
            list.Add("meena");
            list.Add("d");
            list.Add("yes");
            list.Add("yes");

            StringBuilder sb = new StringBuilder();
            foreach (var listItem in list)
            {
                foreach (var item in transLine)
                {
                    if (listItem == item.Key)
                    {
                        var length = item.Value;
                        sb.Insert(length, item.Key);
                    }
                }
            }

but it is throwing me an exception.Index was out of range. Must be non-negative and less than the size of the collection.

A: Firstly define an extension method for StringBuilder:
public static class StringBuilderExtensions
{
    public static void AppendPadded(this StringBuilder builder, string value, int length);
    {
        builder.Append($"{value}{new string(' ', length)}".Substring(0, length));
    }
    public static void AppendPadded(this StringBuilder builder, int value, int length);
    {
        builder.Append($"{new string('0', length)}{value}".Reverse().ToString().Substring(0, length).Reverse().ToString());
    }
}

Then use:
StringBuilder builder = new StringBuilder();
builder.AppendPadded("Hiwor", 8);
builder.AppendPadded("meena", 10);
return builder.ToString();

Or with your example:
foreach (string item in list)
    builder.AppendPadded(item, transLine[item]);

EDIT: Ok, so looks like you want to be able to define a format then build the string using it. Try:
(you will need to reference System.ComponentModel.DataAnnotations and System.Reflection for this)
public abstract class AnItem
{
    private static int GetLength(PropertyInfo property)
    {
        StringLengthAttribute attribute = property.GetCustomAttributes(typeof(StringLengthAttribute), true).FirstOrDefault() as StringLengthAttribute;
        if (attribute == null)
            throw new Exception($"StringLength not specified for {property.Name}");
        return attribute.MaxLength();
    }
    private string GetPropertyValue(PropertyInfo property)
    {
        if (property.PropertyType == typeof(string))
            return property.GetValue(this);
        else if (property.PropertyType == typeof(int))
            return property.GetValue(this).ToString();
        else
            throw new Exception($"Property '{property.Name}' is not a supported type");
    }
    private static void SetPropertyValue(object item, PropertyInfo property, string value)
    {
        if (property.PropertyType == typeof(string))
            property.SetValue(item, value, null);
        else if (property.PropertyType == typeof(int))
            property.SetValue(item, int.Parse(value), null);
        else
            throw new Exception($"Property '{property.Name}' is not a supported type");
    }
    public string GetPaddedString()
    {
        StringBuilder builder = new StringBuilder();
        PropertyInfo[] properties = GetType().GetProperties();
        foreach (PropertyInfo property in properties)
            builder.AppendPadded(GetPropertyValue(property), GetLength(property));
        return builder.ToString();
    }
    public static T CreateFromPaddedString<T>(string paddedString) where T : AnItem, new()
    {
        T item = new T();
        int offset = 0;
        PropertyInfo[] properties = typeof(T).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            int length = GetLength(property);
            if (offset + length > paddedString.Length)
                throw new Exception("The string is too short");
            SetPropertyValue(item, property, paddedString.Substring(offset, length)));
            offset += length;
        }
        if (offset < paddedString.Length)
            throw new Exception("The string is too long");
        return item;
    }
}
public class MyItem : AnItem
{
    [StringLength(1)]
    public string ProductCode { get; set; }

    [StringLength(12)]
    public string ApplicantFirstName { get; set; }

    [StringLength(1)]
    public string ApplicantMiddleInitial { get; set; }

    [StringLength(1)]
    public string Partner { get; set; }

    [StringLength(8)]
    public string Employee { get; set; }
}

Then use it:
MyItem item = new MyItem
{
    ProductCode = "grouplife",
    ApplicantFirstName = "meena",
    ApplicantMiddleInitial = "d",
    Partner = "yes",
    Employee = "yes"
};

string paddedString = item.GetPaddedString();

And to read a string to get an item:
MyItem item = AnItem.CreateFromPaddedString<MyItem>(paddedString);

A: At first I want to say something more about your exception:

Index was out of range. Must be non-negative and less than the size of the collection.

As the exception already said. The problem is that you want to access a position within your new StringBuilder sb which does not exists.
StringBuilder sb = new StringBuilder();

After this line your new sb is empty. There is no single character in it. So you can only access the index at position 0. But almost in your first iteration of the inner for-each loop you want to target the index 1 and try to insert your string at the position 1, which does not exists.
// length: 1 and item.Key: ProductCode
sb.Insert(length, item.Key);

So how to solve this. You can use a feature from String.Format() or since C#6 the string interpolation.
So for example:
String.Format()
var sb = new StringBuilder(string.Empty);      // sb: []
sb.Append(string.Format("{0, -8}", "Hiwor"));  // sb: [Hiwor   ]
sb.Append(string.Format("{0,-10}", "meena"));  // sb: [Hiwor   meena     ]

C#6 String Interpolation
var sb = new StringBuilder(string.Empty);  // sb: []
sb.Append($"{"Hiwor", -8}");               // sb: [Hiwor   ]
sb.Append($"{"meena", -10}");              // sb: [Hiwor   meena     ]

// ...

Targeting your edit:
With your given list items you will never get a match with any of your dictionary keys.


text:
Q: Java Script: OnMouseOver Здравствуйте. Нужно решить такой вопрос:
document.getElementById('sec_info').innerHTML = '1';

Этот код меняет содержимое блока, окей, дальше, мне нужно вычислить, при каком условии это делать. А условие следующее: при наведении на блок (div) А, выполняем этот код (вышенаписанный). Т.е. получится, говоря по нубски, следующее:
if (onMouseOver div A) document.getElementById('sec_info').innerHTML = '1';

Помогите решить задачу :) Ах, и да, обязательное условие - реализация именно на чистом JS, не на JQuery.
A:
2

document.getElementById('sec_info').onmouseenter = function() {
    this.innerHTML = '1'
}
http://jsfiddle.net/B36nk/
A: Всё там рабочее:
document.getElementById('hover_block').onmouseenter = function() {
    document.getElementById('sec_info').innerHTML = '1'
}

Фиддл: http://jsfiddle.net/B36nk/1/


text:
Q: Implementing validations in Angular 2 multi-select drop-down I was wondering bootstrap validations can be implemented in Angular 2 multi-select dropdown by cuppa labs. I went through the documentation but was unable to find any.
Basically I want to highlight the dropdown in red if user does not select any values like for a normal input I can use [ngClass]="{'is-invalid': someThing.invalid}". Here is my HTML and what I have tried:
<angular2-multiselect name="countries"
  [(ngModel)]="myModel.countries" #countries2="ngModel"
  presentInCountries [data]="countries"
  [settings]="presentInCountriesdropdownSettings"
  (ngModelChange)="multiselectChangeCountries($event)">
</angular2-multiselect>

I tried setting a boolean to true if selected countries is 0 and then apply:
this.presentInCountriesdropdownSettings.classes += ' is-invalid';

But this does not work. Is there any way to implement this?

A: Try using ReactiveForm and Required validator like this:

Component.ts

import { Component } from '@angular/core';
import { FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private fb: FormBuilder) { }

  /*########### Form ###########*/
  registrationForm = this.fb.group({
    countryName: ['', [Validators.required]]
  })

Component.html

<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
  <angular2-multiselect name="countries"
     formControlName="countryName"
     presentInCountries [data]="countries"
     [settings]="presentInCountriesdropdownSettings"
     (ngModelChange)="multiselectChangeCountries($event)">
  </angular2-multiselect>
</form>


text:
Q: Recreating aniamtion / side scroll slideshow I'm trying to recreate a animation / side scroll effect. The effect is from https://elrond.com/#partners and its located in the partner section. The slow moving circles. I tried to recreate it, but after slamming my head against mine desk for the duration of the weekend I couldn't recreate it. So here I'm asking for some help.
I made a little code pen to show where I'm at now.
    .slide-wrapper{
  max-width: 800px;
  height: 30vh;
  position: relative;
  margin: 0 auto;
  transform: translate3d(0,0,0);
  outline: red;
}

.slider{
  position: absolute;
  top: 0;
  left: 0;
  height: 200px;
  display:flex;
  transform: translate3d(0,0,0);
  animation: scroll 15s infinite linear;
}

.slider:last-child  .slide{
  background-color: steelblue;
  animation: scroll 13s infinite linear;
  margin-top: 5rem;
}

.slide{
  background-color:orangered;
  height:50px;
  width:50px;
  margin: 1rem 6rem;

}

@keyframes scroll {
  100%{transform: translateX(-66.6666%)}
}

https://codepen.io/tijmenjacobs/pen/LYxrvKq
My main questions are the following:

*

*How can I loop the animation? Now when the animation is done it teleports back to its original position and restarts.

*I was wondering how to position the circles. Should I handle JS to random assign the circles or should I hard code the location? Like they seem to do on the original.

Hope you guys could help!
Thanks in advance!

A: To get the desired effect you need two of the same sliders next to eachother (slider-main and slider-copy in the snippet).
I used CSS variables to make it easier to calculate offsets and whitespace. The offset between the slides is based on the amount per row (--slides-per-row). These are set within the HTML so you can easily reuse the slider somewhere else.

/* Basic reset */
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body > * + * {
  margin-top: 2em;
}

/* Slider styling */

.sliders {
  display: flex;
}

.slider {
  --slide-offset: calc(100vw / var(--slides-per-row, 4)); /* --slides-per-row is set via HTML and uses 4 if nothing is provided */
  --slide-size: 5rem;
  flex: 0 0 100vw;
  animation: scroll 10s linear infinite;
}

.slider-row {
  display: flex;
}

/* Offset every odd row */
.slider-row:nth-child(2n+1) {
  transform: translateX(
    calc((var(--slide-offset) / 2 + var(--slide-size) / 2) * -1)
  );
  margin-bottom: 2rem;
}

.slide {
  width: var(--slide-size);
  height: var(--slide-size);
  margin: 0 0 0 var(--slide-offset);
  background: steelblue;
  font-size: 2rem;
  color: white;
  /* Center content */
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes scroll {
  100% {
    transform: translateX(-100%);
  }
}

4 slides per row

1

2

3

4

5

6

7

8

1

2

3

4

5

6

7

8

2 slides per row

1

2

3

4

5

6

7

8

1

2

3

4

5

6

7

8


text:
Q: Some questions on Swing timer package xyz;

import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class XYZ {

    public static void main(String[] args) throws InterruptedException {

        class TimeClass implements ActionListener {

            private int counter = 0;

            @Override
            public void actionPerformed(ActionEvent e) {
                counter++;
                System.out.println(counter);
            }

        }

        Timer timer;
        TimeClass tc = new TimeClass();
        timer = new Timer (100, tc);
        timer.start();
        Thread.sleep(20000);

    }
}

In the above code :

*

*TimeClass should be created inside the main() function. Otherwise it shows the error "non static variable this cannot be referenced from a static context.". Why is this?

*When I use an access specifier for TimeClass like public or private, I'm getting an illegal start of expression error. Why is this?

A: *

*If you are defining the TimeClass outside of main method, it should be static. because you are trying to access it from a static method (main). accessing non static variables from a static block or method is not possible.

*if you are defining a class inside a method (like your case) you cannot define any access specifier for it. because its only accessible within your method and no one can see or use it outside of this method.
Change your code to something like this, then it works:
public class Test {

    private static class TimeClass implements ActionListener {

        private int counter = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            counter++;
            System.out.println(counter);
        }

    }

    public static void main(String[] args) throws InterruptedException {

        TimeClass tc = new TimeClass();
        Timer timer = new Timer (100, tc);
        timer.start();
        Thread.sleep(20000);
    }
}


text:
Q: Can You Turn Unstructured References to Structured Using VBA? (Excel 2010) I have an excel table (an actual table ie Insert > Table) that uses structured references in all of the formulas. Example: =[@[Predicted Total 2015 Days]]-COUNTA(All.Departments[@[1]:[40]])
The problem I'm having is I want to sort several of the columns from Left to Right. Excel doesn't let you do this with tables, only ranges (at least from what I've found on the subject) So it seems that my only option is to unlist the table (convert it to a range) and then convert it back. However after converting it back to a table my formulas lose their structured references Example : =Sheet2!$V2-COUNTA(Sheet2!$X2:$BK2)
Is there any way to convert these formulas back to structured? Or even better yet, a way to sort left to right without having to convert my table back and forth?

A: I was able to sort columns using the structured references in Excel 2010 with no issues. Formulas within the table using structured references to other columns and data were sorted. No converting formulas back and forth.
Option Explicit

Sub SortTable()
    Dim ws As Worksheet
    Dim tbl As ListObject

    Set ws = ActiveSheet
    Set tbl = ws.ListObjects("MyTable")

    With tbl.Sort
        .SortFields.Clear
        .SortFields.Add Key:=ws.Range(tbl.Name & "[PredictedTotal]"), _
                        SortOn:=xlSortOnValues, Order:=xlDescending, _
                        DataOption:=xlSortNormal
        .SortFields.Add Key:=ws.Range(tbl.Name & "[AllDepartments]"), _
                        SortOn:=xlSortOnValues, Order:=xlAscending, _
                        DataOption:=xlSortNormal
        .header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

A: I figured out a way around converting my table to a range. In case anyone was curious I decided to post my solution.
It's now set up to copy the entire table, Paste it as transposed values into a destination worksheet, where it then does a loop sorting each column's dates from oldest to newest, and then it takes those sorted dates and pastes them as transposed values back into the original table.
Yay to figuring out my own solution! =D
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Application.ScreenUpdating = False

Dim SourceWS As Worksheet
Dim DestWS As Worksheet
Dim TblRange As Range
Dim DataRange As Range
Dim LastRow As Long

Set SourceWS = Worksheets("For HR Use ONLY")
Set DestWS = Worksheets("Transposed Table")

DestWS.Visible = xlSheetVisible
DestWS.Cells.ClearContents

SourceWS.Activate

LastRow = SourceWS.Range("A1").CurrentRegion.Rows.Count
Set TblRange = SourceWS.Range("A1:BM" & LastRow)

TblRange.Copy
DestWS.Range("A1").PasteSpecial xlPasteValues, xlPasteSpecialOperationNone, True, True
Application.CutCopyMode = False

Set DataRange = SourceWS.Range("O2:BB" & LastRow)
DataRange.ClearContents

DestWS.Activate
Dim x As Long, LastCol As Long
LastCol = SourceWS.Range("A1").CurrentRegion.Rows.Count
For x = 2 To LastCol
Range(Cells(15, x), Cells(54, x)).Sort Key1:=Cells(15, x), Order1:=xlAscending, Header:=xlGuess
Next x

DestWS.Range(Cells(15, 2), Cells(54, LastCol)).Copy

SourceWS.Range("O2").PasteSpecial xlPasteValues, lPasteSpecialOperationNone, True, True
Application.CutCopyMode = False

DestWS.Visible = xlSheetHidden

SourceWS.Activate
SourceWS.Range("A1").Select

Set SourceWS = Nothing
Set DestWS = Nothing
Set TblRange = Nothing
Set DataRange = Nothing

Application.ScreenUpdating = True

End Sub

A: I was confronted by the same problem. Use the following recipe:

*

*CTRL+A  // Select entire table.

*CTRL+H  // Replace all equal signs with | or character of your choice.

*ALT+J+G // Convert to range.

*ALT+H+S+U+O+L // Special Sort from left-to-right. Choose sorting row.

*CTRL+T  // Convert back to Table. Remember to rename it!

*CTRL+H  // Put back all your equal signs.

You're done. Caveat: if you have any array formulas, you'll have to recommit them with CTRL+SHIFT+ENTER


text:
Q: apache + wsgi + django : Client denied by server configuration I'm getting a 403 error with my django project.
The only line I get in my error log is :
AH01630: client denied by server configuration: /srv/http/www/src/myproject/preprod_wsgi.py

The permissions for this file are :
-rwxr-xr-x 1 root root  552 Jul 30 04:24 preprod_wsgi.py

And the apache (VERSION : 2.4) conf file contains (amongst other things) :
LoadModule wsgi_module modules/mod_wsgi.so

<IfModule unixd_module>
    User http
    Group http
</IfModule>

<Directory />
    AllowOverride none
    Require all denied
</Directory>

#
# Others
#

Alias /robots.txt /srv/http/www/htdocs/static/robots.txt
Alias /favicon.ico /srv/http/www/htdocs/static/favicon.ico

Alias /media/ /srv/http/www/htdocs/media/
Alias /static/ /srv/http/www/htdocs/static/

<Directory "/srv/http/www/htdocs/static">
           Require all granted
</Directory>

<Directory "/srv/http/www/htdocs/media">
           Require all granted
</Directory>

<Files "/srv/http/www/src/myproject/preprod_wsgi.py">
       Require all granted
</Files>

#
# WSGI
#

WSGIDaemonProcess myproject python-path=/srv/http/www/src
WSGIScriptAlias / /srv/http/www/src/myproject/preprod_wsgi.py
WSGIPythonPath /srv/http/www/src

DocumentRoot "/srv/http/www/htdocs"
<Directory "/srv/http/www/htdocs">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

ErrorLog "/srv/http/www/logs/error_log"
CustomLog "/srv/http/www/logs/access_log" common

LogLevel warn

Here is also the content of my preprod_wsgi.py file :
"""
WSGI config for soisbault project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os, sys

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.preprod_settings")

application = get_wsgi_application()

ALLOWED_HOSTS is also set in my preprod_settings.py.
I tried to add access to this file with <Files> directive, and did a chmod 755 on it. But I can't figure out what I could do more.
How could I fix this? Feel free to ask more details if necessary.
Thank you in advance.

A: It seems it was the <File> directive in apache that can't be used outside of a <Directory> directive.
<Files "/srv/http/www/src/myproject/preprod_wsgi.py">
       Require all granted
</Files>

I changed this to
<Directory "/srv/http/www/src/myproject">
       <Files "preprod_wsgi.py">
              Require all granted
       </Files>
</Directory>

And it worked. :)


text:
Q: How can I create a custom page for this error? How can I create a custom page for this too many connections error page because I know it's because my server is overloaded? I wanted to show a custom error page instead of this when my website is overloaded by traffic.

A: Check out the source of dead_db() which powers the message.
You'll see that you can create a file db-error.php in your WP content directory (which by default is /wp-content/) and it'll load that instead!


text:
Q: How does OpenMPI Secure SHell into all the compute nodes from the master node? First time working with OpenMPI. I am curious how the API invokes a run-time environment to run on compute nodes. I am thinking about setting up a Linux cluster of 4 or 5 nodes. I read a lot of the documentation on creating password-less ssh access for the master node. Does OpenMPI invoke a command line argument to ssh into whatever compute nodes are declared inside the --hostfile and then begin spreading tasks?

A: Open MPI does not add any additional arguments (by default) when ssh'ing to a remote machine.  You should just setup your ssh keys to allow password-less logins (and if you're using an ssh passphrase, set it up so that the passphrase propagates around without manual keyboard entry).
You might also want to read these two blog entries:
http://blogs.cisco.com/performance/tree-based-launch-in-open-mpi
http://blogs.cisco.com/performance/tree-based-launch-in-open-mpi-part-2


text:
Q: How do i move my Minecraft profile to a device with no internet capability? I'm copying Minecraft over to my other computer (Which for rather inconvenient reasons, is incapable of establishing an internet connection). But after copying it onto the machine from a flash drive, I'd accidentallly logged out from the launcher. Is there some sort of file i could copy over from my internet-capable machine to essentially log me back in?

A: You will need to log in on the other computer. Consider buying a small USB wifi adapter and connecting to a network or setup a hotspot on your phone and connect to it.


text:
Q: Combine two names() of lists in R I am trying to append extra dataframes to a list of dataframes and also update the names() of the lists:
DE_list = list(imagetag_age_backup, imagetag_emotion_backup, imagetag_facial_backup, imagetag_gender_backup)
names(DE_list) = c("imagetag_age_backup", "imagetag_emotion_backup", "imagetag_facial_backup", "imagetag_gender_backup")

names(df_list) <- append(names(df_list), names(DE_list))
df_list <- append(df_list, DE_list)

However I get this  error:
Error in names(df_list) <- c(names(df_list), names(DE_list)) :
  'names' attribute [30] must be the same length as the vector [26]

Does anyone know a workaround for this? Thanks!


text:
Q: Prisma: getting "com.prisma.deploy.schema.InvalidProjectId: No service with name 'default' and stage 'default' found" error I'm getting errors related to name 'default' and stage 'default' when initializing new prisma project
Steps to reproduce:

*

*Follow all the steps from official guide strictly

*Get com.prisma.deploy.schema.InvalidProjectId: No service with name 'default' and stage 'default' found error when run prisma deploy

*Get this error when performing a simple query from http://localhost:4466/graphql:

*

*Query:

query {
  user {
    id
    name
  }
}

*

*Response:

{
  "errors": [
    {
      "message": "Project not found: 'graphql_default'",
      "code": 3016,
      "requestId": "local:cjzs556h5000f0754vc6k36qd"
    }
  ]
}

Versions:

*

*Connector: MongoDB

*Prisma Server: 1.34.6

*prisma CLI: prisma/1.34.6 (darwin-x64) node-v10.16.3

*OS: OS X Mojave - 10.14.6
Logs from Docker:
$ docker logs hello-world_prisma_1
No log level set, defaulting to INFO.
[INFO] Cluster created with settings {hosts=[mongo:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
[INFO] Exception in monitor thread while connecting to server mongo:27017
Exception opening socket
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.AsynchronousSocketChannelStream$OpenCompletionHandler.failed(AsynchronousSocketChannelStream.java:272)
    at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:128)
    at sun.nio.ch.Invoker$2.run(Invoker.java:218)
    at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.UnixAsynchronousSocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.UnixAsynchronousSocketChannelImpl.finishConnect(UnixAsynchronousSocketChannelImpl.java:252)
    at sun.nio.ch.UnixAsynchronousSocketChannelImpl.finish(UnixAsynchronousSocketChannelImpl.java:198)
    at sun.nio.ch.UnixAsynchronousSocketChannelImpl.onEvent(UnixAsynchronousSocketChannelImpl.java:213)
    at sun.nio.ch.EPollPort$EventHandlerTask.run(EPollPort.java:293)
    ... 1 more
[INFO] Initializing workers...
[INFO] Obtaining exclusive agent lock...
[INFO] Obtaining exclusive agent lock... Successful.
[INFO] Successfully started 1 workers.
[INFO] No server chosen by com.mongodb.async.client.ClientSessionHelper$1@70a6c292 from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=mongo:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}]}. Waiting for 30000 ms before timing out
[INFO] Opened connection [connectionId{localValue:2, serverValue:1}] to mongo:27017
[INFO] Monitor thread successfully connected to server with description ServerDescription{address=mongo:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 13]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=16638401}
Server running on :4466
[INFO] Opened connection [connectionId{localValue:3, serverValue:2}] to mongo:27017
[INFO] Deployment worker initialization complete.
[Warning] Management authentication is disabled. Enable it in your Prisma config to secure your server.
{"key":"error/handled","requestId":"local:cjzs54qg500020754mbbzqni9","payload":{"exception":"com.prisma.deploy.schema.InvalidProjectId: No service with name 'default' and stage 'default' found","query":"\n      query($name: String! $stage: String!) {\n        project(name: $name stage: $stage) {\n          name\n          stage\n        }\n      }\n    ","variables":"{\"name\":\"default\",\"stage\":\"default\"}","code":"4000","stack_trace":"com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$3(SchemaBuilder.scala:144)\\n scala.Option.getOrElse(Option.scala:121)\\n com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$2(SchemaBuilder.scala:144)\\n scala.util.Success.$anonfun$map$1(Try.scala:251)\\n scala.util.Success.map(Try.scala:209)\\n scala.concurrent.Future.$anonfun$map$1(Future.scala:288)\\n scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)\\n scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)\\n scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)\\n akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)\\n akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:91)\\n scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)\\n scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)\\n akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:91)\\n akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)\\n akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:44)\\n akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\\n akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)\\n akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)\\n akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)","message":"No service with name 'default' and stage 'default' found"}}
[Debug] Initializing deployment worker for default_default
[Debug] Scheduling deployment for project default_default
[INFO] Opened connection [connectionId{localValue:4, serverValue:3}] to mongo:27017
[Debug] Applied migration for project default_default

Formatted [Warning]:
{
  "key": "error/handled",
  "requestId": "local:cjzs54qg500020754mbbzqni9",
  "payload": {
    "exception": "com.prisma.deploy.schema.InvalidProjectId: No service with name 'default' and stage 'default' found",
    "query": "\n      query($name: String! $stage: String!) {\n        project(name: $name stage: $stage) {\n          name\n          stage\n        }\n      }\n    ",
    "variables": "{\"name\":\"default\",\"stage\":\"default\"}",
    "code": "4000",
    "stack_trace": "com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$3(SchemaBuilder.scala:144)\\n scala.Option.getOrElse(Option.scala:121)\\n com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$2(SchemaBuilder.scala:144)\\n scala.util.Success.$anonfun$map$1(Try.scala:251)\\n scala.util.Success.map(Try.scala:209)\\n scala.concurrent.Future.$anonfun$map$1(Future.scala:288)\\n scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)\\n scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)\\n scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)\\n akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)\\n akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:91)\\n scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)\\n scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)\\n akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:91)\\n akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)\\n akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:44)\\n akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\\n akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)\\n akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)\\n akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)",
    "message": "No service with name 'default' and stage 'default' found"
  }
}

Formatted "query":
query($name: String! $stage: String!) {
  project(name: $name stage: $stage) {
    name
    stage
  }
}

Formatted "variables":
{ "name":"default", "stage":"default" }

Formatted stack trace:
com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$3(SchemaBuilder.scala:144)
 scala.Option.getOrElse(Option.scala:121)
 com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$2(SchemaBuilder.scala:144)
 scala.util.Success.$anonfun$map$1(Try.scala:251)
 scala.util.Success.map(Try.scala:209)
 scala.concurrent.Future.$anonfun$map$1(Future.scala:288)
 scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
 scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
 scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
 akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
 akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:91)
 scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
 scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)
 akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:91)
 akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)
 akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:44)
 akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
 akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
 akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
 akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

P/s: It actually was running flawlessly some days before, but today I can't manage to make it work again!


text: Q: Keeping git objects to depth n from branch heads When cloning a repo, you can use --depth=n option to only download the objects up to the specified depth from head of each branch. Is it possible to trim an existing clone to a maximum specified depth?


text:
Q: Terraform predefined variable for the currently executing command type Terraform has some built-in predefined variables for things like path.module (the filesystem path of the module where the expression is placed) and terraform.workspace (the name of the currently selected workspace).
Is there a variable to get the currently executing command? (i.e. 'plan', 'apply', 'import', etc.)


text:
Q: cxf upgrade throw NoSuchFieldError: REFLECTION I want to upgrade my Spring from 2.5.6 to 4.X , then I have to upgrade my cxf also.
after I upgraded them together , I have this problem
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [applicationContext.xml]; nested exception is java.lang.NoSuchFieldError: REFLECTION
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:414)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:434)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at com.caucho.server.webapp.WebApp.start(WebApp.java:1866)
at com.caucho.server.deploy.DeployController.startImpl(DeployController.java:667)
at com.caucho.server.deploy.StartAutoRedeployManualStrategy.startOnInit(StartAutoRedeployManualStrategy.java:74)
at com.caucho.server.deploy.DeployController.startOnInit(DeployController.java:549)
at com.caucho.server.deploy.DeployContainer.start(DeployContainer.java:160)
at com.caucho.server.webapp.WebAppContainer.start(WebAppContainer.java:659)
at com.caucho.server.host.Host.start(Host.java:450)
at com.caucho.server.deploy.DeployController.startImpl(DeployController.java:667)
at com.caucho.server.deploy.StartAutoRedeployAutoStrategy.startOnInit(StartAutoRedeployAutoStrategy.java:72)
at com.caucho.server.deploy.DeployController.startOnInit(DeployController.java:549)
at com.caucho.server.deploy.DeployContainer.start(DeployContainer.java:160)
at com.caucho.server.host.HostContainer.start(HostContainer.java:484)
at com.caucho.server.cluster.Server.start(Server.java:1319)
at com.caucho.server.cluster.Cluster.startServer(Cluster.java:710)
at com.caucho.server.cluster.ClusterServer.startServer(ClusterServer.java:542)
at com.caucho.server.resin.Resin.start(Resin.java:703)
at com.caucho.server.resin.Resin.initMain(Resin.java:1162)
at com.caucho.server.resin.Resin.main(Resin.java:1365)
Caused by: java.lang.NoSuchFieldError: REFLECTION
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.<init>(RuntimeModelBuilder.java:49)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:372)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:236)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:76)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at org.apache.cxf.common.jaxb.JAXBContextCache$2.run(JAXBContextCache.java:347)
at org.apache.cxf.common.jaxb.JAXBContextCache$2.run(JAXBContextCache.java:345)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.cxf.common.jaxb.JAXBContextCache.createContext(JAXBContextCache.java:345)
at org.apache.cxf.common.jaxb.JAXBContextCache.getCachedContextAndSchemas(JAXBContextCache.java:246)
at org.apache.cxf.configuration.spring.AbstractBeanDefinitionParser.getContext(AbstractBeanDefinitionParser.java:322)
at org.apache.cxf.configuration.spring.AbstractBeanDefinitionParser.mapElementToJaxbProperty(AbstractBeanDefinitionParser.java:349)
at org.apache.cxf.configuration.spring.AbstractBeanDefinitionParser.mapElementToJaxbProperty(AbstractBeanDefinitionParser.java:295)
at org.apache.cxf.transport.http.spring.HttpConduitBeanDefinitionParser.doParse(HttpConduitBeanDefinitionParser.java:58)
at org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser.parseInternal(AbstractSingleBeanDefinitionParser.java:85)
at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse(AbstractBeanDefinitionParser.java:61)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:74)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1427)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1417)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:174)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:144)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:100)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:510)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)

my maven dependenties are as follows
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.0.6</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>3.0.6</version>
</dependency>

I don't know whether I need other cxf dependeny or other causes this problem
my applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<description>Spring公共配置文件</description>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:config.properties</value>
            <value>classpath:common.properties</value>
        </list>
    </property>
</bean>
<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreResourceNotFound" value="false" />
    <property name="properties" ref="configProperties" />
</bean>

<http-conf:conduit name="http://risk.epay.163.com/.*">
    <http-conf:client ConnectionTimeout="3000" ReceiveTimeout="6000" AllowChunking="false"/>
</http-conf:conduit>
<http-conf:conduit name="*.http-conduit">
    <http-conf:client ConnectionTimeout="3000" ReceiveTimeout="6000"/>
</http-conf:conduit>

<!-- Web Service Setting start -->
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

<jaxws:client id="blackAccountService"
    address="${XX}"
    serviceClass="XXXX" >
</jaxws:client>

<jaxws:server id="XXXX" serviceClass="XXXX
    address="XX" endpointName="XX" >
    <jaxws:serviceBean>
        <bean class="XXXX"></bean>
    </jaxws:serviceBean>
</jaxws:server>

<!-- annotation way configuration -->
<context:component-scan base-package="XX" />
<bean id="propertiesInjector" class="XX"></bean>

<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"
    destroy-method="close">
    <property name="driver">
        <value>${jdbc-1.proxool.driver-class}</value>
    </property>
    <property name="driverUrl">
        <value>${jdbc-1.proxool.driver-url}</value>
    </property>
    <property name="user">
        <value>${jdbc-1.user}</value>
    </property>
    <property name="password">
        <value>${jdbc-1.password}</value>
    </property>
    <property name="alias">
        <value>${jdbc-1.proxool.alias}</value>
    </property>
    <property name="prototypeCount">
        <value>${jdbc-1.proxool.prototype-count}</value>
    </property>
    <property name="maximumConnectionCount">
        <value>${jdbc-1.proxool.maximum-connection-count}</value>
    </property>
    <property name="minimumConnectionCount">
        <value>${jdbc-1.proxool.minimum-connection-count}</value>
    </property>
    <property name="maximumActiveTime">
        <value>${jdbc-1.proxool.maximum-active-time}</value>
    </property>
    <property name="simultaneousBuildThrottle">
        <value>${jdbc-1.proxool.simultaneous-build-throttle}</value>
    </property>
    <!--
    <property name="trace">
        <value>${jdbc-1.proxool.trace}</value>
    </property>
    -->
    <property name="verbose">
        <value>${jdbc-1.proxool.verbose}</value>
    </property>
    <property name="statistics">
        <value>${jdbc-1.proxool.statistics}</value>
    </property>
    <property name="houseKeepingTestSql">
        <value>${jdbc-1.proxool.house-keeping-test-sql}</value>
    </property>

</bean>

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />

<!-- SpringContextHolder定义 -->
<bean class="com.netease.epay.common.module.spring.SpringContextHolder" lazy-init="false" />

<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
    <property name="configLocations">
       <list>
            <value>classpath:SqlMapConfig.xml</value>
            <value>classpath:epay/common/SqlMapConfig.xml</value>
            <value>classpath:epay/platform/SqlMapConfig.xml</value>
            <value>classpath:epay/account/SqlMapConfig.xml</value>
            <value>classpath:epay/trade/SqlMapConfig.xml</value>
            <value>classpath:epay/core/SqlMapConfig.xml</value>
       </list>
    </property>
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="sqlExecutor" class="com.netease.epay.common.module.orm.ibatis.LimitSqlExecutor">
    <property name="dialect">
        <bean class="com.netease.epay.common.module.orm.ibatis.dialect.OracleDialect" />
    </property>
</bean>

<bean id="threadPool" class="com.netease.epay.common.module.pool.ThreadPool">
    <property name="poolSize" value="${threadpool.size}"/>
</bean>

<bean id="springContextHolder" class="com.netease.epay.common.module.spring.SpringContextHolder">
</bean>

<bean id="transactionMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host">
        <value>tmfast.mail.163.com</value>
    </property>
    <property name="port" value="25"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">false</prop>
            <prop key="mail.smtp.timeout">25000</prop>
        </props>
    </property>
    <property name="username" value="kefu-epay@service.netease.com"/>
</bean>
<bean id="subcribeMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host">
        <value>cmfast.mail.163.com</value>
    </property>
    <property name="port" value="25"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">false</prop>
            <prop key="mail.smtp.timeout">25000</prop>
        </props>
    </property>
    <property name="username" value="kefu-epay@service.netease.com"/>
</bean>
<bean id="uploadFileTransferReceipt" class="com.netease.yfb.ctrol.viewctrl.upload.uploadsubclass.UploadFileTransferReceipt">
    <property name="remoteDir" value="/transferReceipt" />
    <property name="visitDir" value="/wyb/transferReceipt" />
    <property name="maxUploadSize" value="1572864" />
</bean>
<bean id="ftpBusinessTechWyb" class="com.netease.yfb.business.common.FtpBusinessTechWyb" scope="prototype">
    <property name="HOST" value="upload.ms.netease.com" />
    <property name="PORT" value="21" />
    <property name="USERNAME" value="tech_wyb" />
    <property name="PASSWORD" value="ea5eiUUIO@#ALcajr" />
</bean>

<bean id="monitor" class="com.netease.om.Monitor"
    factory-method="getInstance" init-method="init">
    <constructor-arg>
        <value>epay</value>
    </constructor-arg>
    <property name="xmppAddress">
         <value>${epay.monitor.xmpp.address}</value>
     </property>
     <property name="xmppPort">
         <value>${epay.monitor.xmpp.port}</value>
     </property>
</bean>

<import resource="spring/limit-bean.xml" />
<import resource="spring/schedule.xml" />

<bean id="ftpUtil" class="com.netease.epay.module.common.utils.FtpUtil">
    <constructor-arg index="0">
        <value>${epay.ftp.address}</value>
    </constructor-arg>
    <constructor-arg index="1">
        <value>${epay.ftp.port}</value>
    </constructor-arg>
    <constructor-arg index="2">
        <value>${epay.ftp.username}</value>
    </constructor-arg>
    <constructor-arg index="3">
        <value>${epay.ftp.password}</value>
    </constructor-arg>
</bean>

<bean id="nosClient" class="com.netease.cloud.services.nos.NosClient">
    <constructor-arg index="0">
        <bean class="com.netease.cloud.auth.BasicCredentials">
             <constructor-arg index="0" ><value>${nos.accessKey}</value></constructor-arg>
             <constructor-arg index="1" ><value>${nos.secretKey}</value></constructor-arg>
        </bean>
    </constructor-arg>
</bean>

<import resource="rpc_dubbo.xml"/>
<bean id="refreshClientCacheProxy" class="XXX" init-method="init">
    <property name="refUpdateTimeQueryService" ref="refUpdateTimeQueryService"/>
    <property name="payWholeCacheService" ref="payWholeCacheService"/>
    <property name="cacheCleanTimerInterval" value="${gate.local.cache.check.time}"/>
</bean>

In order to be compatible with ibatis , I imported Spring-orm 3.2.8

A: I have found the reason , I would have had an com.sun.xml.bind:jaxb-impl 2.0.5 then cxf-rt-frontend-jaxws provided a com.sun.xml.bind:jaxb-impl 2.2.11.And there is a conflict between them. After I removed the vesion 2.0.5 ,It works well


text:
Q: what difference does it make to append stylesheets or js files on different order? how to use append and prepend stylesheet or append and prependfile? What difference does it make if I write:
$this->headScript()->prependFile( PUBLIC_PATH."/js/frontend/fb.js" );

And then this:
$this->headScript()->appendFile( PUBLIC_PATH."/js/jQuery.bPopup.js" );

A: CSS means Cascading style sheets. That means the style sheet at the bottom will have precedence than sheets above it (unless you use !important parameter) in case of conflict. Thus Appending will have precedence above pre-pending in case of conflict.
I don't know in the context of Zend framework but generally it works this way.

A: prependFile() method adds the top of the list, and appendFile() method adds at the end of the list.
It is better to use prependFile for libraries like jQuery and appendFile for scripts that need these libraries


text:
Q: NodeJS rmdir function error on LINUX ONLY? So I'm running this section of my NodeJS script on my Windows 10 device running the latest version of Node and another version on my webserver running CentOS8 Linux. When this code is run on windows, it outputs what I would expect but when I run it on my Linux machine, it errors on this line:
fs.rmdir('public/u/' + info[0] + '/', { recursive: true }, (err) => {

With this error:
fs.js:136
    throw new ERR_INVALID_CALLBACK();
    ^

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
    at makeCallback (fs.js:136:11)
    at Object.rmdir (fs.js:671:14)
    at /home/frontlinemist57server/celeste.js:156:8
    at /home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:279:15
    at getLine (/home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:166:7)
    at Object.nextLine (/home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:183:7)
    at Immediate.readNext (/home/frontlinemist57server/node_modules/line-reader/lib/line_reader.js:269:14)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)

Any ideas?
app.post('/api/purge', (req, res) => {
    // Get Sent Token //
    var giventoken = req.body.token;
    var authed = false;

    lineReader.eachLine('accounts.txt', function(line, last) {
        // If Valid Token //
        if (crypto.createHash('md5').update(line).digest("hex") == giventoken) {
            authed = true;
            var info = line.split("§");
            if (fs.existsSync('public/u/' + info[0] + '/')){
                fs.rmdir('public/u/' + info[0] + '/', { recursive: true }, (err) => {
                        if (err) {
                            res.send(err);
                            throw err;
                        } else {
                            console.log("Account Purged: " + info[0]);
                            res.send('purged');
                        }
                    }
            )}

        // If Invalid Token //
        } else if (last) {
            if (authed == false) {
                console.log("Invalid Purge Token: " + giventoken);
                res.write("invalid");
                res.end();
            }
        }
    });
});

Edit: Both Windows and Linux systems are running the same version of node.

A: It turns out that DNF doesn't actually update you to the latest version of node for some reason. The server was still running an out of date version of node.
This is how I fixed it:
sudo dnf rm nodejs
curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash -
sudo dnf install nodejs


text:
Q: Code to count 1st, 2nd and first-two digits from a text file I have been struggling to find a code that will give me the sum of the first digit for all (1,2,3,...,9) numbers individually from a text file. I also want to adapt/modify that code for the second and two-first digits. Is anyone able to help? What I have done so far is:
For the first digit:
        fgrep -oE "[[:digit:]]{1,}" 'filename' | grep "^1"| wc -l
For the second digit:
        fgrep -oE "[[:digit:]]{2,}" 'filename' | grep "^1"| wc -l
In order to get it for the other digits (2,3,....,9) I modify "^1" to e.g. "^2" and so on....
I am pretty sure the results I get for the second digit formula are definitely wrong....
I need urgend help, thanks! :)

A: Generally speaking, you can easily do something like this...
import re

def sum_nums_in_text_by_indices(text, indices=slice(0,1)):
    return sum(int(n[indices]) for n in re.findall('\d+', text))

Examples:
>>> sum_nums_in_text_by_indices('123 123')              # first digits
2

>>> sum_nums_in_text_by_indices('123 123', slice(1,2))  # second digits
4

>>> sum_nums_in_text_by_indices('123 123', slice(0,2))  # first and second digits
24

In order to use this properly, you should familiarize yourself with Pythons Slice Notation. (documentation: slice())
The function can be further simplified:
def sum_nums_in_text_by_indices(text, start=0, stop=1):
    return sum(int(n[start:stop]) for n in re.findall('\d+', text))

>>> sum_nums_in_text_by_indices('123 123')
2

>>> sum_nums_in_text_by_indices('123 123', start=1, stop=2)
4

>>> sum_nums_in_text_by_indices('123 123', start=0, stop=2)
24

A: I'll just guess what you want.
Sample input file. (filepath: /tmp/ggz)
240872014
3406121147
131
115388201300032
13022020149210000854942
124342014
1148272013102002
11975281552961075898430474
240872014
118113201520150113164711178

Count the occurrence of digits in the first place of every line.
$ grep -oP "^[0-9]" /tmp/ggz | sort | uniq -c
  7 1       # Digit `1` has 7 occurrences.
  2 2       # Digit `2` has 2 occurrences.
  1 3       # Digit `3` has 1 occurrences.
            # No occurrences for digit `4` ~ `9` and `0`

Count the occurrence of numbers in the first-two place of every line.
$ grep -oP "^[0-9]{2}" /tmp/ggz | sort | uniq -c
  4 11      # Number `11` has 4 occurrences.
  1 12
  2 13
  2 24
  1 34

Count the occurrence of numbers in the second place of every line.
$ grep -oP "(?<=^.)[0-9]" /tmp/ggz | sort | uniq -c
  4 1       # Digit `1` has 4 occurrences.
  1 2
  2 3
  3 4


text: Q: Environment variables accessible to jvm run from root I have a java application (run on Oracle Linux) that is run via an init script at boot as user root.  It would seem that the environment variables that are set are very basic.  They do not appear to be sourcing in the same environment variables that are brought in as the various system users, including root.  I am making a quick assumption that its because the java application is running Runtime.getRuntime().exec("command") is not in an interactive shell.  But even considering I may be correct, I have no idea how to get the java application to have access to the same environment variables the user has upon logon.


text:
Q: How do I set my page so that the Enter key event does not trigger postback? In one of my asp web pages there is a textbox, where I use jQuery to display content in textbox above it when user hit the Enter key. However, it always trigger postback, so the content will disappear immediately after displaying. How do I keep that postback from happening?

A: This should do it.
$('your selector').keyup(function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();
    }
});


text:
Q: Outliers treatment in nonlinear Least squares (scipy) for a 5PL curve I am currently in need of fitting a 5PL curve to some datapoints that I have. 5PL is an asymmetric logistic function often used in bioassays analysis. Its formula is as follow:
F(x) = D+(A-D)/((1+(x/C)^B)^E)
I was able to obtain a fit using scipy in python (duh).
In a first time I use knowledge on my data to determine the starting parameters for the function: -
A is the lower asymptote so guess it with min(y)
B is the Hills slope so guess it with the slope of the line between first and last point.
C is the inflection point (the concentration of analyte where you have
 half of the max response) so guess it finding the concentration whose
response is nearest to the mid response.
D is the upper asymptote so guess it with max(y)
E is the asymmetric factor and so guess it with no asymmetry (E=1) for starters.

With this I then use res = least_squares(residuals, p0,bounds=bnd args=(x, y)) where residuals is the function that computes the residuals between my data and the 5PL function, p0 contains my initial parameters, bnd the bounds of the problem and args= are the arguments passed to residuals (my data).
Now the result is acceptable but I suspect my measurements to have strong outliers and I would like to get a more robust outcome. I found that you can do that by adding a loss function and modify the nonlin LS (as explained here.
The line for solving this problem becomes res_loss = least_squares(residuals, p0, bounds=bnd,loss='soft_l1', f_scale=1000, args=(x, y)) where loss='soft_l1' determines the type of loss function I use and f_scale the threshold between inliners and outliers.
Now in every example that I could find, people just generate data using the curve that they whant to fit and add noise to that signal. They can then set f_scale value equal to the noise they introduced.
That is nice and all but how should f_scale be chosen if there is no knowledge on what are the values for outliers? Is there a way to automatically determine that for every dataset using the data spread?
If my problem was linear I would just use the SD of the data at each X to create a weight matrix and solve a weighted least squares. Is there a similar method for nonlinear problems?
Thanks in advance


text:
Q: custom post type "single" don't show my code in wordpress i am trying to show my code inside a costume post type "single" using :
<?php if ( post_type_exists( 'portfolio' ) ) {
   echo 'the Book post type exists'; } ?>

it shows the ECHO inside the category 'portfolio'.
but i want to show my code inside the "single" that is under portfolio cat (a costume post type)
i have tryed using this aswell:
if ( is_singular()

but nothing works

A: is_singular accept an argument that is the post_type. And is_object_in_term is a conditional function which checks if given object (post) is within the taxonomy term (category, tag). So the code -
add_filter( 'the_content', 'wpse_the_content' );
function wpse_the_content( $content )
{
    if( is_singular('portfolio') )
    {
        $content .= '
the Book post type exists
';
    }
    return $content;
}

Your custom post type portfolio should already be registered with taxonomy - category. Or if it's a custom taxonomy, replace the second argument on is_object_in_term function to that.


text:
Q: Dealing with added and deleted files in a git merge In my repository I have two branches: master and dev. There has been a lot of activity on the dev branch and I need to merge it back into master, but I'm having trouble finding the right way to do it.
If I do a straightforward git merge dev then it creates conflicts in files that have only changed in the dev branch. Worse, if I open those files in the merge tool then the 'merged' version has the contents from the master branch.
git merge dev -X theirs gets closer and those files are now correctly merged. The remaining problem I've got is it's not properly handling files which have been added and deleted in the branch. For files which have been added in the branch I get this conflict:

CONFLICT (modify/delete): my_added_file deleted in HEAD and modified
  in dev. Version dev of my_added_file left in tree.

This is not really an issue as I can just resolve it as 'modify', which takes the branch version. The problem is with files that have been deleted in the branch are not being deleted in the merge. What am I missing?

Update: Ok well I can see why git is confused. Somehow a random commit in master has been parented to a completely unrelated commit in dev. How do I fix this??
The blue line is dev and the purple line is master.

A: There's probably a better way to have done this, but here's what I ultimately ended up doing. The repository is hosted on Bitbucket, which made things a bit more challenging as I had to rewrite the history.

*

*Rewrite the branch to remove the offending parent: git filter-branch --parent-filter "sed 's/-p 12eed45e184246c0553e410734f83d226bf9bd4f//'" master

*Rename the master branch to master_new

*Push master_new to Bitbucket

*Set the main branch on Bitbucket to master_new

*Delete master on Bitbucket

*Delete origin/master locally

*Rename master_new to master locally

*Push master to Bitbucket

*Set the main branch on Bitbucket to master

*Delete master_new on Bitbucket

*Get everyone else to do a fresh checkout

After this I was able to complete the merge normally.


text:
Q: What was the point of bringing Ziesha from the future? Once the time machine was completed, Karan expressed a desire to go back in time and rescue his fiance, Sana. Instead, they travel forward in time, and instead meet Ziesha.

 Eventually, we find out that Zeisha is Sana reincarnated, and eventually chooses to return to Karan's time with him.

Why didn't Dr. Khanna help Karan by going backward in time? Why go through all the trouble of going to the future

 which only worked out because they happened to find Zeisha and restore her memories?


text:
Q: Passing value to Constructor by using new Statement public class MultipleObjects {
    int a;
    int b;

    MultipleObjects(int a,int b) {
        this.a=a;
        this.b=b;
    }

    MultipleObjects(MultipleObjects g) {
        a=g.a;
        b=g.b;
    }

    static MultipleObjects display(/*MultipleObjects o1,MultipleObjects o2*/) {
        MultipleObjects temp = new MultipleObjects(new MultipleObjects(2,3));
        return temp;
    }
}

I used 2 new statements one within the other here.What ıs thing in the brackets of outer new statement? value or object.If object,how? Can someone explain it detailedly?

A: First you created a new MultipleObjects using constructor that takes int, int as params then you invoke another constructor(AKA copy constructor) passing it the newly created object.
Your code
MultipleObjects temp = new MultipleObjects(new MultipleObjects(2,3));

Is equivalent to
MultipleObjects foo = new MultipleObjects(2,3);
MultipleObjects temp = new MultipleObjects(foo);


text:
Q: Issue with many to many relationship using code first mvc I created two models of Class and Teacher, I want to configure many to many relationship using code first approach with two models.
When I add information into class and teacher tables, value not insert into TeacherClasses Table using many to many relationship Entity Framework code first approach.
Here code of models and controller below.
This is Class Model
public class Class
{
    [Key]
    public int ClassId { get; set; }

    [Required]
    public string ClassName { get; set; }

    public virtual ICollection<Teacher> Teachers { get; set; }

}

This is Teacher Model
public class Teacher
{
 [Key]
    public int TeacherId { get; set; }

    [Required]
    public string TeacherName { get; set; }

    [DataType(DataType.Date)]
    public DateTime JoiningDate { get; set; }
    public decimal Salary { get; set; }
    public string Email { get; set; }

    public virtual ICollection<Class> Classes { get; set; }

    [NotMapped]
    public virtual Class Class { get; set; }
    [NotMapped]
    public virtual ICollection<int> SelectedClassList { get; set; }

}

This is Teacher Controller
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "TeacherId,TeacherName,JoiningDate,Salary,Email,Classes,Class,SelectedClassList")] Teacher teacher)
    {
        if (ModelState.IsValid)
        {
            db.Teachers.Add(teacher);
            db.SaveChanges();

            teacher.Classes = new Collection<Class>();

            foreach (var classId in teacher.SelectedClassList)
            {
                teacher.Classes.Add(new Class {ClassId = classId });
            }

            return RedirectToAction("Index");
        }
        return View(teacher);
    }

this is image of database tables
in database class, teacher and teacherclasses tables shown
database
This is View of Teacher

    @Html.Label("Class List", htmlAttributes: new { @class = "control-label col-md-2" })

        @*@Html.ListBox("SelectedClassList", ViewData["ClassList"] as MultiSelectList)
        @Html.ValidationMessageFor(model => model.Classes, "", new { @class = "text-danger" })*@
        @Html.ListBoxFor(model => model.SelectedClassList, new MultiSelectList(ViewBag.ClassList, "value", "text"), new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.SelectedClassList, "", new { @class = "text-danger" })

A: From your description and the way you're saving the data there seem to be two possible scenarios you're trying to achieve:

*

*Insert new teachers and connect them to existing classes.

*Connect existing teachers to existing classes.

Whichever it is, the rule is always:

*

*First attach existing entities to the context

*Then add new entities

So for the first scenario that would be:
foreach (var classId in teacher.SelectedClassList)
{
    var class = new Class { ClassId = classId }; // "stub" entity
    db.Classes.Attach(class);
    teacher.Classes.Add(class); // Assuming that teacher.Classes isn't null
}
db.Teachers.Add(teacher); // <= Add
db.SaveChanges();

And the second scenario:
db.Teachers.Attach(teacher); // <= Attach
foreach (var classId in teacher.SelectedClassList)
{
    var class = new Class { ClassId = classId }; // "stub" entity
    db.Classes.Attach(class);
    teacher.Classes.Add(class); // Assuming that teacher.Classes isn't null
}
db.SaveChanges();

As you see, you never need to pull existing entities from the database. For creating associations all EF needs tho know is the ID values of the entities at both ends, so working with stub entities is the ideal approach here.
In the first scenario, if you don't attach the classes before adding the teacher, the classes will be marked as Added too, and you'll insert empty class records into the database (if they pass validation at all).


text:
Q: Pass python list from context to JS function I have a view that renders a dictionary of data for each country like below:
def InvoicingDashboardView(request):
    # For reference - "c" is the context dictionary, and it's already initialized by this point

    for client in Client.objects.all():
        fte = frame.fte(c['start_date'], c['end_date'], time = 'external', client = client.id)

        if fte > 0:
            c['countrys'][client] = {
                'name': client.name,
                'fte': fte,
                'var_fte': fte - frame.fte(c['var_start_date'], c['var_end_date'], client = client.id),
                'daily_ftes': [frame.fte(day, day) for day in c['label_days']],
            }

    return render(request, 'dashboards/invoicing.html', context = c)

As you can see, for example, if i call {{countrys.client.fte}} i'll get the fte for that client.
Everything good till now, but i'll need the daily_ftes for a JS function, like below:

    {% for country, items in countrys.items %}

        {% with name=items.name fte=items.fte variation=items.var_fte flag=country.flag.url %}
            {% include 'dashboards/charts/country_block.html' %}
        {% endwith %}

    {% endfor %}

The problem is that daily_ftes is a python list.
What can i do here in order to javascript read it as list instead of a string?


text:
Q: Check if List of Items exist in database and if not Add it to database i want to check if List of items exist in database but if particular item does exist i want to insert it in database. Here is what i done but this code is hitting my database many times. Is there any way to do the same task with 1 or 2 hits.
foreach(var item in itemsList)
{
   if(!context.table.Find(x=> x.itemId == item))
   {
       table t= new table()
       {
         field1= 0,
         field2= 0
       }
       context.table.Add(s);
       context.SaveChanges();
   }
}

A: First fetch all existed item Ids, then create object for all non-existed items.
This way you do what you want with 2 hits:
var existedIds = context.table.Where(p => itemsList.Contains(p.itemId))
    .Select(p => p.itemId).ToList();

var nonExistedItems = itemsList.Except(existedIds)
    .Select(id => new Table
    {
        Id = id,
        field1 = 0,
        field2 = 0
    });

context.table.AddRange(nonExistedItems);
context.SaveChanges();


text:
Q: implement an object that holds x seats in y rows What is the best way to implement an object that holds x rows with y seats? Would it be to use a dictionary object, such as
object={'row1:"2", "row2:"2","row3":"4"}

And then reference each row if I where to update number of seats?
Or are there any better way of implementing this?
/Andy.l

A: If all you're doing is tracking rows and seats, you could do it with a simple array:
rows = [2,2,4]

Row 1 is rows[0] with 2 seats, Row 3 is rows[2] with 4 seats, and so on.

A: Depending on the operations you need to perform on a row, you may find it better to create a Row class and put instances of that in the dictionary.
class Row(object):
  def __init__(self, num):
    self.maxseats = num
    self.currseats = num
  def reserve(self.num):
    self.currseats -= num
   ...

theatre = {'row1': Row(26), 'row2': Row(24), ...}


text:
Q: Getting 415 Unsupported media type when executing from address line in browser provifing JSON as parameter for route in .NET Core 3 I'm executing the URL

https://localhost:44310/api/Licensee/{"name":"stan"}

in address field of my browser, getting the error

"title": "Unsupported Media Type", "status": 415

which is described as

... the origin server is refusing to service the request because the payload
is in a format not supported by this method on the target resource.

The suggested troubleshot is

... due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data ...

I can't really control what header the browser provides. Due to intended usage, I can't rely on Postman or a web application. It needs to be exected from the URL line. The parameter will differ in structure, depending what search criteria that are applied.
The controller looks like this.
[HttpGet("{parameters}")]
public async Task<ActionResult> GetLicensee(LicenseeParameters parameters)
{
  return Ok(await Licensee.GetLicenseeByParameters(parameters));

}

I considered decorating the controller with [Consumes("application/json")] but found something dicouraging it. I tried to add JSON converter as suggested here and here but couldn't really work out what option to set, fumbling according to this, not sure if I'm barking up the right tree to begin with.
services.AddControllers()
  .AddJsonOptions(_ =>
  {
    _.JsonSerializerOptions.AllowTrailingCommas = true;
    _.JsonSerializerOptions.PropertyNamingPolicy = null;
    _.JsonSerializerOptions.DictionaryKeyPolicy = null;
    _.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
  });

My backup option is to use query string specifying the desired options for a particular search. However, I'd prefer to use the object with parameters for now.
How can I resolve this (or at least troubleshoot further)?

A:
The reason is that there might be a loooot of parameters and I don't want to refactor the controller's signature each time

*

*Actually, you don't have to change the controller's signature each time. ASP.NET Core Model binder is able to bind an object from query string automatically. For example, assume you have a simple controller:
[HttpGet("/api/licensee")]
public IActionResult GetLicensee([FromQuery]LicenseeParameters parameters)
{
    return Json(parameters);
}

The first time the DTO is:
public class LicenseeParameters
{
    public string Name {get;set;}
    public string Note {get;set;}
}

What you need is to send a HTTP Request as below:
GET /api/licensee?name=stan&note=it+works

And later you decide to change the LicenseeParameters:
public class LicenseeParameters
{
    public string Name {get;set;}
    public string Note {get;set;}

    public List<SubNode> Children{get;set;} // a complex array
}

You don't have to change the controller signature. Just send a payload in this way:
GET /api/licensee?name=stan&note=it+works&children[0].nodeName=it&children[1].nodeName=minus

The conversion is :  . represents property and [] represents collection or dictionary.

*In case you do want to send a json string within URL, what you need is to create a custom model binder.
internal class LicenseeParametersModelBinder : IModelBinder
{
    private readonly JsonSerializerOptions _jsonOpts;

    public LicenseeParametersModelBinder(IOptions<JsonSerializerOptions> jsonOpts)
    {
        this._jsonOpts = jsonOpts.Value;
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var name= bindingContext.FieldName;
        var type = bindingContext.ModelType;
        try{
            var json= bindingContext.ValueProvider.GetValue(name).FirstValue;
            var obj = JsonSerializer.Deserialize(json,type, _jsonOpts);
            bindingContext.Result = ModelBindingResult.Success(obj);
        }
        catch (JsonException ex){
            bindingContext.ModelState.AddModelError(name,$"{ex.Message}");
        }
        return Task.CompletedTask;
    }
}

and register the model binder as below:
[HttpGet("/api/licensee/{parameters}")]
public IActionResult GetLicensee2([ModelBinder(typeof(LicenseeParametersModelBinder))]LicenseeParameters parameters)
{
    return Json(parameters);
}

Finally, you can send a json within URL(suppose the property name is case insensive):
GET /api/licensee/{"name":"stan","note":"it works","children":[{"nodeName":"it"},{"nodeName":"minus"}]}

*The above two approaches both works for me. But personally I would suggest you use the the first one as it is a built-in feature.


text:
Q: ¿Cómo puedo enviar un parámetro desde mi GridView a mi función en javascript? Tengo un gridview el cual tiene una columna con un botón para editar, el problema que tengo es que necesito mandarle un id pero no tengo idea cómo hacerlo, les dejo aquí ambos códigos:
GridView:
Html.DevExpress().Button(b =>
            {
                b.Name = "Button" + c.KeyValue;
                b.Text = "EDITAR";
                //b.ClientSideEvents.Click = string.Format(@"function(s, e) {{ `alert({0}); }}", c.KeyValue);`
                b.ClientSideEvents.Click = "ejecutarFuncion";
            }).GetHtml();

Javascript:
function ejecutarFuncion(s, e) {
    if (s.CVE != null) {

        var url = "@Url.Action("editarRequisicion", "Home", new { CVE_DOC = "param-cve" })";
        url = url.replace("param-cve", encodeURIComponent(s.CVE));
        window.location.href = url;
    }
}

el id que tengo que mandar es el que dice c.keyvalue. El problema que tengo es que ya intenté mandarlo como "ejecutarFuncion(c.keyvalue)" y me dice que hubo un error, entonces no encuentro aún una forma de poder enviarlo. Espero me puedan ayudar a solucionarlo, gracias.


text:
Q: Can't handle with Handler I am playing music form my sd card and i want my seekbar to getprogress every 2 sec when music is playing. I am trying to do it with Handler. But i dont know how to use Handler coretly
Here is my code:
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    textView1 = (TextView) findViewById(R.id.textView1);

    button1.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            MediaPlayer mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(Environment.getExternalStorageDirectory()+"/MyImages/.audio2.wav");
                mediaPlayer.prepare();
                mediaPlayer.start();

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             setupHandler();

        }
    });
}
private void setupHandler()
{

 handler.removeCallbacks(moveSeekBarThread);
  handler.postDelayed(moveSeekBarThread, 2000); //cal the thread after  millisec
}
private Runnable moveSeekBarThread = new Runnable() {

    public void run() {

        if(mediaPlayer.isPlaying()){

        int mediaPos = mediaPlayer.getCurrentPosition();
        int mediaMax = mediaPlayer.getDuration();
        seekBar1.setMax(mediaMax);
        seekBar1.setProgress(mediaPos);

        handler.postDelayed(this, 2000); //Looping the thread after  second
                                        // seconds
        }
    }
};

}
My app crashing 2 second after i clikc the button1. So i am sure the problem here is Handler. Do i call this handler wrong or something?

A: Post your logcat always when you ask about app crashes.
Therefor in this case you have NullPointerException here, i think:
if(mediaPlayer.isPlaying())
You doesn't initialize your mediaplayer variable.
EDITED:
MediaPlayer mediaPlayer;
    @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    textView1 = (TextView) findViewById(R.id.textView1);

    button1.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(Environment.getExternalStorageDirectory()+"/MyImages/.audio2.wav");
                mediaPlayer.prepare();
                mediaPlayer.start();

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             setupHandler();

        }
    });
}
private void setupHandler()
{

 handler.removeCallbacks(moveSeekBarThread);
  handler.postDelayed(moveSeekBarThread, 2000); //cal the thread after  millisec
}
private Runnable moveSeekBarThread = new Runnable() {

    public void run() {

        if(mediaPlayer.isPlaying()){

        int mediaPos = mediaPlayer.getCurrentPosition();
        int mediaMax = mediaPlayer.getDuration();
        seekBar1.setMax(mediaMax);
        seekBar1.setProgress(mediaPos);

        handler.postDelayed(this, 2000); //Looping the thread after  second
                                        // seconds
        }
    }
};

A: Use The below code to Update the SeekBar after 2Seconds.
Create the Object for Handler inside your onCreate() like the following one.
Handler miHandler=new Handler();
add Paste the code inside your thread.
miHandler.postDelayed(new Runnable() {
       @Override
   public void run() {
       try{
                 seekBar1.setProgress(mediaPos+ add 2sec delay time also);
          }catch(Exception e) {e.printStrackTrace();}
   }
}, 1500);


text:
Q: BOOTMGR is missing при установке Win 7 Подскажите, такая проблема: есть ПК, в нем жесткий диск с Win 7. Мне нужно на другой жесткий диск (далее ЖД) поставить тоже Win 7. Я подключил второй ЖД и форматнул его. Потом отключил свой основной ЖД, оставив чистый второй, а в привод вставил диск установочный с WIN 7.
Естественно в биосе первым делом выставлена загрузка с CD привода.
При загрузке выдает ошибку "BOOTMGR is missing". Как я почитал, я при форматировании удалил какую-то ценную прогу типа загрузчика или что-то типа того.
Теперь вопрос: что мне со всем этим делать теперь?

A: Судя по всему, проблема в CD. Если образ диска брали из интернета, попробуйте прожечь диск через программу UltraISO, либо установиться с флешки, подробнее о том как сделать флешку загрузочной тут


text:
Q: Error when attempting to Export data to Excel. I have a button that exports data from telerik's RadGrid into an Excel document.
However, I am encountering the following error when I attempt to export:
[System.Threading.ThreadAbortException]:
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

Here's my code:
private void GenerateFile(object structure, string fileName)
{
    Workbook workbook = structure as Workbook;

    var formatProvider = new XlsxFormatProvider();

    try
    {
        using (MemoryTributary ms = new MemoryTributary())
        {
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);

            formatProvider.Export(workbook, ms);
            ms.Position = 0;
            ms.WriteTo(Response.OutputStream);

            Response.End();
            }
        }
        catch (System.OutOfMemoryException ex)
        {
        }
    }
}

I have tried the following solutions based on posts I have found online that dealt with the same issue, none of the solutions have worked:

*

*Change "Response.End()" to "HttpContext.Current.ApplicationInstance.CompleteRequest()"

*Change "Response.End()" to "HttpContext.Current.Response.End()"

*Move "Response.End()" inside a finally block.

*Move "Response.End()" outside of the try-catch scope.

None of the above solutions have solved the issue. Any further advice on how to resolve this error is greatly appreciate it.
Thanks.

A: You are causing the exception by calling Response.End. End's documented behavior is to flush buffers and abort the current request immediately by aborting it. It's not used in .NET programming. It's there only for compatibility with old ASP code.
Just remove Response.End() from your code
You should also remove the catch statement. Exceptions should be investigated and fixed, not covered up. An OutOfMemoryException means that there is something seriously wrong with the code that's causing leaks. It can be caused either because you run out of memory or because memory is so fragmented that .NET is unable to allocate a large enough block


text:
Q: How can i get output in sequence rather than random in PHP Hi i have some values in 1.txt and want to show them in sequence one by one rather than random and also on click of a button not on reload. And i don't have much code on it. Can anyone help me with it please. ?
index.php:
<?php $lines = file('1.txt');?>   <?php echo $lines[array($lines)];?>

1.txt in list format vertically:
1
2
3
4
5

A: Writing PHP like this is bad practice:
<?php $lines = ...;?>   <?php echo ....;?>

Better write like this:
<?php
  $lines = ...;
  echo ...;

Now to your problem, you should use sort to order an array see: https://www.php.net/manual/de/function.sort.php
The best way to print an array in PHP is foreach:
foreach ($lines as $line) {
    echo "\n<p>" . $line;
}

A: I'm not sure what your saying with the push of button and reload.
But this code assumes you mean, once the list has been generated keep it in the same order to this visitor.
I do that using a session variable so that even if the user reloads the page the order will be the same (for this user), but different between different users.
session_start();

if(empty($_session['lines'])){
    $_session['lines'] = file('1.txt');
    shuffle($_session['lines']);

}
// For debug:
echo implode("<br>\n", $_session['lines']);


text:
Q: Golang web server leaking memory at crypto/tls.(*block).reserve I've got a web server written in Go.
tlsConfig := &tls.Config{
    PreferServerCipherSuites: true,
    MinVersion:               tls.VersionTLS12,
    CurvePreferences: []tls.CurveID{
        tls.CurveP256,
        tls.X25519,
    },
    CipherSuites: []uint16{
        tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
        tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
        tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
        tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
        tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
        tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
    },
}

s := &http.Server{
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout:  120 * time.Second,
    Handler:      r, // where r is my router
    TLSConfig:    tlsConfig,
}

// redirect http to https
redirect := &http.Server{
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout:  120 * time.Second,
    Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Connection", "close")
        url := "https://" + r.Host + r.URL.String()
        http.Redirect(w, r, url, http.StatusMovedPermanently)
    }),
}
go func() {
    log.Fatal(redirect.ListenAndServe())
}()

log.Fatal(s.ListenAndServeTLS(certFile, keyFile))

Here is a screenshot from my Digital Ocean dashboard.

As you can see memory keeps growing and growing. So I started looking at https://github.com/google/pprof. Here is the output of top5.
Type: inuse_space
Time: Nov 7, 2018 at 10:31am (CET)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top5
Showing nodes accounting for 289.50MB, 79.70% of 363.24MB total
Dropped 90 nodes (cum <= 1.82MB)
Showing top 5 nodes out of 88
      flat  flat%   sum%        cum   cum%
  238.98MB 65.79% 65.79%   238.98MB 65.79%  crypto/tls.(*block).reserve
   20.02MB  5.51% 71.30%    20.02MB  5.51%  crypto/tls.Server
   11.50MB  3.17% 74.47%    11.50MB  3.17%  crypto/aes.newCipher
   10.50MB  2.89% 77.36%    10.50MB  2.89%  crypto/aes.(*aesCipherGCM).NewGCM

The SVG shows the same huge amount of memory allocated by crypto/tls.(*block).reserve.

Here is the exact code.

I spent the last days reading every article, document, blog post, source code, help file I could find. However nothing helps. The code is running on a Ubuntu 17.10 x64 machine using Go 1.11 inside a Docker container.
It looks like the server doesn't close the connections to the client. I thought setting all the xyzTimeout would help but it didn't.
Any ideas?
Edit 12/20/2018:
fixed now https://github.com/golang/go/issues/28654#issuecomment-448477056

A: Adding an answer so this doesn't keep showing up in the list of upvoted and unanswered questions.
It appears that the memory leak was related to the gorilla context bug https://github.com/gorilla/sessions/commit/12bd4761fc66ac946e16fcc2a32b1e0b066f6177 and had nothing to do with tls in the stdlib.