text:
Q: The integral of the axial current conservation law In the section 19.1 "The Axial Current in Two Dimensions" of  Peskin & Shroeder.
On page 657,

In free fermion theory, the integral of the axial current conservation law gives
  $$ \int d^2x\,  \partial_{\mu}j^{\,\mu 5} =N_R -N_L \quad (=0) \tag{19.30} $$

What's this?
If (19.30) is correct,  it follows that in the ordinary four-dimensional case,
\begin{cases}
\displaystyle N_R=\int d^4x \, \partial_{\mu} \bar{\psi} \gamma^{\mu}\left(\frac{1+\gamma^5}{2}\right)\psi =\int d^4x \, \partial_{\mu}j_R^{\,\mu}, \\
\displaystyle
N_L=\int d^4x \, \partial_{\mu} \bar{\psi} \gamma^{\mu}\left(\frac{1-\gamma^5}{2}\right)\psi =\int d^4x \, \partial_{\mu}j_L^{\,\mu}, \\
\displaystyle
N=\int d^4 \, \partial_{\mu} \bar{\psi} \gamma^{\mu}\psi = \int d^4x \, \partial_{\mu}j^{\,\mu}.
\end{cases}
These look weird to me.

A: One correcrion: these definitions are the time integrals over the time derivatives of the quantities
$$
N(t)=\int d^{3}\mathbf r J^{0}(\mathbf r, t)
$$
under an assumption that the spatial currents vanishes at infinity,
$$
\int d^{4}\mathbf r \nabla \cdot \mathbf J =\oint d\mathbf S \cdot \mathbf J \to 0
$$
With these assumptions, the integral
$$
\int d^{4}x \partial_{\mu}J^{\mu} = \int \limits_{t_{0}}^{t_{1}} dt \frac{dN}{dt}
$$
of a time derivative of $N$ is reduced to the values of $N$ at the boundaries $t_1, t_0$ of the integration, namely,
$$
N(t_{1})-N(t_0) = \Delta N
$$

A: In four dimensions,
The correct definition of $N_R ,\,N_L \, \text{and}\, N$ is
\begin{cases}
\displaystyle
N_R=\int d^3 \mathbf{x} \, \bar{\psi} \gamma^{0}P_R \psi =\int d^3 \mathbf{x} \, \bar{\psi} \gamma^{0}\left(\frac{1+\gamma^5}{2}\right)\psi =\int d^3 \mathbf{x} \, j_R^{\,0}\,, \\
\displaystyle
N_L=\int d^3 \mathbf{x} \, \bar{\psi} \gamma^{0}P_L \psi =\int d^3 \mathbf{x} \, \bar{\psi} \gamma^{0}\left(\frac{1-\gamma^5}{2}\right)\psi =\int d^3 \mathbf{x} \, j_L^{\,0}\,, \\
\displaystyle
N=\int d^3 \mathbf{x} \, \bar{\psi} \gamma^{0}\psi = \int d^3 \mathbf{x} \, j^{\,0}\,.
\end{cases}
$N$ is the Noether charge $Q$ associated with the vector current conservation law.
Let $Q^5$ be the Noether charge associated with the axial current conservation law.
$$ Q^5= \int d^3 \mathbf{x} \, j^{\,05} =\int d^3 \mathbf{x} \, \bar{\psi} \gamma^{0}\gamma^{5}\psi = \int d^3 \mathbf{x} \,\left( \bar{\psi} \gamma^{0}P_R\psi - \, \bar{\psi} \gamma^{0}P_L\psi \right) =N_R-N_L $$
$$ \partial_0 Q^5=\partial_0 N_R - \partial_0 N_L= \int d^3 \mathbf{x} \, \partial_0 \bar{\psi} \gamma^{0}\gamma^{5}\psi = \int d^3 \mathbf{x} \, \partial_0 j^{\,05} = \int d^3 \mathbf{x} \, \partial_{\mu} j^{\,\mu 5}=0 $$
This is under an assumption that the spatial axial currents vanishes at infinity.
$$ \int d^3 \mathbf{x} \,\partial_i j^{\,i5} =\oint d\mathbf S \cdot \mathbf j^5 \to 0 $$
$$ \therefore \Delta N_R - \Delta N_L =0 = \int d^4 x \, \partial_0 \bar{\psi} \gamma^{0}\gamma^{5}\psi  = \int d^4 x \, \partial_{\mu} j^{\,\mu 5} $$
In two dimensions,
$$ Q^5= \int d x^1 \, \bar{\psi} \gamma^{0}\gamma^{5}\psi = \int d x^1 \,\left( \bar{\psi} \gamma^{0}P_R\psi - \bar{\psi} \gamma^{0}P_L\psi \right) =N_R-N_L $$
$$ \partial_0 Q^5=\partial_0 N_R - \partial_0 N_L= \int d x^1 \, \partial_0 \bar{\psi} \gamma^{0}\gamma^{5}\psi = \int d x^1 \,\partial_0 j^{\,05}=\int d x^1 \,\partial_{\mu} j^{\,\mu 5} =0 $$
Here the authors assume the spatial axial current vnishes at infinity.
$$ \int dx^1 \, \partial_1 j^{\,15} =\left[ j^{\,15}\right]_{-\infty}^{\infty} \to 0 $$
(19.30) should be replaced by
$$ \int d^2x\,  \partial_{\mu}j^{\,\mu 5} =\Delta N_R -\Delta N_L =0 .\tag{19.30} $$
So the sentence just below (19.30)

This relation implies that the difference in the number of right-moving and left-moving fermions cannot be changed in any possible process.

should be replaced by

This relation implies that the difference in the variation of right-moving and left-moving fermion numbers cannot be changed in any possible process.

The LHS of (19.39) should be also
$$ \Delta N_R -\Delta N_L .$$


text:
Q: Using Linq, How can I properly append multiple Where clauses so that they appear in the appropriate order? The order I would like the end result to appear in is Exact Matches first given a input string, followed by other matches that are Contains for a given field.  I tried to approach this in a very rudimentary way as shown here in this example:
var raw = Model.SearchResults.Where(m =>  m.EffectiveDateTime != null).OrderBy(m => m.EffectiveDateTime).ToList();
    var exact = raw.Where(m => m.IssueNumber.ToLower() == Model.SearchText.ToLower());
    var contains = raw.Where(m => m.IssueNumber.ToLower().Contains(Model.SearchText.ToLower()));
    var list = exact.Union(contains);

This approach seems like it'd be a really bad way to do this.  In fact, the Union portion seems to effectively crash my application.  Is there an opposite to Intersection which would give me the remaining results outside the Exact matches that I could then append to a final list so that the order would be Exact Matches followed by StartsWith matches followed finally by Contains matches in that descending order?

A: To answer your original question, you can use a temporary expression to classify the match types, then order by the match type and other criteria, and it will translate to SQL as well:
var st = Model.SearchText.ToLower();
var list = Model.SearchResults.Where(m => m.EffectiveDateTime != null)
                              .Select(m => new {
                                  m,
                                  im = m.IssueNumber.ToLower()
                              })
                              .Select(mim => new {
                                  mim.m,
                                  Rank = mim.im == st ? 1 : mim.im.StartsWith(st) ? 2 : mim.im.Contains(st) ? 3 : 4
                              })
                              .Where(mr => mr.Rank < 4)
                              .OrderBy(mr => mr.Rank)
                              .ThenBy(mr => mr.m.EffectiveDateTime)
                              .Select(mr => mr.m)
                              .ToList();

I did the double Select to emulate let from fluent syntax, which I think is a bit clearer than lambda syntax in this case:
var lisx = (from m in Model.SearchResults
            where m.EffectiveDateTime != null
            let im = m.IssueNumber.ToLower()
            let Rank = im == st ? 1 : im.StartsWith(st) ? 2 : im.Contains(st) ? 3 : 4
            where Rank < 4
            orderby Rank, m.EffectiveDateTime
            select m)
           .ToList();

Also, if you do the whole query in the database, the ToLower is likely unnecessary, as the default for SQL is probably to be case-insensitive anyway.

A: Actually, I went back to the drawing board and figured it out.  This is a little bit better for me and returns the results I needed.
        var list = Model.SearchResults
             .Where(e => e.A.ToLower().Contains(Model.SearchText.ToLower()))
             .GroupBy(d => new { d.A, d.B, d.C})
             .OrderBy(x => x.Key.A)
             .ThenBy(x => x.Key.B)
             .ThenBy(x => x.Key.C)
             .Select(x => new
             {
                 A= x.Key.A,
                 B= x.Key.B,
                 C= x.Key.C
             })
             .ToList();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show user that program still. Running I wrote  a Java program that reads a file, process the numbers and then output result to to the user. The processing could take a while  so I would like to display some sort of progress bar or just simply thinking glass (anything reallly)  that indicate to the user that the program is actually processing something.
Any recommendation for quick Solution for it?
Thank you

A: Display a busy cursor:
try {
  component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  // process
} finally {
 component.setCursor(Cursor.getDefaultCursor());
}

A: This might help you...
Command line progressbar
http://nakkaya.com/2009/11/08/command-line-progress-bar/
public static void printProgBar(int percent){
    StringBuilder bar = new StringBuilder("[");

    for(int i = 0; i < 50; i++){
        if( i < (percent/2)){
            bar.append("=");
        }else if( i == (percent/2)){
            bar.append(">");
        }else{
            bar.append(" ");
        }
    }

    bar.append("]   " + percent + "%     ");
    System.out.print("\r" + bar.toString());
}


text:
Q: Display the ::after pseudo-element outside padding space and horizontally center I try to add a little triangle as the current page indicator under the list item of my navbar with class "active" using ::after.
However,

*

*The alignment of the triangle may not be center for all list items due to the length differences.

*The website should be responsive. When I resize the window screen, list items are compacted and enlarge the width of the list. Again, due to the length differences of list items, part of the triangle will be covered if it is under a short list item as the "::after" ignores the padding space.

Here's the code snippet:

nav {
  display: block;
}

ul {
  display: table;
  text-align: center;
  background-color: red;
  margin-bottom: 5%;
  width: 100%;
  padding-left: 0;
  margin-bottom: 0;
  list-style: none;
}

li {
  display: table-cell;
  float: none;
  padding: 5px 0;
  vertical-align: middle;
  position: relative
}

li.active::after {
  content: "";
  width: 0;
  height: 0;
  position: absolute;
  right: 40%;
  border-style: solid;
  border-width: 15px 10px 0 10px;
  border-color: red transparent transparent transparent;
}

xxxxxxxxxxxxxxxxxx

xxxx

xxxx

xxxx

xxxx

xxxx

xxxx

Is there any solution for that?

A: Replace right: 40% in li.active:after with this:
bottom: 0; /* aligns to the bottom*/
right: 50%;
transform: translate(50%, 100%); /* centering */

See demo below:

nav {
  display: block;
}

ul {
  display: table;
  text-align: center;
  background-color: red;
  margin-bottom: 5%;
  width: 100%;
  padding-left: 0;
  margin-bottom: 0;
  list-style: none;
}

li {
  display: table-cell;
  float: none;
  padding: 5px 0;
  vertical-align: middle;
  position: relative
}

li.active::after {
  content: "";
  width: 0;
  height: 0;
  position: absolute;
  bottom: 0;
  transform: translate(50%, 100%);
  right: 50%;
  border-style: solid;
  border-width: 15px 10px 0 10px;
  border-color: red transparent transparent transparent;
}

xxxxxxxxxxxxxxxxxx

xxxx

xxxx

xxxx

xxxx

xxxx

xxxx

A: You're almost there.
You can solve the horizontal position issue by using calc() in your CSS. It's worth looking at the CanIUse data for this to check its support.
You can use this by to calculate the position of your arrow given the fact you want it to be in the centre by subtracting half of the width of your arrow from 50%;
left: calc(50% - 10px)

Then, you just need a negative position on your bottom position attribute to bring the arrow underneath your list element.
bottom: -15px;

Here's a working code snippet;

nav{
    display: block;
}

ul{
    display: table;
    text-align: center;
    background-color: red;
    margin-bottom: 5%;
    width: 100%;
    padding-left: 0;
    margin-bottom: 0;
    list-style: none;
}

li{
    display: table-cell;
    float: none;
    padding: 5px 0;
    vertical-align: middle;
    position: relative
}

li.active::after{
      content: "";
      width: 0;
      height: 0;
      position: absolute;
      left: calc(50% - 10px);
      bottom: -15px;
      border-style: solid;
      border-width: 15px 10px 0 10px;
      border-color: red transparent transparent transparent;
}

xxxxxxxxxxxxxxxxxx

xxxx

xxxx

xxxx

xxxx

xxxx

xxxx


text:
Q: No results are returned in dataframe I am trying to take the average every fifth and every sixth row of var A in a dataframe, and put the result in a new column as var B. But it NaN shows. It may be resulted by I did not return values correctly?
Here is the sample data:
PID    A
1      0
1      3
1      2
1      6
1      0
1      2
2      3
2      3
2      1
2      4
2      0
2      4

Expected results:
PID    A      B
1      0      1
1      3      1
1      2      1
1      6      1
1      0      1
1      2      1
2      3      2
2      3      2
2      1      2
2      4      2
2      0      2
2      4      2

My codes:
lst1 = df.iloc[5::6, :]
lst2 = df.iloc[4::6, :]

df['B'] = (lst1['A'] + lst2['A'])/2
print(df['B'])

The script can be run without error, but the var B is empty and show NaN.
Thanks for your help!

A: There is problem data not aligned, because different indexes, so get NaNs.
print(lst1)
    PID  A
5     1  2
11    2  4

print(lst2)
    PID  A
4     1  0
10    2  0

print (lst1['A'] + lst2['A'])
4    NaN
5    NaN
10   NaN
11   NaN
Name: A, dtype: float64

Solution is use values for add Series to numpy array:
print (lst1['A'] + (lst2['A'].values))
5     2
11    4
Name: A, dtype: int64

Or you can sum 2 numpy arrays:
print (lst1['A'].values + (lst2['A'].values))
[2 4]

It seems you need:
df['B'] = (lst1['A'] + lst2['A'].values).div(2)
df['B'] = df['B'].bfill()
print(df)
    PID  A    B
0     1  0  1.0
1     1  3  1.0
2     1  2  1.0
3     1  6  1.0
4     1  0  1.0
5     1  2  1.0
6     2  3  2.0
7     2  3  2.0
8     2  1  2.0
9     2  4  2.0
10    2  0  2.0
11    2  4  2.0

But if need mean of 5. and 6. value per group by PID use groupby with transform:
df['B']  = df.groupby('PID').transform(lambda x: x.iloc[[4, 5]].mean())
print(df)
    PID  A    B
0     1  0  1.0
1     1  3  1.0
2     1  2  1.0
3     1  6  1.0
4     1  0  1.0
5     1  2  1.0
6     2  3  2.0
7     2  3  2.0
8     2  1  2.0
9     2  4  2.0
10    2  0  2.0
11    2  4  2.0

A: Option 1
Straightforward way taking the mean of the 5th and 6th positions within each group defined by 'PID'.
df.assign(B=df.groupby('PID').transform(lambda x: x.values[[4, 5]].mean()))

    PID  A    B
0     1  0  1.0
1     1  3  1.0
2     1  2  1.0
3     1  6  1.0
4     1  0  1.0
5     1  2  1.0
6     2  3  2.0
7     2  3  2.0
8     2  1  2.0
9     2  4  2.0
10    2  0  2.0
11    2  4  2.0

Option 2
Fun way using join assuming there are actually exactly 6 rows for each 'PID'.
df.join(df.set_index('PID').A.pipe(lambda d: (d.iloc[4::6] + d.iloc[5::6]) / 2).rename('B'), on='PID')

    PID  A    B
0     1  0  1.0
1     1  3  1.0
2     1  2  1.0
3     1  6  1.0
4     1  0  1.0
5     1  2  1.0
6     2  3  2.0
7     2  3  2.0
8     2  1  2.0
9     2  4  2.0
10    2  0  2.0
11    2  4  2.0


text:
Q: Как добавить подсказки в VS Code для Unity? Когда я открываю C# скрипт из Unity, то VS Code при вводе любых слов не выдает подсказки. Например, если я пишу "using Sy", то он должен предложить System, но этого не происходит. Расширение C# установлено, dotnet тоже. VS Code также выбран как основной во вкладке External Tools в Unity.

A: Заходишь в VS Code, заходишь в расширения, ищешь в поиске "Unity", находишь "Unity Tools" от Avin Zarlez, и устанавливает. Ну и все готово, по крайней мере у меня все работает.


text:
Q: Alsamixer: Headphone volume controls Speaker volume in Acer NE46RS1 Laptop I have recently bought a cheap laptop which has a single integrated speaker and headphone out. The problem is, speaker is not working while headphone works fine. I used alsamixer to figure out what is wrong. When I increase headphone volume, the speaker sound works. But, on next reboot, Headphone volume control gets muted again. How to correctly assign speaker volume.

A: Yesterday, I found a workaround. I simply installed Alsamixergui (An interface for Alsa), and the program saved my config (headphone volume) to my next boot.


text:
Q: How to add some value into variable of advice in aspect class This is quite odd but I really need this ... I have this code
@Aspect
public class SomeAspect {

    SomeObject someObject = null;

    @Pointcut("something")
    public void somePoint() {
    }

    @Before("somePoint()")
    public void beforeSomePoint() {
    }

    @After("somePoint()")
    public void afterSomePoint() {
        someObject.hello();
    }

    public void waitForEvent(SomeEvent event) {
        someObject = event.getObject();
    }
}

So basically I have pointcut and two advices, I have a method which is listening to some event which is fired in my application. I get object from that event I am interested in and I initialize someObject variable in waitForEvent method. This works and I am sure that someObject is passed correctly into waitForEvent method.
The point is that I need to operate on that object I got in the body of advice method like someObject.hello() but it seems to me that it is still null even I know that event is fired before actual execution of the afterSomePoint advice.
I am not using Spring or any other related framework. I am using pure Java + AspectJ, annotated version.
How do I pass some object into advice from outside?
Thank you a lot

A: Hi are you sure that someObj is still null?
Here is the result for my experiment:
I change someObject to String.
@Aspect
public class SomeAspect {

    String someObject = null;

    @Pointcut("Call( * init(..) )")
    public void somePoint() {
    }

    @Before("somePoint()")
    public void beforeSomePoint() {
    }

    @After("somePoint()")
    public void afterSomePoint() {
        System.out.println(someObject);
    }

    public void waitForEvent(String event) {
        someObject = event;
    }
}

In my main program:
public static void main(String[] args) {

SomeAspect a = Aspects.aspectOf(SomeAspect.class);
a.waitForEvent("Event!!");

Child c = new Child();
c.init(); //The advice will be triggered here!!

}

This way, afterSomePoint() advice is triggered, and "Event!!" is printed out
I think you can use Aspects.aspectOf(SomeAspect.class) to get the aspect instance, and pass it to the framework. If you new the SomeAspect, it will create another instance apart from the one already in the VM
Reference: eclipse.org/aspectj/doc/next/progguide/semantics-aspects.html

Unlike class expressions, aspects are not instantiated with new
  expressions. Rather, aspect instances are automatically created to cut
  across programs. A program can get a reference to an aspect instance
  using the static method aspectOf(..)

A: Oh this is very funny ...
I just made that variable static and it seems it works. Is this some kind of magic? Is this the way how to do? Is there any other way?
@Aspect
public class SomeAspect {

    private static SomeObject someObject = null;

    @Pointcut("something")
    public void somePoint() {
    }

    @Before("somePoint()")
    public void beforeSomePoint() {
    }

    @After("somePoint()")
    public void afterSomePoint() {
        SomeAspect.someObject.hello();
    }

    public void waitForEvent(SomeEvent event) {
        SomeAspect.someObject = event.getObject();
    }
}


text:
Q: React use variable in .setState In my function I need to pass a variable to the .setState function but I'm not able to solve this issue. I'm rather new to React so I hope someone can help me out. My code is like this:
  public componentDidMount(){
    var reactHandler = this;
    var Xresults = {};

    jquery.ajax({
      //url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`,
      url: "https://blabla.sharepoint.com/sites/ilss/_api/search/query?querytext='ContentType:test_matters'&selectproperties='RefinableString10%2cCreatedBy%2cCreated'&rowlimit=500'",

      type: "GET",
      headers:{'Accept': 'application/json; odata=verbose;'},
      success: function(resultData) {
        for(var i=0;i<resultData.d.query.PrimaryQueryResult.RelevantResults.TotalRows;i++){
          Xresults [resultData.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results[i].Cells.results[2].Key] = resultData.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results[i].Cells.results[2].value;
        }

        reactHandler.setState({
          items: Xresults
        });
      },
      error : function(jqXHR, textStatus, errorThrown) {
      }
   });
 }

in the .setState "Xresults" is not available. How do I pass this?
Thanks, Mike


text:
Q: Exploding an object column, concatenating the results and adding them to the original rows I have a Snowflake table similar to this:
CREATE OR REPLACE VIEW EXAMPLE AS
SELECT $1 AS ID_EXAMPLE,
       PARSE_JSON($2) AS SOME_JSON
  FROM (VALUES ('a','[1,2]'),
               ('b','[3,4]'));

I want to create a derived view with the same structure, but with an extra column that is the string concatenation of the values inside the JSON column.
This attempt at query for the new view doesn't work:
SELECT E.*,
       EXTRA.VALUE AS EXTRA_COL
 FROM EXAMPLE E
 CROSS JOIN LATERAL
   (SELECT LISTAGG(VALUE,'/') AS VALUE
      FROM TABLE(FLATTEN(INPUT => E.SOME_JSON))) EXTRA;

It fails with "SQL compilation error: Unsupported subquery type cannot be evaluated".
This query using GROUP BY does work:
SELECT E.*,
       LISTAGG(EXTRA.VALUE,'/') AS EXTRA_COL
FROM EXAMPLE E
CROSS JOIN LATERAL FLATTEN(INPUT => E.SOME_JSON) EXTRA
GROUP BY E.ID_EXAMPLE, E.SOME_JSON;

The problem is that my real table has a huge number of columns, so the GROUP BY will be cumbersome to write and maintain. Is there some way of formulating the query that doesn't involve writing the complete GROUP BY clause?

A: So moving the create to a CTE to just prove the error still happens in this form:
WITH the_view AS (
  SELECT $1 AS ID_EXAMPLE,
       PARSE_JSON($2) AS SOME_JSON
  FROM (VALUES ('a','[1,2]'),
               ('b','[3,4]'))
)
SELECT E.*,
       EXTRA.VALUE AS EXTRA_COL
 FROM the_view E
 CROSS JOIN LATERAL
   (SELECT LISTAGG(VALUE,'/') AS VALUE
      FROM TABLE(FLATTEN(INPUT => E.SOME_JSON))) EXTRA;

and it does, if we move the sub-select to it's own level CTE we can join on the id_column
WITH example AS (
  SELECT $1 AS ID_EXAMPLE,
       PARSE_JSON($2) AS SOME_JSON
  FROM VALUES ('a','[1,2]'),
              ('b','[3,4]')
), sub_process AS (
  SELECT E.ID_EXAMPLE,
     LISTAGG(EXTRA.VALUE,'/') AS EXTRA_COL
  FROM EXAMPLE E,
  TABLE(FLATTEN(INPUT => E.SOME_JSON)) EXTRA
  GROUP BY E.ID_EXAMPLE
)
SELECT e.*,
       s.EXTRA_COL
 FROM example AS e
 JOIN sub_process s ON E.ID_EXAMPLE = s.ID_EXAMPLE;

which gives:
ID_EXAMPLE  SOME_JSON   EXTRA_COL
a   [    1,    2  ]     1/2
b   [    3,    4  ]     3/4

that seems to solve the problem.


text:
Q: what is the difference between LINQ and ADO.net what is the difference between LINQ and ADO.net

A: Linq is a language feature (Language INtegrated Query) that allows for querying of objects. It is often conflated with Linq to Sql, which is a series of extension methods and other code that allows querying of a Sql Server database using Linq statements.
You can write a Linq provider to query any kind of datasource, for example, there is a Linq to Amazon provider that allows you to retrieve results from Amazon's public API.
ADO.Net is series of technologies for retrieving data, I suggest starting here: http://en.wikipedia.org/wiki/ADO.NET

A: I think you probably mean LINQ-to-SQL. ADO.NET is the bare bones of talking to a Database, so you need to set up the DataTables, DataReaders, etc. yourself. This includes iterating through our tables, setting up your connections, transactions, etc.
LINQ-to-SQL is an ORM (Object Relationship Mapper)  which allows you to view your data as business objects, instead of collections of data in DataTables. LINQ-to-SQL works with ADO.NET under the hood. Much easier!
LINQ is the expression syntax used by LINQ-to-SQL to query tables, eg
ClientSet.Where(q=>q.ID==1).First();

A: LINQ to SQL actually stands for LINQ to 'databases that use SQL' or in other words LINQ for the relational data model.  LINQ to Entities means LINQ for the Entity-Data-Model which is a kind of a relational++ model.
More info:
http://blogs.microsoft.co.il/blogs/gilf/archive/2008/04/20/linq-to-sql-vs-entity-framework.aspx

A: ADO.NET

*

*It is a part of .NET Framework since .NET Framework 1.0

*SqlConnection/OleDbConnection is used for database connectivity.

*Difficult to debug and cause syntax errors at run-time.

*It has full type checking at run-time and not IntelliSense support in Visual
Studio, since it used the T-SQL to query the database.

LINQ

*

*It is a part of .NET Framework since .NET Framework 3.5

*We can use context for database connectivity.

*Easy to debug and cause syntax errors at compile-time.

*It has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET Framework languages like C# and VB.


text:
Q: How to add class to random element in pure JavaScript and set value to another element my code
My code use

var lights = document.getElementsByClassName("light");
  var previousRandomLight = null

  function repeatOften() {
    if (previousRandomLight) previousRandomLight.classList.toggle('select')
    var random = Math.floor(Math.random() * (lights.length - 1)) + 0;
    var randomLight = lights[random];
    randomLight.classList.toggle('select');
    previousRandomLight = randomLight;
    setTimeout(repeatOften, 1000);

  }

  repeatOften();

now I need to be transferred value to the Customer field with each time added to the SELECT class
Like the code below :

text3

But I did not know how to do that please help me?

A: Not really clean in my opinion but it works:

var lights = document.querySelectorAll(".light");

function repeatOften() {
  var random = Math.floor(Math.random() * (lights.length)) + 0;
  var randomLight = lights[random];
  lights.forEach((light) => {
    light.classList.remove('select');
  });
  randomLight.classList.toggle('select');
  setTimeout(repeatOften, 1000);
}

repeatOften();
.select {
  color: red;
}


text:
Q: Behavior difference www.foosite.com versus foosite.com I have a shopping cart I'm implementing (well known company and a solid platform) -- it's based in PHP/Smarty.
Works great if I put www.foosite.com/store/ into my browser.
If I put foosite.com/store/ into the browser it is not populating saved cookie variables correctly.  Also, I noticed that it prompts me twice on my .htaccess/.htpasswd block.
So, what is it about www. versus without that can cause such a dramatic difference in the behavior of a site?  And is there a way to fix it?

A: well a solution to fix this would be to add in your htaccess a rewrite rule to force the 'www', something like this:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: My Protocol is not Calling I am using protocol for call method but my method does not call.Is there is any example which i use.
Here is my code:
ViewController
    class ViewController: UIViewController {
      override func viewDidLoad() {
        super.viewDidLoad()
                // Do any additional setup after loading the view.
    }

extension ViewController :ViewController1Delegate
{
    func hello()
    {
        println("hbgyguyg");
    }
}

In View Controller 1
import UIKit
@objc
protocol ViewController1Delegate
{
   optional func hello()
}
class ViewController1: UIViewController {
 var delegate: ViewController?
    override func viewDidLoad() {
        super.viewDidLoad()
                    delegate?.hello()
             }

}

Please Help, I am new in Swift.Any help would be apperciated. Thanks in Advance

A: An example demo.
ViewController file
import UIKit

class ViewController: UIViewController, PopUpViewControllerDelegate
{
    var popupVC: PopUpViewController!;

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.view!.backgroundColor = UIColor.whiteColor();

        self.popupVC = PopUpViewController();
        self.popupVC.delegate = self;

        self.showPopUpVC();
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func popUpViewControllerDidPressOK(popUpVC: PopUpViewController) {

        println("Yay?");

        self.closePopUpVC();
    }

    func showPopUpVC()
    {
        let delayTime = dispatch_time(DISPATCH_TIME_NOW,
            Int64(1.0 * Double(NSEC_PER_SEC)))

        dispatch_after(delayTime, dispatch_get_main_queue()) {

            self .presentViewController(self.popupVC, animated: true, completion: nil);

        }
    }

    func closePopUpVC()
    {
        let delayTime = dispatch_time(DISPATCH_TIME_NOW,
            Int64(1.0 * Double(NSEC_PER_SEC)))

        dispatch_after(delayTime, dispatch_get_main_queue()) {

            self.dismissViewControllerAnimated(true, completion: nil);

        }
    }
}

PopUpViewController file
import UIKit

protocol PopUpViewControllerDelegate
{
    func popUpViewControllerDidPressOK(popUpVC: PopUpViewController);
}

class PopUpViewController: UIViewController {

    var delegate: PopUpViewControllerDelegate!;

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view!.backgroundColor = UIColor.redColor();

        // Do any additional setup after loading the view.

        self.delegate!.popUpViewControllerDidPressOK(self);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Notice how in my ViewController viewDidLoad() method, I have a line that initialises the popUp view controller and then set its delegate to be the ViewController itself:
self.popupVC = PopUpViewController();
self.popupVC.delegate = self; // you're missing this line I believe ?

I don't use Interface Builder or Storyboard but maybe select your VC1 in your Storyboard and look in the connections inspector to see if you drag a line from "delegate" to your ViewController file owner thing.
In the end, you should see a red screen popup after 1 second, followed by the word "Yay?" logged into your Xcode console and finally the popupVC dismisses.


text:
Q: How to share file access between some processes using Mutex? I have a simple class for copying files from one directory to another. Also, I need to get a file checksum after copying. The copying method may be called by many instances, for example, 5 processes are copying one file to 5 different directories in parallel, so when some processes try to get checksum, I get an IO exception.
So I've tried to tell each process to wait until the source file is unlocked:
bool IsFileLocked(FileInfo file)
{
    try
    {
        using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
        {
            stream.Close();
        }
    }
    catch (IOException)
    {
        return true;
    }

    return false;
}

Such a decision works, but only if I call Thread.Sleep(10) in while loop(in getting checksum method for waiting), otherwise I get the same error.
while (IsFileLocked(fi))
{
    System.Threading.Thread.Sleep(10);
}

So I see, that it's a very bad solution.
Now I try to use Mutex:
string GetFileHash(string path)
{
    string hashValue = null;

    using (SHA256 sha256 = SHA256.Create())
    {
        FileInfo fi = new FileInfo(path);

        try
        {
            mutexObj.WaitOne();

            using (FileStream fileStream = fi.Open(FileMode.Open))
            {
                fileStream.Position = 0;
                hashValue = System.Text.Encoding.Default.GetString(sha256.ComputeHash(fileStream));
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine($"GHM:I/O Exception: {ex.Message}");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine($"GHM:Access Exception: {ex.Message}");
        }
        finally
        {
            mutexObj.ReleaseMutex();
        }
    }

    return hashValue;
}

But that doesn't work. I think, that the problem is in different Mutex instances in 5 independent processes.
So, tell me, please, how to solve this? Is there a way to declare global mutex?


text:
Q: Why traps Rocket Chip on FPGA after code execution in DRAM I try to get a version of Rocket Chip on a Nexys4 DDR board up and running. So far I managed to generate the verilog, synthesize the design and attach a jtag probe (segger jlink). It is possible to access registers and memory via openocd and gdb. After loading a small snippet of asm the core starts executing but jumps after the first executed instruction directly to 0x0000000. I assume it traps and since the trap vector is not initialized the core ends up at 0. Does anybody know how to fix this?
The simulation of the core works both with verilator and vcs. In both cases the core executes the three asm instructions without complains.
The tested asm code is:
.section .text
.global _start
_start:
    add x0,x0,x0
    add x0,x0,x0
    j _start

linked with the this script:
SECTIONS
{
    . = 0x80000000;
    .text : { *(.text) }
}

Object dump:
Disassembly of section .text:

0000000080000000 <_start>:
    80000000:   00000033                add     zero,zero,zero
    80000004:   00000033                add     zero,zero,zero
    80000008:   ff9ff06f                j       80000000 <_start>

A: Recently ran into a similar issue with DDR4, GDB and a SiFive RISC chip.  After loading code onto the DDR4, and attempting to step from the reset vector, the RISCV would immediately jump to 0x00000000.   After debuging with a Xilinx ILA, we found that although we were programming the DDR4 memory space with GDB, the RISCV was caching some of the code internally, and only occasionally pushing some to the DDR4.  From the RISCV point of view, this is thought to be okay because, when you step and it will decide to use cache if available, otherwise it would retrieve code from the DDR4.  But lets say your CPU pulls several bursts of DDR accesses because it wants a lot of code for efficency.  Some of that large chunk of code, which could be empty space if your program is really small, will not have been programmed and thus the ECC is not calculated correctly.
Check the machine cause register after jumping to 0x00000000.  See if it indicates 0x2, illegal instruction.  In my case, I saw this because the bus observed a "bus error", which was induced by an ECC fault do to a half programmed DDR burst.
One way to work around this might be to pad your ELF with a bunch of extra zeros at the end such that the size will force the cache to flush to the memory. Once the DDR is really programmed, and the ECC's are correct, you shouldn't see the invalid instruction anymore.  Let me know if that works for you or not.


text:
Q: How do i make sure ALL textfields & Radio Buttons are selected inside a form? I have a form with textfield, textareas and radio buttons. I want to make sure everything inside the div is selected, therefore i have disabled the submit button until everything is selected. But i can't seem to get it to work. I have a jquery functions which works, when i check on all the required input fields, but it doesn't work on radio buttons. Here is what is working:
$(document).ready(function(){
  function checkInputs() {
    var validInputs = true;
    $('input').filter('[required]').each(function() {
      if ($(this).val() === '') {
        validInputs = false;
        return false;
      }
    });

    if(validInputs) {$('#speichern').prop('disabled', false)}
    return validInputs;
  }

  //Enable or disable button based on if inputs are filled or not
  $('input').filter('[required]').on('keyup',function() {
    checkInputs();
  })

  checkInputs();

});

How can i include the radio buttons inside this function?

A: Try this inside checkInputs()
$('input').filter('[required]').each(function() {
  var elm = this,
    $elm = $(elm);
  switch (elm.type) {
    case 'text':
      if ($elm.val() === '') {
        validInputs = false;
        return false;
      }
      break;
    case 'radio':
      if (!elm.checked) {
        validInputs = false;
        return false;
      }
      break;
    case 'checkbox':
      // handle checkbox
      break;
    default:
      // handle others
      break;
  }
});


text:
Q: Multiple Data source in hibernate annotation throwing No Session found for current thread error I am using spring 4 & hibernate annotation in my web app. Everything works fine with single datasource. When I add second datasource I am getting No session for current thread error.
Here is the code.
public abstract class PortalAbstractDao<PK extends Serializable, T> {

private final Class<T> persistentClass;

@SuppressWarnings("unchecked")
public PortalAbstractDao() {
    this.persistentClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
            .getActualTypeArguments()[1];
}

@Autowired
@Qualifier("eportalSessionFactory")
private SessionFactory sessionFactory;

protected Session getSession() {
    return sessionFactory.getCurrentSession();
}

@SuppressWarnings("unchecked")
public T getByKey(PK key) {
    return (T) getSession().get(persistentClass, key);
}

public void persist(T entity) {
    getSession().persist(entity);
}

public void delete(T entity) {
    getSession().delete(entity);
}

protected Criteria createEntityCriteria() {
    return getSession().createCriteria(persistentClass);
}

}
DAO Implementation
@Repository("portalDao")
public class PortalDaoImpl extends PortalAbstractDao<Integer, PortalAsset> implements PortalDao {

    @SuppressWarnings("unchecked")
    @Override
    public List<PortalAsset> findAllAssets() {
        //      Query query = getSession().createSQLQuery(
        //              "select id,CSC_ASSET_TAG,SERIAL_NO,IBM_ASSET_TAG from sgh_assets where CSC_ASSET_TAG like :term");
        //      query.setString("term", "%gwls1208%");
        Criteria criteria = getSession()
                .createCriteria(PortalAsset.class)
                .setMaxResults(20)
                .setProjection(
                        Projections.projectionList().add(Projections.property("id"), "id")
                                .add(Projections.property("ctcassettag"), "ctcassettag")
                                .add(Projections.property("serialno"), "serialno")
                                .add(Projections.property("ibmassettag"), "ibmassettag")
                                .add(Projections.property("block"), "block")
                                .add(Projections.property("level"), "level").add(Projections.property("room"), "room"))
                .setResultTransformer(Transformers.aliasToBean(PortalAsset.class));
        return (List<PortalAsset>) criteria.list();
    }
}

Hibernate configuration
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.span.vms.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    @Primary
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.span.vms.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    @Qualifier("eportalSessionFactory")
    public LocalSessionFactoryBean eportalSessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(eportalDataSource());
        sessionFactory.setPackagesToScan(new String[] { "org.ctc.pm.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public DataSource eportalDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.eportal.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.eportal.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.eportal.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }
}

Service Implementation
@Service("portalService")
public class PortalServiceImpl implements PortalService {
    @Autowired
    private PortalDao dao;

    @Override
    public List<PortalAsset> findAllAssets() {
        return dao.findAllAssets();
    }

}

Service Interface
public interface PortalDao {
    List<PortalAsset> findAllAssets();
}

When I run List<PortalAsset> assets = portalService.findAllAssets(); I am getting no session for current thread error where the primary datasource is working fine. What is the mistake I did?

A: Inside your hibernate configuration file it should be..
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.span.vms.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    @Primary
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.span.vms.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean(name = "eportalSessionFactory")
    public LocalSessionFactoryBean eportalSessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(eportalDataSource());
        sessionFactory.setPackagesToScan(new String[] { "org.ctc.pm.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public DataSource eportalDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.eportal.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.eportal.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.eportal.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean(name = "txManager1")
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory());
        return txManager;
    }

    @Bean(name = "txManager2")
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(eportalSessionFactory());
        return txManager;
    }

and In service layer, at @Transactional annotation specify the name of transaction manager which you want to use.


text:
Q: How to make points with fixed distance and orientation from another points layer? I have a points layer with hundreds of features at variable distance from each other. Now what I want to do is create 4 new points for each feature of this layer at a fixed distance (30m) AND orientation (exactly North, East, South, West).
Something like this (forgive my draw skills):

Where grey points are from input and the color ones are the output.
I was willing to do in QGIS, but can be also PostGIS or another solution.

A: The desired result can be achieved both in QGIS and PostGIS, and I will offer a method in QGIS in SRID 4326.
1) Run the "Rectangles, ovals, rhombus (fixed)" tool and set the values specified in the fields, see figure 1.

2) Extract from all the obtained rhombuses of the point, for which run Vector> Geometry processing> Extract vertices ... see figure 2.

3) See the result in figure 3.


text:
Q: Why are we interested in how long it takes to sort a file that is already sorted? This is asked in google interview  I didn't get the answer. Even worse didn't got the question.
When discussing sorting algorithms we talk about the behavior on files that are already sorted. Why are we interested in how long it takes to sort a file that is already sorted?  Explain your answer briefly ?

A: The question is basically:

Why do we care how a sorting algorithm will behave on an input which is already sorted?

Long story short, files tend to be sorted with higher probability than the "expected" of 1/n! that is assuming the file is randomly permuted1.
Here are two use cases where we care a lot for the performance of the algorithm if the array/file is already sorted:

*

*Users (of API) don't tend to check if their file is already sorted before using the API and sorting it again, and since the probability of it to be already sorted is not that slim (because someone already sorted it at some point), this worst case behavior is not something that is unlikely to happen. This will make "our" API slowish comparing to our competitors who do care about it.

*If we know how it works on a sorted file, it will most likely behave similarly on an almost sorted file, and again - this input is even more likely. Assume a user has a file, appends some entries to it, and send it to the sorting algorithm again - the file is almost sorted, and the performance will be very close to the one expected on sorted ones.

Foot notes:
(1) It's an empirical fact due to the nature of incremental processing, a mathematical support is: A file that is randomly generated has a probability of 1/n! to be already sorted. Assume there is some probability p that the file was sorted since last update. It means that the probability of it being sorted is not 1/n! anymore, it is p + (1-p)1/n!. Assuming p>0, it means the probability for the file to be already sorted is higher than the probability of other files.

A: Assuming the question was about the behavior on input that is already sorted (not necessarily files), different sorting algorithms behave differently when they receive already sorted input:

*

*in case of Insertion sort, you will get best case, i.e. O(n)

*in case of Quicksort implementation without randomization, already sorted input will cause worst case! (O(n^2))

These two simple examples show that you have to include the behavior of the sorting algorithm on the already sorted input in your algorithm analysis.
The main reason is that in practical applications, user's input tends to come in sorted or almost sorted form, some examples:

*

*almost-chronological data - data that is received in chronological order, but occasionally some elements are out of position (see link below)

*natural ordering - when you increase your database of users, you will probably assign higher id to the new user

See also:

*

*Worst case for Quicksort - when can it occur?

A: Most real world data are not uniformly randomly distributed, but rather they're usually almost sorted. If a sorting algorithm always take O(nlog(n)) even when the data is nearly sorted, then it wouldn't perform as well with real world data.
For example sorting a log file based on the datetime entry in the log. As log entries are created while the events happens, most of the log entries would be close to where they should be, with just a few that are out of place due to concurrent writes. A log file can be extremely large, on the order of gigabytes or more, so a sorting algorithm that doesn't take advantage of the near sorted state of the log file is not as efficient as it should be.
Another case with log files, in a distributed system, multiple systems can produce log entries concurrently. The individual log file itself is sorted (or nearly sorted) but you'd want to merge the multiple log files into a single linear log file containing all the events in all systems. You can just concatenate all the logs and if the sorting algorithm recognizes that most of the data have wide spans of already sorted entries, it can do a much more efficient O(n) merge operation rather than an O(nlog(n)) sort.

A: I will give another example. Most bank transactions are almost sorted, as people like to receive their bank statements in order of their check numbers. People write checks in order by check number and traders cash them accordingly. So the problem of converting a time of transaction ordering is again an example of sorting an always sorted input.
One of the most widely used sorting technique is quicksort. However quicksort performs very poorly when the input is sorted. When the input data is sorted it approaches a time complexity of O(n^2). This is not good so we go for randomization. Either we randomly arrange the data elements or randomly choose a pivot (median of three). This is done so that the input data set will not matter. There is no bad ordering of the input data. Of course, if your randomization causes the input data set to be sorted then it is just you being unlucky. The running  time in such a randomized quick sort algorithm is now independent of input ordering. The expected run time of the randomized quick sort is O(nlogn).


text:
Q: Which STD container to use to get [] operator and erase elements without moving memory around? I used std::vector<MyClass> and everything was fine until I had to use erase() function. Problem caused by MyClass having
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;

This is needed because MyClass holds unique_ptr objects and I generally want to avoid copy. But at this point my code has index access [] operator utilized, and I dont want to re write chucks of code. Is there a container in STD that is suitable?
Edit:
To people suggesting usage of move constructor, I've tried this:
//MyClass(const MyClass&) = delete;
//MyClass& operator=(const MyClass&) = delete;
MyClass(MyClass&&) = default;

but compiler(g++) still gives error:
/usr/include/c++/11/bits/stl_algobase.h:405:25: error: use of deleted function 'M::MyClass& M::MyClass::operator=(const M::MyClass&)'
  405 |               *__result = std::move(*__first);
      |               ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~

saying:
note: 'M::MyClass& M::MyClass::operator=(const M::MyClass&)' is implicitly declared as deleted because 'M::MyClass' declares a move constructor or move assignment operator

or I should not use default keyword and actually define move constructor?

A: As std::unique_ptr<T> is a moveable and non-copyable type, any class with a std::unique_ptr<T> member will by default be moveable and non-copyable (as long as all of the other members are at least moveable).
#include <memory>
#include <utility>

struct A {
    std::unique_ptr<int> ptr;
};

int main()
{
    A a;
    //A b = a; //Will not compile
    A c = std::move(a); // Perfectly legal
}

Therefore if you remove the copy contstructor, copy assignment operator, move constructor, and move assignment operator, then everything would work fine. Your type would not be copyable, and erasing from std::vector would work fine.
Note: std::vector<T>::operator[] returns a reference to the element so no copy is performed at this step either (for T not equal to bool).
If you want to explicitly = delete the copy semantics then you also have to = default both the move constructor and move assignment operator to keep the move semantics of the type. This is known as the rule of 5.


text:
Q: Responsive Carousel Issue - prependTo Jumps I am trying to do the responsive carousel which should proportionally hide last item on screen re-size. In the code below everything works fine and does what I want, except one thing. When slide is moving item disappears and quickly appears back the next one in the row. I need to put one item on background and make it invisible somehow, but I could not find the way to do it not loosing centered position of all items.
HTML

                slide1

                slide2

                slide3

                slide 4

PREV

NEXT

CSS
#slider-wrapper {
    position: relative;
    margin: 50px auto;
    overflow: hidden;
    text-align: center;
    width: 100%;
    height:200px;
}
#slider-wrapper .slider {
    position: relative;
    width: 100%;
}
#slider-wrapper .slide {
    position: relative;
    display: inline-block;
    width: 250px;
    height:200px;
}
.item{
    line-height: 200px;
    background: pink;
}
.item.alt{
    line-height: 200px;
    background: red;
}
#controls{
    position: relative;
    height: 50px;
    width: 220px;
    margin: 0 auto;
}
#controls div{
    position: absolute;
    height: 50px;
    width: 100px;
    background: grey;
    color: white;
    text-align: center;
    line-height: 50px;
}
#next{
    margin-left: 120px;
}

JQuery
var slider = function(){
    var slideWidth = $('.slide').width();

    $('.slide:last-child').prependTo('.slider');
        function moveLeft() {
        $('.slider').animate({
            left: + slideWidth
        }, 200, function () {
            $('.slide:last-child').prependTo('.slider');
            $('.slider').css('left', '');
        });
    };
    function moveRight() {
        $('.slider').animate({
            left: - slideWidth
        }, 200, function () {
            $('.slide:first-child').appendTo('.slider');
            $('.slider').css('left', '');
        });
    };
        $('#prev').on("click",function(){
        moveRight();
    });
    $('#next').on("click",function(){
        moveLeft();
    });
}
$(document).ready(function(){
    slider();
});

Here also a JSFiddle example https://jsfiddle.net/Lv64275r/2/


text:
Q: Pasar variables de una clase a otra (JFrame) estudio desarrollo de software  y de un semestre a otro nos cambiaron el lenguaje de programación (C# -> Java) Para adaptarnos, nos ponen programas sencillos pero tuve un problema con uno que no se como resolverlo. A veces tengo problemas al comprender clases y mi problema es que intento pasar unas variables que se calculan en la clase principal (Que se ejecuta en consola) a otra clase (que ya es un JFrame) pero la verdad no sé como (no se si fijar las variables como propiedades de la clase o instanciando la clase del jframe, la verdad no se)
public static void main(String[] args) {
    // Inicio declaracion de variables
    Scanner scan = new Scanner(System.in);
    int clientes[] = new int[20];
    int op, i = 0;
    String val1="",val2="",val3="",val4="",val5="";
    //Fin declaracion de variables
    //Inicio de mensajes
    mensaje("Bienvenido a la cafeteria estudiantil!");
    mensaje("");
    mensaje("Porfavor, califique nuestro servicio con la siguiente escala");
    mensaje("");
    mensaje("");
    mensaje("--- 1. Pesimo ---");
    mensaje("--- 2. Regular ---");
    mensaje("--- 3. Bueno ---");
    mensaje("--- 4. Muy bueno ---");
    mensaje("--- 5. Excelente ---");
    mensaje("");
    //Fin de mensajes
    //Inicio de captura de datos
    do{
        String men = JOptionPane.showInputDialog("Cliente numero "+(i+1)+" ¿Cual es su opinion?");
        clientes[i] = Integer.parseInt(men);
        //Si el usuario pone un numero que no sea 1-5 No sumará nada el contador i ni asignará valores, solo mandara un mensaje de error
        if(clientes[i] == 1 || clientes[i] == 2 || clientes[i] == 3 || clientes[i] == 4 || clientes[i] == 5){
            op = clientes[i];
            i++;
            switch(op){
                case 1:
                    val1+="*";
                    break;
                case 2:
                    val2+="*";
                    break;
                case 3:
                    val3+="*";
                    break;
                case 4:
                    val4+="*";
                    break;
                case 5:
                    val5+="*";
                    break;
            }
        } else { //Este es el mensaje de error que va a mandar
            mensaje("");
            mensaje("Porfavor, introduzca una opcion valida e intentelo de nuevo");
            mensaje("");
        }
    } while(i < clientes.length); //Se repite el bucle hasta que pasen los 20 alumnos
    //Mensajes con los resultados finales
    mensaje("");
    mensaje("Estos son los resultados de la encuesta:");
    mensaje("");
    mensaje("");
    mensaje("--- 1. Pesimo --- |" + val1+"|");
    mensaje("--- 2. Regular --- |" + val2+"|");
    mensaje("--- 3. Bueno --- |" + val3+"|");
    mensaje("--- 4. Muy bueno --- |" + val4+"|");
    mensaje("--- 5. Excelente --- |" + val5+"|");
    mensaje("");
    mensaje("En total se entrevistó a "+ clientes.length + " estudiantes");
    Salida sal = new Salida();
    sal.setTitle("RESULTADO");
    sal.show();

}

static void mensaje(String mens){ //Metodo para evitar escribir todo el choro de System.out.println sustituyendolo por mensaje("mensaje");
    System.out.println(mens);
}

}`
Y la clase del JFrame es esta
public class Salida extends javax.swing.JFrame {

/**
 * Creates new form Salida
 */
public Salida() {
    initComponents();

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    lblTexto1 = new javax.swing.JLabel();
    lblTexto2 = new javax.swing.JLabel();
    lblTexto3 = new javax.swing.JLabel();
    lblTexto4 = new javax.swing.JLabel();
    lblTexto5 = new javax.swing.JLabel();
    lblTexto6 = new javax.swing.JLabel();
    lblPesimo = new javax.swing.JLabel();
    lblRegular = new javax.swing.JLabel();
    lblBueno = new javax.swing.JLabel();
    lblMuyBueno = new javax.swing.JLabel();
    lblExcelente = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    lblTexto1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblTexto1.setText("2. Regular");

    lblTexto2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblTexto2.setText("1. Pesimo");

    lblTexto3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblTexto3.setText("3. Bueno");

    lblTexto4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblTexto4.setText("4. Muy bueno");

    lblTexto5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblTexto5.setText("5. Excelente");

    lblTexto6.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
    lblTexto6.setText("Valoracion final");

    lblPesimo.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblPesimo.setText("||");

    lblRegular.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblRegular.setText("||");

    lblBueno.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblBueno.setText("||");

    lblMuyBueno.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblMuyBueno.setText("||");

    lblExcelente.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblExcelente.setText("||");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(148, 148, 148)
                    .addComponent(lblTexto6, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(lblTexto2)
                        .addComponent(lblTexto1)
                        .addComponent(lblTexto3)
                        .addComponent(lblTexto4)
                        .addComponent(lblTexto5))
                    .addGap(35, 35, 35)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(lblExcelente)
                        .addComponent(lblMuyBueno)
                        .addComponent(lblBueno)
                        .addComponent(lblRegular)
                        .addComponent(lblPesimo))))
            .addContainerGap(153, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(lblTexto6)
            .addGap(62, 62, 62)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblTexto2)
                .addComponent(lblPesimo))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblTexto1)
                .addComponent(lblRegular))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblTexto3)
                .addComponent(lblBueno))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblTexto4)
                .addComponent(lblMuyBueno))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblTexto5)
                .addComponent(lblExcelente))
            .addContainerGap(74, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Salida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Salida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Salida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Salida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Salida().setVisible(true);
        }
    });
}

// Variables declaration - do not modify
private javax.swing.JLabel lblBueno;
private javax.swing.JLabel lblExcelente;
private javax.swing.JLabel lblMuyBueno;
private javax.swing.JLabel lblPesimo;
private javax.swing.JLabel lblRegular;
private javax.swing.JLabel lblTexto1;
private javax.swing.JLabel lblTexto2;
private javax.swing.JLabel lblTexto3;
private javax.swing.JLabel lblTexto4;
private javax.swing.JLabel lblTexto5;
private javax.swing.JLabel lblTexto6;
// End of variables declaration

}

A: Para pasar datos de entre Jframe necesitas tener la variable de tipo publico estatico; en en este ejemplo es Jlabel
public static final JLabel jLabel1 = new JLabel();

Lo siguiente tienes que hacer es llamar al metodo del jlabel1 para colocar los datos que quieres enviar en este caso j1 que es el frame.
Jframe1 j1 = new Jframe1();
j1.jLabel1.setText("dato a pasar");

Espero te sirva de algo este aporte!


text:
Q: Python xml.etree formatting beautify? I got a script that uses xml.etree.ElementTree to parse an XML-file and is supposed to add a child to an element. I have two approaches, that both work technically but both result in messed up formatting/whitespace when I dump the whole xml using ET.dump(root)
First method I use fromstring
import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

#snip

newgroup='''
    <group>
        <uuid>%s</uuid>
        <id>%s</id>
        <name>%s</name>
        <desc>%s</desc>
    </group>
''' % (g_uuid, g_id, g_name, g_desc)

access = root.find('access')
access.append(ET.fromstring(newgroup))

This results in the group being added as a child, but after endtag of group is no newline and the first tag only has 1 tab, no matter how many tabulators I put into the newgroup string.
<group>
        <uuid>f60e6b30-eec9-11e6-a5d4-2c768aabceca</uuid>
        <id>2</id>
        <name>newgroup</name>
        <desc>Testing groups</desc>
    </group></access>

I wonder why it takes the whitespaces correctly for the childs of group but messes up the formatting of the group tags itself.
Second method was building an etree of the group with it's children
newgroup = ET.Element('group')
ET.SubElement(newgroup, 'uuid').text = '%s' % g_uuid
ET.SubElement(newgroup, 'id').text = '%s' % g_id
ET.SubElement(newgroup, 'name').text = '%s' % g_name
ET.SubElement(newgroup, 'desc').text = '%s' % g_desc

access = root.find('access')
access.append(newgroup)

But then the whole newgroup-tree appears in a single line without newlines and tabs at all:
<group><uuid>f60e6b30-eec9-11e6-a5d4-2c768aabceca</uuid><id>2</id><name>newgroup</name><desc>Testing groups</desc></group></access>

I am new to python and don't really know how to format strings. So how can I beautify this thing so that I get well formatted XML out of the script?

A: Use any approach to create your XML without any worrying about formatting, and then just use universal indent function like this on your root element:
def indent(elem, level=0, hor='\t', ver='\n'):
    i = ver + level * hor
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + hor
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level + 1, hor, ver)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

Another solution is use the lxml third-party library, that already has similar effect when writing to a file with keyword argument pretty_print=True. By the way, this is almost non-configurable approach. So, with custom indent functions you may configure any behavior you want learning on this example.


text:
Q: Rails Heroku Migrate Unknown Error I am trying to get my app up and running on heroku.  However once I go to migrate I get the following error:
$ heroku rake db:migrate --trace
rake aborted!
An error has occurred, this and all later migrations canceled:

530 5.7.0 Must issue a STARTTLS command first. f5sm3554179qcg.2
/usr/local/lib/ruby/1.8/net/smtp.rb:576:in `auth_plain'
/usr/local/lib/ruby/1.8/net/smtp.rb:570:in `__send__'
/usr/local/lib/ruby/1.8/net/smtp.rb:570:in `authenticate'
/usr/local/lib/ruby/1.8/net/smtp.rb:410:in `do_start'
/usr/local/lib/ruby/1.8/net/smtp.rb:377:in `start'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.5/lib/action_mailer/base.rb:6
82:in `perform_delivery_smtp'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.5/lib/action_mailer/base.rb:5
23:in `__send__'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.5/lib/action_mailer/base.rb:5
23:in `deliver!'
/usr/local/lib/ruby/gems/1.8/gems/actionmailer-2.3.5/lib/action_mailer/base.rb:3
95:in `method_missing'
/disk1/home/slugs/155328_71d8f62_845e/mnt/app/models/user_observer.rb:3:in `afte
r_create'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/observer.
rb:171:in `send'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/observer.
rb:171:in `update'
/usr/local/lib/ruby/1.8/observer.rb:185:in `notify_observers'
/usr/local/lib/ruby/1.8/observer.rb:184:in `each'
/usr/local/lib/ruby/1.8/observer.rb:184:in `notify_observers'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/callbacks
.rb:357:in `notify'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/callbacks
.rb:350:in `callback'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/callbacks
.rb:267:in `create'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2
874:in `create_or_update_without_callbacks'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/callbacks
.rb:250:in `create_or_update'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2
538:in `save_without_validation'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/validatio
ns.rb:1078:in `save_without_dirty'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/dirty.rb:
79:in `save_without_transactions'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:229:in `send'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:229:in `with_transaction_returning_status'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connectio
n_adapters/abstract/database_statements.rb:136:in `transaction'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:182:in `transaction'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:228:in `with_transaction_returning_status'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:196:in `save'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:208:in `rollback_active_record_state!'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:196:in `save'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:7
23:in `create'
./db/migrate//20080929171348_bort_migration.rb:67:in `up_without_benchmarks'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:282:in `send'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:282:in `migrate'
/usr/local/lib/ruby/1.8/benchmark.rb:293:in `measure'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:282:in `migrate'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:365:in `__send__'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:365:in `migrate'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:486:in `migrate'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:560:in `call'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:560:in `ddl_transaction'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connectio
n_adapters/abstract/database_statements.rb:136:in `transaction'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/transacti
ons.rb:182:in `transaction'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:560:in `ddl_transaction'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:485:in `migrate'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:472:in `each'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:472:in `migrate'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:400:in `up'
/usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/migration
.rb:383:in `migrate'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/databases.rake:116
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:636
:in `call'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:636
:in `execute'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:631
:in `each'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:631
:in `execute'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:597
:in `invoke_with_call_chain'
/usr/local/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:590
:in `invoke_with_call_chain'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:583
:in `invoke'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:205
1:in `invoke_task'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:202
9:in `top_level'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:202
9:in `each'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:202
9:in `top_level'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:206
8:in `standard_exception_handling'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:202
3:in `top_level'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:200
1:in `run'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:206
8:in `standard_exception_handling'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/lib/rake.rb:199
8:in `run'
/home/slugs/155328_71d8f62_845e/mnt/.bundle/gems/gems/rake-0.8.7/bin/rake:31
/usr/local/bin/rake:19:in `load'
/usr/local/bin/rake:19
(in /disk1/home/slugs/155328_71d8f62_845e/mnt)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
==  BortMigration: migrating ==================================================
-- create_table(:sessions)
   -> 0.0197s
-- add_index(:sessions, :session_id)
   -> 0.0114s
-- add_index(:sessions, :updated_at)
   -> 0.0125s
-- create_table(:open_id_authentication_associations, {:force=>true})
   -> 0.0244s
-- create_table(:open_id_authentication_nonces, {:force=>true})
   -> 0.0241s
-- create_table(:users)
   -> 0.0658s
-- add_index(:users, :login, {:unique=>true})
   -> 0.0094s
-- create_table(:passwords)
   -> 0.0141s
-- create_table(:roles)
   -> 0.0237s
-- create_table(:roles_users, {:id=>false})
   -> 0.0029s

I'm not sure exactly what it means.  Or really what it means at all. Could it have to do with my Bort installation? I did remove all the open-id stuff from it.  But I never had any problems with my migrations locally. Additionally on Bort the Restful Authentication uses my gmail stmp to send confirmation emails...all the searches on google i do on STARTTLS have to do with stmp.  Can someone point me in the right direction?

A: Are you using GMail for sending email?
If you ae using Gmail, there are some extra steps you need to go through as detailed in the Heroku Docs and this blog post.

A: On development environment maybe you can add:
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => 'localhost:3000' }

to the file  config/enviroments/development.rb


text:
Q: Select2 jQuery CSS changing, on page render.(laravel 5.7 project) In my laravel project version 5.7, I have a home_admin page in which I use four select dropdown inputs with some CSS custom, and in my home.js I initialize them with the select2 function from select2 jQuery library v.4.0.10 CDNS. So when the page renders, within seconds loading firstly the custom CSS and then changes to select 2 default CSS.
What can I do, so as to have only my CSS?


text:
Q: Spring - how to exclude a particular URL from spring Controller? May be this question has an answer already.But that is an accepted answer.Because it works in web servers only.
My web.xml will be ,
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

I want to exclude the hello.html from the spring controller.
Also that thing should be work on all servers like tomcat,Jboss,websphere etc..
Is it possible ?Hope I will get a good solution.

A: How about just creating a new server-mapping point that points to the default servlet before the spring mapping?
<servlet-mapping>
    <servlet-name>Default</servlet-name>
    <url-pattern>hello.html</url-pattern>
</servlet-mapping>

Should work for tomcat but possibly it will work for other servers as well.


text:
Q: Oh My Zsh Theme only works after reloading I am creating a custom zsh theme. Below is the code from the theme file. That part that I am concerned with is the part modifying the git_branch variable.
if [[ $USER = "vivek" ]]; then
    local user='%{$terminfo[bold]$fg[red]%}vivek%{$reset_color%}'
else
    local user='%{$terminfo[bold]$fg[green]%}tamil%{$reset_color%}'
fi

local current_dir='%{$terminfo[bold]$fg[blue]%} %~%{$reset_color%}'

local git_branch=''
if [[ -d .git ]]; then
    git_branch='some text $(git_prompt_info)%{$reset_color%}'
fi

PROMPT="╭─${user} ${current_dir} ${git_branch}
╰─%B$%b "
RPS1="${return_code}"

ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg[yellow]%}‹"
ZSH_THEME_GIT_PROMPT_SUFFIX="› %{$reset_color%}"

For some reason the git_branch only gets updated if I call zsh when I am in a directory with git initialized. It doesn't get reloaded automatically when I switch directories or when I first open zsh shell.
Can someone help explain why this is happening?


text:
Q: Determining north using the android phone I looked over SensorManager and was still unsure, how do I detect if the phone is looking at true north (or any other direction for that matter).

A: If you are just looking for a sample, the publishers of Professional Android 2 Application Development have all their example code available for download and there is a compass application in chapter 14.


text:
Q: Call Django API running on a server from Angular running locally I am learning with Django and Angular.
I have setup a Django API back-end on on http://serverip:8666/athletics/
I have created a small Angular application that I am running from my local machine.
The following code in my Angular app:
$scope.list_athletes = function(){

    console.log('hey');

    $http
        .get('http://serverip:8666/athletics/')
        .success(function (result) {

            console.log('success');

        })

}

generates the error:

XMLHttpRequest cannot load http://serverip:8666/athletics/. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://127.0.0.1:65356' is therefore not allowed
  access.

What causes this error? How can I resolve it so that I can access the Django API from my local Angular app?

A: The problem you're having is related to not having CORS enabled.
As a security policy, JavaScript can't make requests across domains while running in your browser. This is meant to prevent untrusted code from executing without the user's knowledge. The workaround is to enable CORS by white listing domains.
You need to set the Access-Control-Allow-Origin response header in your responses like so:
def my_view(request):
    data = json.dumps({'foo':'bar'})
    response = HttpResponse(data)
    response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:65356'
    return response

This will enable CORS for your angular app. You can even add django-cors-headers to your project to have this functionality implemented for you. This can be added to any Django response object, such as django.http.repsonse.HttpResponse. Because you appear to be using a DRF Response object, you may need to use something like
return Response(serializer.data, headers={'Access-Control-Allow-Origin': 'http://127.0.0.1:65356'})

to set your response headers.
You should also check out this site for more information on how to enable CORS in your webapp.

A: Have you done the settings part in settings.py
INSTALLED_APPS = (
    'corsheaders',
)
MIDDLEWARE_CLASSES = (
    'corsheaders.middleware.CorsMiddleware',
)
CORS_ORIGIN_WHITELIST = (
  'http://127.0.0.1:65356'
)

And also include CORS_ALLOW_CREDENTIALS, CORS_ALLOW_HEADERS settings


text:
Q: How can I configure the layers of the neruonal network to generate a 400x400 image? Hello I am starting in the world of neural networks, I have taken as a total basis the example of the book "Python Deep Learning" from the publisher Marcombo, in this a Generative Adversarial Networks is generated based on an example of the book, the following was developed code
# Esta es la linea original
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
# se reemplazo por la siguiente linea
train_images = train_images.reshape(train_images.shape[0], 400, 400, 1).astype('float32')

train_images = (train_images - 127.5) / 127.5 # esta linea normaliza de -1 a 1 los datos

BUFFER_SIZE = 60000
BATCH_SIZE = 256
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Reshape, Conv2DTranspose, BatchNormalization, LeakyReLU

def make_generator_model():
    model = Sequential()
    model.add(Dense(7*7*256, use_bias=False, input_shape=(100,)))

    model.add(Reshape((7, 7, 256)))

    model.add(Conv2DTranspose(128, (5, 5), strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(LeakyReLU(alpha=0.01))

    model.add(Conv2DTranspose(64, (5, 5), strides=(1, 1), padding='same'))
    model.add(BatchNormalization())
    model.add(LeakyReLU(alpha=0.01))

    model.add(Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', activation='tanh'))

    return model
generator = make_generator_model()
generator.summary ()

noise_dim = 100
noise = tf.random.normal([1, noise_dim])
generated_image = generator(noise, training=False)

plt.imshow(generated_image[0, :, :, 0], cmap='gray')

This generates a noise image that will be trained until it looks like the training image, "train_images", the original data of the example is from a 28x28 image, my intention is to use data from an image that is 400x400 that has already been loaded successfully but when it tries to load the image it tells me that it is not possible.
---------------------------------------------------------------------------
ResourceExhaustedError                    Traceback (most recent call last)
<ipython-input-14-73ddb44f2cff> in <module>()
    182 if __name__ == "__main__":
    183     execute = Read()
--> 184     execute.read()

4 frames
/usr/local/lib/python3.7/dist-packages/keras/backend.py in random_uniform(self, shape, minval, maxval, dtype)
   1831     return tf.random.uniform(
   1832         shape=shape, minval=minval, maxval=maxval, dtype=dtype,
-> 1833         seed=self.make_legacy_seed())
   1834
   1835   def truncated_normal(self, shape, mean=0., stddev=1., dtype=None):

ResourceExhaustedError: OOM when allocating tensor with shape[100,2560000] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [Op:RandomUniform]

My specific intention is to generate a noise image of size 400x400 so that it can be trained with an image that measures 400x400
How can I configure the layers of the neruonal network to generate a 400x400 image?
All the cited code was taken from the book "Python Deep Learning" by Jordi Torres.

A: In your error messege "OOM" is mentioned wich means out of memory. This messege occurs when you try to allocate more data on your GPU as is available. You have the following options:

*

*decrease the batch size

*reduce the spatial dimensions of your data

*Use GPU with more memory.


text:
Q: How to create a new smaller array from a larger array, taking the average of the old array's elements? Lets say I have an array of length n:
a = np.arange(1, 20, 0.5).tolist()

I want to create a new array of a smaller size of length m, where m < n, and fill this array with the average values of the older array. For example, array a is 38 in length, but I want to create array b of length 15. The first element of b would be the average value of the first two or three elements in a.
Another example: if I had a vector of length 1491 and wanted to reshape it to an array of length 200, 1491 cannot be perfectly divided by 200 right? The same is true if array a was 4442 but array b was still 200, a different number of values will be needed to get the average values to put into b this time.
Is there a suitable way to do this?

A: If for example you have array of size 20 a = np.arange(20) then you can reshape it to new 2D shape a = a.reshape(10, 2), second dimension says how many consequent numbers you want to average, in my example you average each 2 consequent numbers, then you compute average reducing 2nd dimension a = a.mean(axis = 1) thus having resulting array of size 10. Full code:
Try it online!
import numpy as np
a = np.arange(20)
print(a)
a = a.reshape(10, 2)
a = a.mean(axis = 1)
print(a)

Output:
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
[ 0.5  2.5  4.5  6.5  8.5 10.5 12.5 14.5 16.5 18.5]

If you for some reason have such b size that a size is not divisible evenly by b size, then you can do next thing - some elements on the left group in blocks of size a_size // b_size + 1 and some on the right in blocks of size a_size // b_size. Next code does this computation (example input a size is 18, desired b size is 5):
Try it online!
import numpy as np
a = np.arange(18)
b_size = 5
print('a =', a)
# bl = a.size // b_size
# l + r = b_size
# l * (bl + 1) + r * bl = a_size
# l = a_size - b_size * bl
bl = a.size // b_size
l = a.size - b_size * bl
r = b_size - l
print('a_size =', a.size, 'b_size =', b_size, 'left =', l,
    'right =', r, 'block_left =', bl + 1, 'block_right =', bl)
assert l * (bl + 1) + r * bl == a.size
al, ar = a[:l * (bl + 1)], a[l * (bl + 1):]
al = al.reshape(l, bl + 1)
ar = ar.reshape(r, bl)
b = np.concatenate((al.mean(axis = 1), ar.mean(axis = 1)))
print('b =', b)

Output:
a = [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17]
a_size = 18 b_size = 5 left = 3 right = 2 block_left = 4 block_right = 3
b = [ 1.5  5.5  9.5 13.  16. ]


text:
Q: How to to list array values that are equal or greater to user inputed value I'm looking to write javascript code that creates an integer array of numbers, prompts the user to input a minimum number (minNumber), and then display the values in the array that are equal to or higher than minNumber input. I was able to do almost all of that in the code below, but it displayed all of the array's values instead of just displaying the values that are equal to or higher than minNumber, as I originally intended. I would like to keep the basic formatting with the function etc, but can you please advise what i can add to my code to achieve the desired result? Thanks so much
function arrayFunction(arrayOne, minNumber) {
  for (var number = 0; number <= arrayOne.length; number++) {
    if (arrayOne[number] >= minNumber) {
      document.write("The array numbers starting from minNumber are " + arrayOne[number] + " ");
      return arrayOne.slice(number, arrayOne.length);
    }
  }
  return;
}

const NEW_LINE = "
";       // This is like one ENTER key-press
const NEW_PARAGRAPH = "
";   // This is like two ENTER key-presses

let arrayOne = [10, 20, 30, 40, 50];
var minNumber = parseInt(prompt("Enter in the min. number"));
let array = arrayFunction(arrayOne, minNumber);

document.write(array);

A: You've essentially written the Array Filter method.
The problem is with the return statements. You need to return the array after to loop has completed rather than in it.
If you prefer to skip all the code you can simply use filter():

let arrayOne = [10, 20, 30, 40, 50];
var minNumber = parseInt(prompt("Enter in the min. number"));
let array = arrayOne.filter(item => item >= minNumber);
console.log(array);

document.getElementById('output').textContent = array;

A: arrayOne.filter((val) => val >= minNumber);

Just put this line in with return in the function.


text:
Q: Why "continue" is considered as a C violation in MISRA C:2004? MISRA 14.5 says continue statement must not be used. Can anyone explain the reason?
Thank you.

A: Programming in C makes it notoriously hard to keep track of multiple execution branches. If you allocate resources somewhere, you have to release them elsewhere, non-locally. If your code branches, you will in general need to have separate deallocation logic for each branch or way to exit a scope.
The continue statement adds another way to exit from the scope of a for loop, and thus makes such a loop harder to reason about and understand all the possible ways in which control can flow through it, which in turn makes it harder to ascertain that your code behaves correctly in all circumstances.
This is just speculation on my part, but I imagine that trying to limit complexity coming from this extra branching behaviour is the driving reason for the rule that you mention.

A: I've just run into it. We have items, which

*

*should be checked for several things,

*checks require some preparation,

*we should apply cheap checks first, then go with expensive ones,

*some checks depends others,

*whichever item fails on any check, it should be logged,

*if the item passes all the checks, it should be passed to further processing.

Watch this, without continue:
foreach (items) {

   prepare check1
   if (check1) {

      prepare check2
      if (check2) {

        prepare check3
        if (check3) {
          log("all checks passed")
          process_good_item(item)
        } else {
          log("check3 failed")
        }

      } else {
        log("check2 failed")
      }

   } else {
      log("check 1 failed")
   }
}

...and compare with this, with continue:
foreach (items) {

   prepare check1
   if (!check1) {
      log("check 1 failed")
      continue
   }

   prepare check2
   if (!check2) {
      log("check 2 failed")
      continue
   }

   prepare check3
   if (!check3) {
      log("check 3 failed")
      continue
   }

   log("all checks passed")
   process_good_item(item)
}

Assume that "prepare"-s are multiple line long each, so you can't see the whole code at once.
Decide yourself, which is

*

*less complex, have a simpler execution graph

*have lower cyclomatic complexity value

*more readable, more linear, no "eye jumps"

*better expandable (e.g. try to add check4, check5, check12)

IMHO Misra is wrong in this topic.

A: It is because of the ancient debate about goto, unconditional branching and spaghetti code, that has been going on for 40 years or so. goto, continue, break and multiple return statements are all considered more or less equally bad.
The consensus of the world's programming community has roughly ended up something like: we recognize that you can use these features of the language without writing spaghetti code if you know what you are doing. But we still discourage them because there is a large chance that someone who doesn't know what they are doing are going to use the features if they are available, and then create spaghetti. And we also discourage them because they are superfluous features: you can obviously write programs without using them.
Since MISRA-C is aimed towards critical systems, MISRA-C:2004 has the approach to ban as many of these unconditional branch features as possible. Therefore, goto, continue and multiple returns were banned. break was only allowed if there was a single break inside the same loop.
However, in the "MISRA-C:2011" draft which is currently under evaluation, the committee has considered to allow all these features yet again, with a restriction that goto should only be allowed to jump downwards and never upwards. The rationale from the committee said that there are now tools (ie static analysers) smart enough to spot bad program flow, so the keywords can be allowed.
The goto debate is still going strong...

A: As with all MISRA rules, if you can justify it, you can deviate from the rule (section 4.3.2 of MISRA-C:2004)
The point behind MISRA (and other similar guidelines) is to trap the things that generally cause problems... yes, continue can be used properly, but the evidence suggested that it was a common cause of problem.
As such, MISRA created a rule to prevent its (ab)use, and the reviewing community approved the rule. And the views of the user community are generally supportive of the rule.
But I repeat, if you really want to use it, and you can justify it to your company hierarchy, deviate.


text:
Q: MouseEvent Listeners/EventTypes for TreeItems Basically, I have a TreeView
TreeView<String> treeView = new TreeView<String>();

The root
TreeItem<String> root = new TreeItem<String>();
treeView.setRoot(root);

And lastly an item inside the root
TreeItem<String> item1 = new TreeItem<String>();
root.getChildren().add(item1);

(With or without more siblings or adding more children to item1)
And what I want to do is add a listener or EventHandler specifically for item1 (and any siblings) so when a user double clicks on it or changes its value, something happens. I also want to know if there are any of these that show the oldValue and newValue of the TreeItem when it is edited.
The only leads I really have are that it probably has to do with using:
root.getChildren().addListeners()...
treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener...

or
item1.addEventHandler(...

Any help is very appreciated!

A:
I also want to know if there are any of these that show the oldValue and newValue of the TreeItem when it is edited.

Are you just looking for
item1.valueProperty().addListener((obs, oldValue, newValue) -> {
    // do whatever you need with oldValue and newValue
});

?