text:
Q: How to exclude a field from @JsonInclude(JsonInclude.Include.NON_NULL) I have annotated a POJO with @JsonInclude(JsonInclude.Include.NON_NULL) to exclude all null fields while serialization/deserialization.
But now I need to exclude one of the fields from this behaviour. ie - I want to send over the value of a field as null if it has a null value.
There is some update in legacy code which has put me in this situation.
How can i achieve this?
Edit:
Would using a JSONSerialize(include=CustomSerializer.class) give higher precedence to the CustomSerializer?

A: Use @JsonInclude(Include.ALWAYS) annotation on your field. This will override @JsonInclude(Include.NON_NULL) on the class level.


text:
Q: How to split the videos into multiple packets using php? I Just want to buffer a video manually, so I need to split the videos into smaller packets.
For example: convert 6 MB video into 6 - 1 MB small videos.
Is this feasible using PHP?

A: This sounds related to the questions about "Streaming Video in Parts".
As mentioned, the described way of consuming videos is similar to adaptive streaming. An introduction to that topic can be found here.
If you are bound to PHP, you can still use it to generate segmented content, with Bitmovin's API, as shown in the example at https://github.com/bitmovin/bitcodin-php.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the created site category on Area 51 I've just created a site on Area 51 and realized that I had set the wrong category, but realized that I couldn't change it with editing.
Is the only way to delete the site and create it again tomorrow?


text:
Q: How to plot a function when we want to change the independent variables? Suppose we have two functions $z(x)=x^4+1$ and $y(x)=x^2+x+1$. Then how to plot $z$ vs $y$ (assuming in general that $z$ can not be written explicitly in terms of $y$)?

A: Given your definitions
eqns = z == x^4 + 1 && y == x^2 + x + 1;

you can plot the resulting curve
Show[Region[ImplicitRegion[Eliminate[eqns, x], {y, z}]], Axes -> True]


text:
Q: Entity Framework 6: Delete entity with many-to-many relationship I'm using Entity Framework 6 and I have following entities
public class Entity1
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; }

   public virtual ICollection<Entity3> Entities3 { get; set; }

   public virtual Entity2 Entity2 { get; set; }
}

public class Entity2
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; }

   public virtual ICollection<Entity3> Entities3 { get; set; }
}

public class Entity3
{
   [Key, Column(Order = 0)]
   [ForeignKey("Entity2")]
   public int Entity2_Id { get; set; }
   public virtual ICollection<Entity2> Entities2 { get; set; }

   [Key, Column(Order = 1)]
   [ForeignKey("Entity1")]
   public int Entity1_Id { get; set; }
   public virtual ICollection<Entity1> Entities1{ get; set; }

   [Key, Column(Order = 2)]
   public DateTime Timestamp { get; set; }
}

I'm trying to delete Entity1 this way:
private void DeleteEntity1(int id)
{
   var ent1 = dataContext.Entities1.Include(x=>x.Entities3).FirstOrDefault(x=>x.Id == id);
   var entities3 = ent1.Entities3.ToList();
   foreach(var entity3 in entities3)
   {
      entity3.Entities2.Clear();
      entity3.Entities1.Clear();
      dataContext.Entities3.Remove(entity3);
   }
   dataContext.Entities1.Remove(entity);
   dataContext.SaveChanges();
}

dataContext.Entites1 is DbSet<Entity1> and similar dataContext.Entities3 is DbSet<Entity3>.
If Entity1 exists without any relationship to Entity2 and Entity3 I'm able to delete Entity1.
But if Entity3 exists then dataContext.SaveChanges throws an exception:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error
  occurred while saving entities that do not expose foreign key
  properties for their relationships.  The EntityEntries property will
  return null because a single entity cannot be identified as the source
  of the exception.  Handling of exceptions while saving can be made
  easier by exposing foreign key properties in your entity types.  See
  the InnerException for details.'

Inner exception:

OptimisticConcurrencyException: Store update, insert, or delete
  statement affected an unexpected number of rows (0). Entities may have
  been modified or deleted since entities were loaded.

Inner exception has one StateEntries of type RelationshipEntry:
EntitySet: Entity3_Entity2
Not sure how to delete Entity1 properly.


text:
Q: jdbc connection socketexception error am successfully finished login form in android using mysql connection via jdbc in java...its successfully worked in my localhost...but development site its not worked...the following error is displyed.
java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.ConnectException: Connection timed out: connect

** BEGIN NESTED EXCEPTION **

java.net.SocketException
MESSAGE: java.net.ConnectException: Connection timed out: connect

STACKTRACE:

java.net.SocketException: java.net.ConnectException: Connection timed out: connect
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
    at com.mysql.jdbc.Connection.<init>(Connection.java:452)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.retrieve.retrieve.main(retrieve.java:15)

** END NESTED EXCEPTION **

    at com.mysql.jdbc.Connection.createNewIO(Connection.java:1875)
    at com.mysql.jdbc.Connection.<init>(Connection.java:452)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.retrieve.retrieve.main(retrieve.java:15)

why dis error  is occurred.give me some solutions.
if am running localhost means my sql query is
             package com.example.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginLayoutActivity extends Activity {

    EditText username,password;
    TextView error;
    Button ok;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        username=(EditText)findViewById(R.id.et_un);
        password=(EditText)findViewById(R.id.et_pw);
        error=(TextView)findViewById(R.id.tv_error);
        ok=(Button)findViewById(R.id.btn_login);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Editable user = username.getText();
                Editable pass = password.getText();

                try {

                    **Class.forName("com.mysql.jdbc.Driver");

                        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/people", "root", "");
                        Statement st = con.createStatement();

                        ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**

                        if(rs.next())
                        {
                            String dbpass = rs.getString(1);
                            if(dbpass.equals(pass)){
                                 error.setText("Correct Username or Password");

                        }
                        else
                        {
                            error.setText("Sorry!! Incorrect Username or Password");
                        }
                        }
                }

                     catch (SQLException e) {
                        username.setText(e.toString());
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

        });
    }
}

if am running development site means my query is:
              package com.example.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginLayoutActivity extends Activity {

    EditText username,password;
    TextView error;
    Button ok;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        username=(EditText)findViewById(R.id.et_un);
        password=(EditText)findViewById(R.id.et_pw);
        error=(TextView)findViewById(R.id.tv_error);
        ok=(Button)findViewById(R.id.btn_login);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Editable user = username.getText();
                Editable pass = password.getText();

                try {

                    **Class.forName("com.mysql.jdbc.Driver");

                        Connection con = DriverManager.getConnection("jdbc:mysql://dev.xxxxx.com/xxx", "xxxx", "xxxx");
                        Statement st = con.createStatement();

                        ResultSet rs = st.executeQuery("SELECT password FROM customers where login='"+user+"'");**

                        if(rs.next())
                        {
                            String dbpass = rs.getString(1);
                            if(dbpass.equals(pass)){
                                 error.setText("Correct Username or Password");

                        }
                        else
                        {
                            error.setText("Sorry!! Incorrect Username or Password");
                        }
                        }
                }

                     catch (SQLException e) {
                        username.setText(e.toString());
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

        });
    }
}

dis development site username,password,database name and url all r correct only...then why dis error is occured....give me solutions...

A: If you are trying to connect your mysql in the localhost from an android application, it may not get communication, refer this.
This exception seems like the mysql doesn't have public access.
Make your mysql available in a remote system and give the remote system's ip. Let 192.168.1.102 be its ip, then change this statement as jdbc:mysql://192.168.1.102:3306/people.
You have to modify the mysql configuration file. It may be /etc/mysql/my.cnf (in linux) or  \xampp\mysql\bin\my.ini (depends on mysql refer more).
By default it contains bind-address            = 127.0.0.1, change it as bind-address            = 0.0.0.0. When this change is made, then the mysql is available publicaly i.e. it can be accessed remotely. Now your application can access this mysql.

A: Sounds like a network problem. Verify if you can access the Database host and port from the device you're making the connection, and if the DBMS is up and running.

A: The key question is whether or not the mobile device is on the network when you try to connect to the database.  If you're on the network, you'll need to talk to the MySQL database administrator to see if you have permission to access that database.  I'm guessing that you do not, because you're trying to log in as root without a password.  No administrator in their right mind would allow you to do that.
If you're the administrator, please call your therapist of pharmacist.
If the mobile device is not on the network,  I'm guessing that the database is behind a firewall of some kind.  At best you'll have to talk to some administrator to get firewall rules set up to allow access from the mobile device.  Those usually require some information about the device.  Firewall rules won't be practical if you intend to release an app for several users.
A better solution would be to set up a proxy that would authenticate incoming mobile devices and communicate with the database on their behalf.
I would not have a mobile device connecting directly to a database, especially the way you're trying to do it.
Who else knows about what you're trying to do?  It looks to me like you're trying to connect to a database, but that fact isn't widely known.  Who else knows about your project?

A: If you use en emulator use a special IP to your localhost.
10.0.2.2
jdbc:mysql://10.0.2.2:3306/people


text:
Q: Why aren't dependencies generated inside makefiles? I recently learned how to use Makefiles, and I found out that GCC/G++ generates dependencies for you:
$ g++ -MM file.cpp
file.o: file.cpp file.h

I then thought that the obvious thing to do would be to use this to generate dependencies directly in the file without creating a dependency file:
CXX = g++

SRCS = $(wildcard src/*.cpp)
OBJS = $(SRCS:.cpp=.o)
OCT = $(CXX -MM $(SRCS))
OBJDIR = obj
CPPFLAGS = -Wall -I/usr/local/include -L/usr/local/lib -lGLEW -lglfw -lGL

.PHONY: all
all: $(OBJS)
    $(CXX) $(CPPFLAGS) $(OBJS) -o output

$(OCT)

.PHONY: clean
clean:
    rm -f obj/*

For some reason, I have never seen anyone else do this; they always generate a dependency file. Is there something wrong with this system? In my case yes -- the objects don't go to OBJDIR, they go to they location of the source file. I'm sure this could be fixed though. If anyone knows how I could fix this and why dependency files are usually generated, please let me know.

A: Well, the first reason people don't do this is that it's not possible to do: if you try to make your suggestion work in real life you'll see that.  Your example, for instance, doesn't do anything at all.  This:
OCT = $(CXX -MM $(SRCS))

(I assume you mean $($(CXX) -MM $(SRCS)) but it doesn't matter either way) is putting a reference to the make variable named, literally, CXX -MM $(SRCS) into the variable OCT: you probably are thinking that it's using the shell command invocation syntax $(...) but this is a makefile, not a shell script.  So when you write:
$(OCT)

that tries to look up that make variable, which obviously does not exist, and so this expands to the empty string and nothing at all happens.  If you actually try to test your makefile by touching a header etc. you'll see nothing gets rebuilt.
How can you do this?  You can't do it.  You can change your variable assignment like this:
OCT = $(shell $(CXX) -MM $(SRCS))

and that will actually run the compiler, which is moving you in the right direction, but the results of the shell function will change all newlines to whitespace, so this:
$(OCT)

will expand to the entire output of the compiler command on one line, and since it contains multiple colons you'll get a syntax error.
All you can do is redirect the output of the compiler to a file, and using make's include capability to include that file.  But now you're basically back to the scenario suggested in the GNU make manual, except your version is less efficient because, as pointed out in the comments above, you're regenerating all the headers for all the source files every time you run make, rather than only regenerating header information for the files that have actually changed.
There are better/more efficient ways to generate headers, such as the one used by most GNU packages.


text:
Q: How to set constant for a constraint in xib file I want to have a constant and use it for leading and trailing constraint in xib files or storyboard.
Then if I change this constant I want all leading and trainings to change

A: For this you need to create outlets of the constraints leading or trailing in class of the xib. Then you should pass the constant values to those constraints.
For example:-
@IBOutlet weak var leadingConstraint: NSLayoutConstraint!
@IBOutlet weak var trailingConstraint: NSLayoutConstraint!

Now you pass your constant value whenever you want to change it to these constraints in xib class.
leadingConstraint.constant = 80.0(Your constant)
trailingConstraint.constant = 80.0(Your constant)

Or if you want to pass it in tableViewDataSource method cellForRowAtIndex:
Then,
cell.leadingConstraint.constant = 80.0(Your constant)
cell.trailingConstraint.constant = 80.0(Your constant)


text:
Q: Why insert-select to variable table from XML variable so slow? I'm trying to insert some data from a XML document into a variable table. What blows my mind is that the same select-into (bulk) runs in no time while insert-select takes ages and holds SQL server process accountable for 100% CPU usage while the query executes.
I took a look at the execution plan and INDEED there's a difference. The insert-select adds an extra "Table spool" node even though it doesn't assign cost. The "Table Valued Function [XML Reader]" then gets 92%. With select-into, the two "Table Valued Function [XML Reader]" get 49% each.
Please explain "WHY is this happening" and "HOW to resolve this (elegantly)" as I can indeed bulk insert into a temporary table and then in turn insert into variable table, but that's just creepy.
I tried this on SQL 10.50.1600, 10.00.2531 with the same results
Here's a test case:
declare @xColumns xml
declare @columns table(name nvarchar(300))

if OBJECT_ID('tempdb.dbo.#columns') is not null drop table #columns

insert @columns select name from sys.all_columns

set @xColumns = (select name from @columns for xml path('columns'))

delete @columns

print 'XML data size: ' + cast(datalength(@xColumns) as varchar(30))

--raiserror('selecting', 10, 1) with nowait

--select ColumnNames.value('.', 'nvarchar(300)') name
--from @xColumns.nodes('/columns/name') T1(ColumnNames)

raiserror('selecting into #columns', 10, 1) with nowait

select ColumnNames.value('.', 'nvarchar(300)') name
into #columns
from @xColumns.nodes('/columns/name') T1(ColumnNames)

raiserror('inserting @columns', 10, 1) with nowait

insert @columns
select ColumnNames.value('.', 'nvarchar(300)') name
from @xColumns.nodes('/columns/name') T1(ColumnNames)

Thanks a bunch!!

A: Looks to be an issue specific to SQL Server 2008. When I run the code in SQL Server 2005, both inserts run quickly and produce identical execution plans that start with the fragment shown below as Plan 1. In 2008, the first insert uses Plan 1 but the second insert produces Plan 2. The remainder of both plans beyond the fragment shown are identical.
Plan 1

Plan 2

A: This is a bug in SQL Server 2008.
Use
insert @columns
select ColumnNames.value('.', 'nvarchar(300)') name
from @xColumns.nodes('/columns/name') T1(ColumnNames)
OPTION (OPTIMIZE FOR ( @xColumns = NULL ))

This workaround is from an item on the Microsoft Connect Site which also mentions a hotfix for this Eager Spool / XML Reader issue is available (under traceflag 4130).
The reason for the performance regression is explained in a different connect item

The spool was introduced due to a general halloween protection logic
  (that is not needed for the XQuery expressions).


text:
Q: How to merge two lists into dictionary without using nested for loop I have two lists:
a = [0, 0, 0, 1, 1, 1, 1, 1, .... 99999]
b = [24, 53, 88, 32, 45, 24, 88, 53, ...... 1]

I want to merge those two lists into a dictionary like:
{
    0: [24, 53, 88],
    1: [32, 45, 24, 88, 53],
    ......
    99999: [1]
}

A solution might be using for loop, which does not look good and elegant, like:
d = {}
unique_a = list(set(list_a))
for i in range(len(list_a)):
    if list_a[i] in d.keys:
        d[list_a[i]].append(list_b[i])
    else:
        d[list_a] = [list_b[i]]

Though this does work, it's an inefficient and would take too much time when the list is extremely large. I want to know more elegant ways to construct such a dictionary?
Thanks in advance!

A: No fancy structures, just a plain ol' dictionary.
d = {}
for x, y in zip(a, b):
    d.setdefault(x, []).append(y)

A: You can use a defaultdict:
from collections import defaultdict
d = defaultdict(list)
list_a = [0, 0, 0, 1, 1, 1, 1, 1, 9999]
list_b = [24, 53, 88, 32, 45, 24, 88, 53, 1]
for a, b in zip(list_a, list_b):
   d[a].append(b)

print(dict(d))

Output:
{0: [24, 53, 88], 1: [32, 45, 24, 88, 53], 9999: [1]}

A: You can do this with a dict comprehension:
list_a = [0, 0, 0, 1, 1, 1, 1, 1]
list_b = [24, 53, 88, 32, 45, 24, 88, 53]
my_dict = {key: [] for key in set(a)}  # my_dict = {0: [], 1: []}
for a, b in zip(list_a, list_b):
    my_dict[a].append(b)
# {0: [24, 53, 88], 1: [32, 45, 24, 88, 53]}

Oddly enough, you cannot seem to make this work using dict.fromkeys(set(list_a), []) as this will set the value of all keys equal to the same empty array:
my_dict = dict.fromkeys(set(list_a), [])  # my_dict = {0: [], 1: []}
my_dict[0].append(1)  # my_dict = {0: [1], 1: [1]}

A: A pandas solution:
Setup:
import pandas as pd

a = [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4]

b = pd.np.random.randint(0, 100, len(a)).tolist()

>>> b
Out[]: [28, 68, 71, 25, 25, 79, 30, 50, 17, 1, 35, 23, 52, 87, 21]

df = pd.DataFrame(columns=['Group', 'Value'], data=list(zip(a, b)))  # Create a dataframe

>>> df
Out[]:
    Group  Value
0       0     28
1       0     68
2       0     71
3       1     25
4       1     25
5       1     79
6       1     30
7       1     50
8       2     17
9       2      1
10      2     35
11      3     23
12      4     52
13      4     87
14      4     21

Solution:
>>> df.groupby('Group').Value.apply(list).to_dict()
Out[]:
{0: [28, 68, 71],
 1: [25, 25, 79, 30, 50],
 2: [17, 1, 35],
 3: [23],
 4: [52, 87, 21]}

Walkthrough:

*

*create a pd.DataFrame from the input lists, a is called Group and b called Value

*df.groupby('Group') creates groups based on a

*.Value.apply(list) gets the values for each group and cast it to list

*.to_dict() converts the resulting DataFrame to dict
Timing:
To get an idea of timings for a test set of 1,000,000 values in 100,000 groups:
a = sorted(np.random.randint(0, 100000, 1000000).tolist())
b = pd.np.random.randint(0, 100, len(a)).tolist()
df = pd.DataFrame(columns=['Group', 'Value'], data=list(zip(a, b)))

>>> df.shape
Out[]: (1000000, 2)

%timeit df.groupby('Group').Value.apply(list).to_dict()
4.13 s ± 9.29 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

But to be honest it is likely less efficient than itertools.groupby suggested by @RomanPerekhrest, or defaultdict suggested by @Ajax1234.

A: Maybe I miss the point, but at least I will try to help. If you have to lists and want to put them in the dict do the following
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
lists = [a, b] # or directly -> lists = [ [1, 2, 3, 4], [5, 6, 7, 8] ]
new_dict = {}
for idx, sublist in enumerate([a, b]): # or enumerate(lists)
    new_dict[idx] = sublist

hope it helps

A: Alternative itertools.groupby() solution:
import itertools

a = [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3]
b = [24, 53, 88, 32, 45, 24, 88, 53, 11, 22, 33, 44, 55, 66, 77]

result = { k: [i[1] for i in g]
           for k,g in itertools.groupby(sorted(zip(a, b)), key=lambda x:x[0]) }
print(result)

The output:
{0: [24, 53, 88], 1: [24, 32, 45, 53, 88], 2: [11, 22, 33, 44, 55, 66], 3: [77]}

A: Or do dictionary comprehension beforehand, then since all keys are there with values of empty lists, iterate trough the zip of the two lists, then add the second list's value to the dictionary's key naming first list's value, no need for try-except clause (or if statements), to see if the key exists or not, because of the beforehand dictionary comprehension:
d={k:[] for k in l}
for x,y in zip(l,l2):
   d[x].append(y)

Now:
print(d)

Is:
{0: [24, 53, 88], 1: [32, 45, 24, 88, 53], 9999: [1]}


text:
Q: GeoServer caching request not aligned to grid(s) For starters, just to point out I have really gone through all posts here on this issue and none of the solutions are working for me.
I have a lot of GeoServer layers which I am serving in EPSG:3765 without a problem to my app. However, when I turn on caching using GeoServer integrated GWC, the trouble begins. I created a new gridset as in the image:

The pixel sizes I calculated by dividing the coordinate difference (e.g. X2-X1 or Y2-Y1, the result is the same) of tile bounds(from the http request params) at respective zoom levels with 256 and calculated the result on pow(-1). Maybe this is where I went wrong but adding normal zoom levels without any change hasn't done it for me either.
All my layer extents are set to SRID extent, my request is set to tile width and height 256. I think I am doing something wrong with defining pixel size /scale but for the life of me, I can't get it right. I also tried changing CRS extent to the one defined on SRS official page, hasn't made any difference. My projection and view are defined like this:
proj4.defs('EPSG:3765', "+proj=tmerc +lat_0=0 +lon_0=16.5 +k=0.9999 +x_0=500000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");

var htrs = ol.proj.get('EPSG:3765');

var view = new ol.View({center: [467500, 5101500],
projection: htrs,
minZoom: 7,
maxZoom: 20,
zoom: 12 });

All of my layers, have a 'TILED':true parameter. The error I am getting is
geowebcache-cache-result "MISS"
geowebcache-miss-reason "request does not align to grid(s) 'grid_3765'"

I am a newbie at Geoserver, GWC and JavaScript and have no idea anymore what I could be doing wrong. Any solutions?

A: I figured out the solution. My projection extent was wrong, which I realised by looking into the GWC GET request info in my web browser. I saw my extent was different from the one assigned to the tile for zoom level 0(0, 0, 0), read the new coordinates and assigned them to my projection extent and custom gridset. Now it works like a charm. By what I've read on some forums, it seems GeoWebCache and GeoServer have different extent value for some projections. I'm sorry my browsers language is Croatian, but you get the idea. Hope this helps someone.


text:
Q: How to copy page from one PDF document to another and add margin Can someone please give me example of copying pages with iText 7 from one PDF to another.
I need to copy page from one PDF to another and leave some space on the top for the barcode ... but every time I copy page with:
srcDoc.copyPagesTo(Integer.valueOf(tBrStr), Integer.valueOf(tBrStr), pdf)

The copied page fits over whole page and I cannot put margin on the top of page for barcode.


text:
Q: Iterating through Processes using Python Multiprocessing package I have two processes, one that runs a flask app and another that runs an experiment built in Python. I run these two processes in parallel using the Python multiprocessing package. I want to run these two processes in parallel multiple times, each time correcting beginning and ending both processes. So far I have been able to run them concurrently once or multiple times in such a way: function1 function1 function1 function2 function2 function2 or function1 function2 function2 function2 function1. Otherwise I get errors stating that I cannot start a process twice. I want to run them like so: function1 function2 function1 function2 function1 function2.
Below is a simpler example outlining what I've tried to do.
    proc1 = Process(target=function1)
    proc1.daemon = True
    proc2 = Process(target=function2)
    proc2.daemon = True

    processes1 = [proc1 for i in range(5)]
    processes2 = [proc2 for i in range(5)]

    for process1 in processes1:
        process1.start()
        process1.join()
        process1.terminate()

    for process2 in processes2:
        process2.start()
        process2.join()
        process2.terminate()


text:
Q: What is the figure which is throughput with processor means in oracle java official document The "Java Platform, Standard Edition HotSpot Virtual Machine Garbage Collection Tuning Guide", explains its figure 1-1 like below

The red line is an application spending only 1% of the time in garbage collection on a uniprocessor system. This translates to more than a 20% loss in throughput on systems with 32 processors.

I don't understand what this figures really mean.
Does it mean that, in the condition which is fixed gc time, the GC affects throughput of CPUs because of its suspension?

A: Here is the explanation text in the document where you found this graph is:

The graph in Figure 1-1 models an ideal system that's perfectly scalable with the exception of garbage collection. The red line is an application spending only 1% of the time in garbage collection on a uniprocessor system. This translates to more than a 20% loss in throughput on systems with 32 processors. The magenta line shows that for an application at 10% of the time in garbage collection (not considered an outrageous amount of time in garbage collection in uniprocessor applications), more than 75% of throughput is lost when scaling up to 32 processors.

The link below the graph says:

The graph models an ideal system that's perfectly scalable with the exception of garbage collection (GC). It plots the number of processors (x-axis) against throughput (y-axis). It contains six plotted lines labeled 1% GC, 2% GC, 3% GC, 10% GC, 20% GC, and 30% GC. Each line represents the changing throughput for an application that spends the specified percentage of time used for garbage collection on a uniprocessor system versus on a multiprocessor system. The graph is described in the text that precedes it.

So ...

*

*This is a model, not a graph of real measured performance.

*The model is idealized.  It assumes that the application is perfectly scalable (apart from GC).

*It is illustrating what happens when you don't make the garbage collection scalable; e.g. if there is only one GC thread and it doesn't operate in parallel with application threads.

*The 1% GC, 2% GC, etc lines represent different modeled GC loads on a uniprocessor system.  So the 1% line represents the case of an application running on a uniprocessor system where the application threads generate a GC load that could be collected using 1% of the available CPU.

*The throughput represents the useful (application) work that is being done by a busy application; i.e. the time (GC overhead) that is *not taken up with garbage collection or waiting for the GC to finish.

*The throughput is measured as a percentage of the available CPU time on a system with the given number of processors.

So, for example, at the 30% GC level, the throughput for a 32 core system will be roughly 1/10th of the theoretical throughput of the hardware.  It  will waste roughly 9/10ths of the available CPU time waiting for garbage collection to complete!

A: The important thing is Amdahl's law, it states that "the overall performance improvement gained by optimizing a single part of a system is limited by the fraction of time that the improved part is actually used".
You can calculate the graph.


text:
Q: How to push laravel notification via pusher beams ? and How can I add interests to my created notification so I can Listen in my react app? I've implemented pusher beams like this:

*

*I've added credentials in config/services.php
'pusher' => [
  'beams_instance_id' => '********',
  'beams_secret_key' => '*************',
],

*I've created a new notification

class TestOne extends Notification
{
    use Queueable;

    public $message;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($message)
    {
        $this->message = $message;

    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [PusherChannel::class , 'database'];
    }

    /**
     * Get the array representation of the notification.
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
    //    event( new PostLiked($notifiable->id ,$this->message));
        return [
            'title' => $this->message->title,
            'content' => $this->message->content,
        ];
    }
    // notification type
    public function broadcastType()
{
    return 'users';
}
public function toPushNotification($notifiable)
    {
        return PusherMessage::create()
            ->platform('web')
            ->badge(1)
            ->sound('success')
            ->body("Your ac account was approved!");
    }

}

*I've added Notifiable to User Model :

class User extends Authenticatable
{
  use HasApiTokens, HasFactory, Notifiable;

How to specify the interest in my backend so I can listen to it in my react app and how to use beams debug console to make sure the Laravel notification is being fired?

A: public function toPushNotification($notifiable)
    {
        return PusherMessage::create()
            ->platform('web')
            ->badge(1)
            ->sound('success')
            ->body("Your ac account was approved!");
    }

While I was tracking this code , It seems that I had a certificate issues problem in my local environment.
So I moved to this way in connection to beams :
$beamsClient = new \Pusher\PushNotifications\PushNotifications(array(
        "instanceId" => "*********************************",
        "secretKey" => "***************",

    ), new GuzzleHTTP\Client(['verify' => false]));

    $publishResponse = $beamsClient->publishToUsers(
        array("user-001", "user-002", "1"),
        array("web" => array("notification" => array(
            "title" => "fofo",
            "body" => "Hello, World!",
            "deep_link" => "https://www.pusher.com",
        )),
        ));


text:
Q: How to expose services running in Kubernetes I have installed Charmed-Kubernetes on Ubuntu. and then istio and its bookinfo application.
kubectl exec -it $(kubectl get pod -l app=ratings -o jsonpath='{.items[0].metadata.name}') -c ratings -- curl productpage:9080/productpage | grep -o "<title>.*</title>"
This returns, Simple Bookstore App
kubectl get gateway -> bookinfo-gateway   32s
kubectl get svc istio-ingressgateway -n istio-system
Shows external IP address, but when I try to access with curl it gives me nothing.
I also tried to access to kubernetes-dashboard as described here, it also failed.
Basically, how can I access to these UI s from another PC? I have installed MetalLB, but still no luck.
Refered :
No endpoint with dashboard
Kube-dashboard serviceunavailable
Cant access K8 Dashboard
Traffic goes through a network proxy, could it be a problem?
I am newby for Kubernetes.

A: This was an issue with Charmed-Kubernetes. We need to install all services as juju and then deploy also with juju.
Here nginx sample is really running in the system, but MetalLB can not access to it as juju configuration hides it.


text:
Q: Cloudflare SSL not working on AWS EC2 I just installed cloudflare on my ec2 instance.
But while opening https://eizo.co.in/ i am getting ERR_SSL_PROTOCOL_ERROR
I've already run a2enmod ssl & apt-get install openssl. Have allocated 443 port.
Please help!

A: No need to worry! It will get fixed automatically just wait for around 24-48 hours.


text:
Q: Schema Length Validation Error on Python Dash DataTable I am building a dashboard using python dash and have a requirement of datatable with multiple dropdowns. The dataframe is created one with groupby (multiple columns) and aggregation.
I have written the code as below:
'''
app = JupyterDash()
app.layout = html.Div(children = [html.H2('SPEND PLANNING',
             style = {'background-color':'#C0C0C0',
                      'border': '5px solid',
                      'font-family':'Serif',
                      'font-size': 25,
                      'text-align':'center',
                      'margin':'auto',
                      'justify-content': 'space-evenly',
                      'width':'100%'
                     }),

            html.H1(),

            html.Div(children = [dcc.Dropdown(
                       id ='period-filter',
                       options = dict([{"label": i, "value": i} for i in s2['PERIOD'].unique()]),
                       value = s2['PERIOD'].max(),
                       multi = True,
                       searchable=True,
                       style = {'display':'inline-block','width':'48%','vertical-align':'top'},
                       clearable=False,
                       placeholder="Quarter"
                    )]),

            html.H1(),

            html.Div(children = [dcc.Dropdown(
                       id ='commodity-filter',
                       options = dict([{"label": i, "value": i} for i in s2['COMMODITY GROUP'].unique()]),
                       value = s2['COMMODITY GROUP'].max(),
                       multi = True,
                       searchable=True,
                       style = {'display':'inline-block','width':'48%'},
                       clearable=False,
                       placeholder= "Commodity Group"
                    )]),

            html.H1(),

            html.Div(children = [dt(
                        id = "datatable",
                        columns = [{"name": i, "id": i} for i in s2.columns],
                        editable = True,
                        data = s2.to_dict('records'),
                        multi = True
                       ])

@app.callback(output = [Output("datatable", "data")],
              inputs = [Input("period-filter", "value"),Input("commodity-filter","value")])

def display_table(comm,period):
    filtered_df = s2.loc[(s2['COMMODITY GROUP'].eq('comm')) & (s2['PERIOD'].eq('period'))]
    return filtered_df.to_dict('records')

if _name_ == "_main_":
    app.run_server(debug=True)
'''

The error after running the script is below:
SchemaLengthValidationError: Schema: [<Output datatable.data>]
Path: ()
Expected length: 1
Received value of length 0:
[]
When I remove the [] from [Output("datatable", "data")] the error is gone, however the data in the table also disappears giving a blank table.
The dropdowns also do not show the values, instead shows only - value.
Please help me with the above.


text:
Q: How to import a fixed width csv file when lines have different patterns of column size using Python? This dataset has information on two kinds of entities: companies and persons. Each line of data identifies the entity by the first two characters: 01 for companies and 02 for persons.
Example:
0183738293836728NAME OF THE COMPANY - ME
02837382938367282              22NAME OF THE OWNER,NAME OF WIFE

First line is the company and second line is the owner information. Not all of the companies have only one owner and some of the names have commas and periods. When there's more than one owner, it's presented on separate lines, but keeping the ID that follows the first two digits in every line. As you can see, the lines present different types of information, thus the need for different patterns to separate the columns.
I need to import this into PYTHON in a way that afterwards it's possible to do some data analysis using statistics, econometrics, etc... . There are 27 big files with this kind of data. If it's possible to automate the iteration of the individual files inside the same folder, even better.
I tried reading it and separating, as well as with dataframes, but haven't been able to make it work. Any help?
Thank you!

A: Instead of using the csv module, you should use a normal file read, and then separating each column on each line by yourself(using a custom function that fit your need).
In this case I don't think you should/can use the csv module to do the work.


text:
Q: Can't change empty index name in DataFrame I have over 100 csv files, all contain a table with the same indexes and indentical length. I am able to concat them into a single dataframe and save as csv.
print(df)

         a   b   c   d
0    1   5   1   7   7
1    2   3   1   7   7
2    3   2   2   8   7
3    1   6   1   7   6

I want to add a name to the now blank 'initial index' but every solution I find doesn't work...
I've tried:
df.rename(columns={'': 'initial'}, inplace=True)
df1 = df.rename(columns={'': 'initial'})
df1 = df.set_index('initial')
df1 = df.rename_axis("initial")

Header printout as is:
print([*df])
[' a b c d']

I am using Python 3.7.3
Edit
Thanks for the feedback. Both Joe Ferndz and icecity96 solutions work. They didn't initially only because .csv file columns were seperated with spaces not comma's, therefore the DataFrame has seen only one column. Problem gone away after adding delim_whitespace=True
pd.read_csv(file, delim_whitespace=True)

Output before:
print(*df)
[' a b c d']

Output after:
print([*df])
['a', 'b', 'c', 'd']

A: Try:
df.rename({df.columns[0]: 'initial'}, axis='columns', inplace=True)

Output:
>>> print([*df])
['', 'a', 'b']
>>> df.rename({df.columns[0]: 'initial'}, axis='columns', inplace=True)
>>> print([*df])
['initial', 'a', 'b']

A: If you want to rename the columns, can't you just do something as simple as this please?
import pandas as pd

df = pd.DataFrame({'' :[1,2,3,4],
                   'A':['A','B','C','D'],
                   'Z':[True, False, False, True]})
print(df)

df.columns = ['New','A','B']

print(df)

Here the first column got renamed as 'New' and also renamed column Z as B
Output is:
Before:
      A      Z
0  1  A   True
1  2  B  False
2  3  C  False
3  4  D   True

After:
   New  A      B
0    1  A   True
1    2  B  False
2    3  C  False
3    4  D   True


text:
Q: Android: IOException with HttpGet request Im trying to connect to a server and than receive some data back in Json format. Here is my java code:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("https://my.server.com/validate/" + data);
request.setHeader("Accept", "application/json");
request.setHeader("X-AuthToken","my authorisation code");
HttpResponse response = client.execute(request);

I also have
<permission android:name="android.permission.INTERNET"></permission>

as a child of manifest (not application) in my manifest.xml
When I try to open the url in browser, I get the correct page but I dont get any data since it misses the authentication. I also have a good connection.
I've been trying to fix this for a few hours now, but I still get IOException at the line with client.execute(request)
java.net.UnknownHostException: my.server.com

Any ideas? :) Thanks!

A: Seems like you're missing uses-?
<uses-permission android:name="android.permission.INTERNET" />?
<permission> is used to declare a new permission. Docs

A: Sorry if I'm missing something, but is my.server.com really a valid host?  Did you forget to plug in the actual host?

A: Besides the answers here, here are a few aditional suggestions

*

*Try going to to URL in a browser

*Check to make sure you have an internet connection on your device by using the browser

*Try cleaning the project and trying again (this has done the trick for me several times)  (Project -> Clean)


text:
Q: Send a date value by post method to php process by ajax I'm using php and ajax to upload multiples files with progress bar animation
Everything work well, except I can't get a date value with Post method
this code return empty variable
$expire = $_POST['expire'];

I tried to change the order of reading the value of $expire from $_POST['expire']
But I always get an empty value !
Here is my import.php (contains form to upload multple files) :
<input type="file" name="file[]" id="file" required multiple accept="application/pdf" />
<input type="date" name="expire" class="form-control" min="<?php echo date('Y-m-d') ?>" />
<button type="submit" id="submit" name="submit" class="btn btn-success" style="width:100%">
   Commencer
</button>

And it contains te ajax code to call upload.php process

document.getElementById('submit').addEventListener('click', function(e){
    e.preventDefault();
    var f = document.getElementById('file'),
        pb = document.getElementById('progressbar'),
        pt = document.getElementById('progressbar-text'),
        btn = document.getElementById('submit');

    btn.innerHTML = "Chargement en cours …";
    btn.disabled = true;

    app.uploader({
        files: f,
        progressBar: pb,
        progressText: pt,
        processor: 'upload.php',

        finished: function(data){
            //

        },

        error: function() {
            alert('Erreur ! veuillez réessayer SVP');
        }
    });

});

this is my upload.php
phpheader('Content-Type: application/json');

    $allowed = ['pdf'];

    $succeeded = [];
    $failed_move = [];
    $failed_ext = [];
    $failed_bdd = [];
    $failed_name = [];

    if(!empty($_FILES['file'])) {
        $expire = $_POST['expire'];

        include '../config/config.php';
        foreach($_FILES['file']['name'] as $key => $name){

            if(file_exists('../pdf/'.$name)) {
                $failed_name[] = array(
                    'name' => $name
                );
            } else {
                $tmp = $_FILES['file']['tmp_name'][$key];
                $code = explode('.', $name);
                $ext = strtolower(end($code));

                if (in_array($ext, $allowed) === true) {
                    if (move_uploaded_file($tmp, '../pdf/'.$name)) {

                        if (addPdf($code['0'], $expire)) {
                            $succeeded[] = array(
                                'name' => $name
                            );
                        } else {
                            $failed_bdd[] = array(
                                'name' => $name
                            );
                            unlink('../pdf/'.$name);
                        }
                    } else {
                        $failed_move[] = array(
                            'name' => $name
                        );
                    }
                } else {
                    $failed_ext[] = array(
                        'name' => $name
                    );
                }
            }
        }
    }

    if (!empty($_POST['ajax'])){
        echo json_encode(array(
            'succeeded' => $succeeded,
            'failed_move' => $failed_move,
            'failed_ext' => $failed_ext,
            'failed_bdd' => $failed_bdd,
            'failed_name' => $failed_name
        ));
    }

A: Here you go. I have modified your code so it includes the value of the input with ID 'expire'. You'll have to modify the HTML code as well as your expire input has no ID attached to it.
<input type="file" name="file[]" id="file" required multiple accept="application/pdf" />
<input type="date" name="expire" id="expire" class="form-control" min="<?php echo date('Y-m-d') ?>" />
<button type="submit" id="submit" name="submit" class="btn btn-success" style="width:100%">Commencer

upload.js
var app = app || {};

(function(o) {
    "use strict";

    // private methods
    var ajax, getFormData, setProgress;

    ajax = function(data) {
        var xmlhttp = new XMLHttpRequest(), uploaded;

        xmlhttp.addEventListener('readystatechange', function(){
            if(this.readyState === 4){
                if(this.status === 200){
                    uploaded = JSON.parse(this.response);
                    if(typeof o.options.finished === 'function') {
                        o.options.finished(uploaded);
                    }
                } else {
                    if(typeof o.options.error === 'function') {
                        o.options.error();
                    }
                }

            }
        });

        xmlhttp.addEventListener('progress', function(event) {
            var percent;
            if(event.lengthComputable === true){
                percent = Math.round((event.loaded / event.total) * 100);
                setProgress(percent);
            }
        });

        xmlhttp.open('post', o.options.processor);
        xmlhttp.send(data);
    }

    getFormData = function(source, expire) {
        var data = new FormData(), i;

        for (i = 0; i < source.length; i++) {
           data.append('file[]', source[i]);
        }

        data.append('ajax', true);
        data.append('expire', expire);

        return data;
    };

    setProgress = function(value){
        if(o.options.progressBar !== undefined){
            o.options.progressBar.style.width = value ? value + '%' : 0;
        }

        if(o.options.progressText !== undefined){
            o.options.progressText.innerText = value ? value + '%' : '';
        }
    };

    o.uploader = function(options) {
        o.options = options;

        if(o.options.files !== undefined){
            ajax(getFormData(o.options.files.files, o.options.expire.value));
        }
    };
}(app));

Ajax code:
document.getElementById('submit').addEventListener('click', function(e){
    e.preventDefault();
    var f = document.getElementById('file'),
        pb = document.getElementById('progressbar'),
        pt = document.getElementById('progressbar-text'),
        btn = document.getElementById('submit'),
        expire = document.getElementById('expire');

    btn.innerHTML = "Chargement en cours …";
    btn.disabled = true;

    app.uploader({
        files: f,
        progressBar: pb,
        progressText: pt,
        processor: 'upload.php',
        expire: expire,

        finished: function(data){
            //

        },

        error: function() {
            alert('Erreur ! veuillez réessayer SVP');
        }
    });

});


text:
Q: BeautifulSoup get text from tag searching by Title I'm scrapping a webpage with python that provides different documents and I want to retrieve some information from them. The document gives the information in two ways, there's this one where it gives it like this: Company name: Company name which is solved in this question, and another one that goes like Title: and then all the text on a separate block of text, here's an example of this second html starting at div with class DocumentBody:

...

...

...

...

...

...

         ...
         Denomination:

Information about denomination

At first I tried hardcoding the xpath to the text, but the problem is that the html from the documents might change, they are not always the same.
This is an example of what I made to get the denomination:
from lxml import etree

class LTED:
   def __init__(self, url, soup):
      if(not soup)
         soup = get_soup_from_url(url, "html.parser")
         dom = etree.HTML(str(soup))

      # case document it's updated and not a new one
      self.corrigenda = bool(soup.body.findAll(text="Corrigenda"))

      self.denomination = self.get_denomination(dom)

   def get_denomination(self, dom):
      if self.corrigenda:
         item = dom.xpath("//div[@class='DocumentBody']/div[7]/div[2]/div/p[2]")[0].text
      else:
         item = dom.xpath("//div[@class='DocumentBody']/div[6]/div[2]/div/p[2]")[0].text
      return item

As the xpath is hardcoded, this works the majority of the time, but in some cases it gets another text because the html has changed.
How should I retrieve the text in this case? Is there any way to get Information about denomination searching by Denomination?
In case you want to check the webpage, here's a link to an example I'm trying to scrape

A: Link do not contain such Denomination but you can adapt and proceed like:
for e in soup.select('span:-soup-contains("Title:") + div'):
    print(e.get_text(strip=True))

In newer code avoid old syntax findAll() instead use find_all() or select() with css selectors - For more take a minute to check docs
Example
import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get('https://ted.europa.eu/udl?uri=TED:NOTICE:628602-2022:TEXT:EN:HTML&tabId=0',
                                  headers = {'User-Agent': 'Mozilla/5.0'}).text)

for e in soup.select('div.txtmark:-soup-contains("Official name:")'):
    print(e.next.split(':')[-1].strip())

for e in soup.select('span:-soup-contains("Title:") + div'):
    print(e.get_text(strip=True))

Output
KfW Bankengruppe
Vergabekammer Bund
Management of the PtX-Fund by the Power-to-X D&G GmbH (in formation)


text:
Q: Jenkins downstream jobs not triggering from Build Flow job I have installed an build flow plugin for polling and multiple jobs are running. At the end of execution, based on SUCCESS/FAILURE i'm trying to trigger a "Downstream job" which is not triggering.
Anyone faced the similar issue? or please help what could be the reason?

In the above screen shot i have a set of Jobs running in sequence/parallel (in define build flow using DSL section). and below that in "Post build actions section, configured downstream job named "STOP & FIX disable" which is not triggering after success in my case.

A: I have got an answer for this after spending long time. In the Flow section check "Flow run needs a workspace" and copy the content from "Define build flow using flow DSL" box and save it in a file(any name without extension) and provide the full path to the file path. It works!!


text:
Q: Filtering by one column based on the value of another Suppose I have a table, TestTable, that looks like this:
|-------------------|------------------|------------------|
|        Id         |    EventDate     |     EventCode    |
|-------------------|------------------|------------------|
|         1         |    2017-04-10    |        42        |
|-------------------|------------------|------------------|
|         2         |    2017-10-32    |        50        |
|-------------------|------------------|------------------|
|         3         |    2017-06-15    |        60        |
|-------------------|------------------|------------------|
|         4         |    2017-07-13    |        10        |
|-------------------|------------------|------------------|

I want to select only events that took place at a later Date than EventCode 60. Obviously, I could just create a temporary variable and use a WHERE clause:
DECLARE @TestEventDate DATETIME;
SET @TestEventDate =
    (SELECT TOP 1 EventDate
    FROM TestTable
    WHERE EventCode = 60);
SELECT *
FROM TestTable
WHERE EventDate > @TestEventDate

But I can't help but think here should be a way to do this without running multiple SELECT statements. Can I filter indirectly within the same SELECT, mapping an EventDate to an EventCode in the where clause without setting the temporary variable?
Here's the above set to a temporary table so that you can just run it straight in your SSMS:
DECLARE @TestTable TABLE(Id INT, EventDate DATETIME, EventCode INT);
INSERT INTO @TestTable(Id, EventDate, EventCode) VALUES (1, '20170410', 42);
INSERT INTO @TestTable(Id, EventDate, EventCode) VALUES (2, '20171030', 50);
INSERT INTO @TestTable(Id, EventDate, EventCode) VALUES (3, '20170615', 60);
INSERT INTO @TestTable(Id, EventDate, EventCode) VALUES (4, '20170713', 10);

DECLARE @TestEventDate DATETIME;
SET @TestEventDate =
    (SELECT TOP 1 EventDate
    FROM @TestTable
    WHERE EventCode = 60);
SELECT *
FROM @TestTable
WHERE EventDate > @TestEventDate

A: If EventCode is unique, you can do :
SELECT T2.*
FROM TestTable AS T
INNER JOIN TestTable AS T2 ON (T.eventdate > T2.eventdate)
WHERE T.EventCode = 60

A: It is possible to do the whole thing in a join. Basically you want to join all the records that fit the description to the record you want like this:
DECLARE @TestTable TABLE(Id INT, EventDate DATETIME, EventCode INT);

INSERT INTO @TestTable
    (Id,  EventDate, EventCode)
VALUES
    ( 1, '20170410',        42),
    ( 2, '20171030',        50),
    ( 3, '20170615',        60),
    ( 4, '20170713',        10);

SELECT
    T1.*
FROM
    @TestTable T1
    JOIN @TestTable T2
        ON T1.EventDate > T2.EventDate
        AND T2.EventCode = 60

A: One method is a subquery:
SELECT *
FROM TestTable
WHERE EventDate > (SELECT TOP 1 EventDate FROM TestTable WHERE EventCode = 60);

You could also use window functions:
select tt.*
from (select tt.*,
             max(case when eventcode = 60 then eventdate end) over () as eventdate_60
      from testtable tt
     ) tt
where eventdate > eventdate_60;


text:
Q: Sending a JSON object via Javascript POST request to a Rails controller I'm trying to submit a form in a Rails 5.1 app that uses Vue.js and Dropzone. During the sendingEvent I am using JSON.stringify on the object before sending it over to the controller. However, I don't feel this is the correct way to do it, as I am then having problems with using strong params in the controller.
JS:
import Vue from 'vue/dist/vue.esm'
import VueResource from 'vue-resource'
import vue2Dropzone from 'vue2-dropzone'

Vue.use(VueResource)

document.addEventListener('DOMContentLoaded', () => {
  if(document.getElementById('listing-multistep') !== null) {
    Vue.http.headers.common['X-CSRF-Token'] = document.querySelector('input[name="authenticity_token"]').getAttribute('value');
    var listingForm = document.getElementById('listing_form');
    var listing = JSON.parse(listingForm.dataset.listing);
    var locale = document.getElementsByTagName('html')[0].getAttribute('lang');
    const myForm = new Vue({
      el: '#listing-multistep',
      components: {
        vueDropzone: vue2Dropzone
      },
      data: function () {
        return {
          id: listing.id,
          locale: locale,
          slug: listing.slug,
          activeStep: 0,
          // More data
          dropzoneOptions: {
            url: `/${locale}/listings`,
            method: 'post',
            acceptedFiles: 'image/*',
            uploadMultiple: true,
            autoProcessQueue: false,
            parallelUploads: 15,
            maxFiles: 15,
            addRemoveLinks: true,
            thumbnailWidth: 150,
            maxFilesize: 5,
            dictDefaultMessage: "<i class='fa fa-cloud-upload'></i> Drop files here to upload (max. 15 files)",
            headers: { 'X-CSRF-Token': Vue.http.headers.common['X-CSRF-Token'] }
          }
        }
      },
      methods: {
        sendingEvent: function(file, xhr, formData) {
          // This function gets called by Dropzone upon form submission.
          var listingObj = this.setupListingObj()
          formData.append('listing', JSON.stringify(listingObj))
        },
        listingRedirect: function(files, response) {
          window.location = `/${this.locale}/listings/${response.slug}`
        },
        submitListing: function() {
          var numFiles = this.$refs.listingDropzone.getAcceptedFiles().length
          // If there are images to upload, use Dropzone
          // Else submit the form normally.
          if(numFiles > 0) {
            this.$refs.listingDropzone.processQueue()
          } else {
            var listingObj = this.setupListingObj()

            if(this.id === null) {
              // POST if it's a new listing
              this.$http.post(`/${this.locale}/listings`, {listing: listingObj}).then(
                response => {
                  window.location = `/${this.locale}/listings/${response.body.slug}`
              }, response => {
                console.log(response)
              })
            } else {
              // PUT if it's an existing listing
              this.$http.put(`/${this.locale}/listings/${this.slug}`, {listing: listingObj}).then(
                response => {
                  window.location = `/${this.locale}/listings/${response.body.slug}`
              }, response => {
                console.log(response)
              })
            }
          }
        },
        setupListingObj: function() {
          // do some processing...

          var listingObj = {
            id: this.id,
            name: this.name,
            // set more attributes
          }
          return listingObj
        },
      }
  }
});

as you can see I am using formData.append('listing', JSON.stringify(listingObj)) on the sendingEvent.
My controller:
class ListingsController < ApplicationController

  def create
    @listing = Listing.new JSON.parse(params[:listing])
    @listing.owner = current_user
    respond_to do |format|
      if @listing.save
        format.html { redirect_to listing_path(@listing), notice: 'Listing was created successfully!' }
        format.json { render :show, status: :created, location: @listing }
      else
        format.html { render :new }
        format.json { render json: @listing.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def listing_params
    params.require(:listing).permit(
      :name,
      :bedrooms,
      :beds,
      :bathrooms,
      :price_cents,
      :price_currency,
      :property_type,
      :city,
      :state,
      :address,
      :lat,
      :lng,
      :description,
      :amenities => []
    )
  end
end

It seems to work in development, but when I run a test with this code in RSpec I get errors like:
Internal Server Error no implicit conversion of ActionController::Parameters into String

When I try to swap @listing = Listing.new JSON.parse(listing_params) it fails to work in development.
I have a feeling I'm not sending the form data across properly. What is the correct way to send the data over via Javascript to my Rails controller? Does it need to be strigified and then posted? How can I access it via strong params instead?
Thanks in advance!
UPDATE
This is what my spec looks like:
RSpec.feature 'Listing owners can create new listings' do
  let(:owner) { create(:user, :owner) }

  before do
    login_as owner
    visit new_listing_path
  end

  scenario 'successfully', js: true do
    fill_in 'Property name', with: 'Example property'
    select 'Apartment', from: 'Property type'
    fill_in 'Address', with: 'Somewhere'
    click_button 'Next'

    fill_in 'Property description', with: Faker::Lorem.paragraph(2)
    click_button 'Create Listing'

    expect(page).to have_content 'Listing was created successfully!'
  end
end

I am using Chrome headless for these tests in order to parse the Vue.js stuff on the form. In my rails_helper.rb I have:
require 'spec_helper'
require 'rspec/rails'
require 'capybara/rails'
require 'capybara/rspec'
require 'pundit/rspec'
require 'selenium/webdriver'

RSpec.configure do |config|
  # ...
  Capybara.javascript_driver = :headless_chrome
end

and I have a support/chrome_driver.rb file with the following:
Capybara.register_driver(:headless_chrome) do |app|
  capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
    chromeOptions: { args: %w[headless disable-gpu] }
  )

  Capybara::Selenium::Driver.new(
    app,
    browser: :chrome,
    desired_capabilities: capabilities
  )
end


text:
Q: Why is bundle update taking so long? I am upgrading my Rails app to use Ruby 2.1 and am updating my gems. However, when I run bundle update it is taking an incredibly long time to complete (3+ hours on the last run).
Any suggestions for fixing this would be greatly appreciated.
Here is my current gemfile:
source 'http://rubygems.org'

gem 'rails', '~> 3.2.11'
gem 'mysql2', '~>0.3.10'
gem 'json', '1.7.7'
gem 'will_paginate', '~> 3.0'
gem 'carrierwave'
gem "fog", "~> 1.3.1"
gem 'gibbon'
gem 'nokogiri'
gem 'premailer-rails3'
gem 'pg'
gem 'aws-s3'
gem 'amazon-ec2'
# Use unicorn as the app server
gem 'unicorn'
gem 'sidekiq'
gem 'rufus-scheduler'
gem 'exception_notification'
gem 'haml', '>= 4.0.0.rc.1'
gem 'html2haml'
gem 'state_machine'
gem 'garb', :git => 'git://github.com/Sija/garb.git'
gem "activerecord-import", ">= 0.2.0"
gem "hashie"
gem 'draper', '~> 1.0'
gem 'dotenv-rails', :groups => [:development, :test]
gem 'airbrake'
gem 'newrelic_rpm'

gem 'devise', '~> 2.2.4'
gem 'acts_as_tenant', :git => 'git://github.com/ErwinM/acts_as_tenant.git'

gem 'bourbon'
gem 'sass'
gem 'neat'
gem 'bitters'
gem 'middleman'

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'handlebars_assets', :git => 'git://github.com/leshill/handlebars_assets.git'
  gem 'jquery-rails', '~> 2.0.1'
  gem 'uglifier', '>= 1.0.3'
end

group :test do
  #gem 'webmock'
  gem 'vcr'
  gem 'launchy'
  gem 'database_cleaner'
  gem 'capybara', '2.0.0'
  gem 'shoulda'
end

group :development, :test do
  gem 'faker'
  gem "rspec-rails", "2.14.0"
  gem "factory_girl_rails", "~> 4.0", :require => false
  gem 'spork', '~> 1.0rc'
  gem 'guard-livereload'
  gem 'guard-jasmine'
  gem 'guard-spork'
  gem 'guard-rspec'
  gem 'jasminerice', :git => 'git://github.com/bradphelan/jasminerice.git'
end

group :development do
  gem 'rb-inotify', :require => false
  gem 'rb-fsevent', :require => false
  gem 'rb-fchange', :require => false
  gem 'pry'
end

Here is the last result I received:
Bundler could not find compatible versions for gem "thor":
  In Gemfile:
    rails (~> 3.2.11) ruby depends on
      railties (= 3.2.11) ruby depends on
        thor (< 2.0, >= 0.14.6) ruby

    jquery-rails (~> 2.0.1) ruby depends on
      thor (0.14.0)

A: You're including gems with incompatible dependencies. You cannot have both jquery-rails ~> 2.0.1 and rails ~> 3.2.11 as they have mutually exclusive requirements for versions of the Thor gem.
I would recommend removing the explicit version requirement for jquery-rails let Rails choose the version it needs based on its dependencies.


text:
Q: generics : getting parameterizedtype classname from a static method? I have a simple static method :
public static <U> U findStuff(String id) {
    // how can i get the class of type U here ?
    Class classObject = ....;

    return classObject.newInstance();
}

public static void main(String[] args) {
    MyEntity entity = MyClass.<MyEntity>findStuff("abc");
}

I wonder how i can get the class object from the U ?
Currently i have to pass the class around because i dont know the way yet.. so, now im using something like this  :
public static <U> U findStuff(Class<U> classObject, String id) {
    return classObject.newInstance();
}

public static void main(String[] args) {
    MyEntity entity = MyClass.findStuff(MyEntity.class, "abc");
}

A: To get the class of the object, use object.getClass();
By the way, this is a common way to do it that is not related to Generics

A: Does
Class<?> classObject = object.getClass();

do enough for you? It's not clear what you need em.find to do.
EDIT: Okay, with the edit, you're running into the problem of type erasure. Basically, you need to pass in the class you're interested in, as you're already doing. See the Java generics FAQ for more information. It's an unfortunate corollary of the way that Java generics are implemented :(

A: // because object extends java.lang.Object
Class<?> classObject = object.getClass();


text:
Q: GIDSignIn.sharedInstance()?.currentUser returns nil (when a user was previously signed in) for first few seconds when app launches I have an app whose layout is based on UINavigationControllers. This app has a RootVC that has a table view, and clicking its cells takes the users to different view controllers.
RootVC
|--- MainVC
|--- DiscussionsVC (Is GIDSignIn.sharedInstance()'s delegate and presentingViewController)
|--- InfoVC
In all of the child view controllers viewDidLoad method, I have added the following print statement:
print("Google User (View Controller Name): ", GIDSignIn.sharedInstance()?.currentUser)

Initially, MainVC is pushed on viewVillAppear of RootVC, making it the first screen visible to the user.
The value of currentUseris nil in RootVC and MainVC. However, if I go back to the RootVC and navigate to InfoVC or DiscussionsVC, then currentUser is not nil. So I tried making the first presented VC to InfoVC and now currentUser is nil there. So I changed the code for printing in MainVC and currentUser is not nil anymore.
DispatchQueue.main.asyncAfter(deadline: .now() + 30) {
   print("Google User (Main VC): ", GIDSignIn.sharedInstance()?.currentUser)
}

I think it takes some time for the value of currentUser to not be nil. So I have 2 questions:

*

*What is the appropriate amount of time to wait before checking for currentUser

*Is there something that I can add to make the setting of currentUser instantaneous? Some post suggested adding this, which did not help.

if(GIDSignIn.sharedInstance().hasPreviousSignIn()) {
    GIDSignIn.sharedInstance()?.restorePreviousSignIn()
}

Edit 1
I tried adding the following lister as mentioned in the answer, but user is still nil after a long time.
Auth.auth().addStateDidChangeListener { (auth, user) in
    print("Auth state changed: \n AUTH: \n\(auth)\nUSER \n\(user)")
    if let user = user {
        print("User is not nil")
    }
}

This is how I am signing the user in initially, am I missing something with the firebase auth?
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
            // ...
            if let error = error {
                // ...
                print("Error signing in")
                print(error)
                return
            }

            guard let authentication = user.authentication else { return }
            let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                           accessToken: authentication.accessToken)

            Auth.auth().signIn(with: credential) { (authResult, error) in
                if let error = error {
                    print("authentication error \(error.localizedDescription)")
                }
            }
            setUserProfileImage()
        }

Edit 2
I think it's working now after I enabled Google signin via firebase console. Though it said in the console that Google sigin is enabled by default for iOS and Web.

A: This is the expected behavior. Firebase Authentication is based on a combination of a long lived refresh token, and short lived ID tokens. When the app is started, Firebase connects to the server to get a new ID token. While this call is going on, the currentUser is nil.
To better respond to the user authentication state, use an authentication state listener as shown in the documentation on getting the current user:
Auth.auth().addStateDidChangeListener { (auth, user) in
  // ...
}

This callback will automatically be called by Firebase once it has (succeeded or failed to) refresh the ID token.


text:
Q: Construction of continuous-time markov chain and finding stationary distribution There are 15 lily pads and 6 frogs. Each frog, with rate 1, jumps to one of the other 9 unoccupied pads chosen uniformly at random.
What is the stationary distribution for the set of occupied lily pads?
This is from Durrett's Essentials of Stochastic Processes.
I thought we would consider all possible combinations of occupied pads as states of a continuous-time Markov chain, so $15\choose6$ states. From there I suspect the stationary distribution is $\frac{1}{15\choose6}$ for every state. Is this a correct formulation? I am new to the subject of CTMC's so am not very sure in my answer.

A: Yes, the states all have the same probabilities in the stationary distribution.  This is easy to see once you notice that the process is reversible: given two states $s_1$ and $s_2$ such that a transition from $s_1$ to $s_2$ is possible (by moving one frog), the rate of jumps from $s_1$ to $s_2$ when in state $s_1$ is the same as the rate of jumps from $s_2$ to $s_1$ when in state $s_2$.


text:
Q: ScopedModel in Flutter I am trying to create a scoped model in my project , but something is going wrong ..
Model class :
 class CartonModel extends Model{
  bool playerState = false;
  bool get getPlayerState => playerState ;
  void stateOff(){
  playerState = false ;
  notifyListeners();
  }
  void stateOn(){
    playerState = true ;
     notifyListeners();
  }
}

Material App wrapped with Scoped Model :
ScopedModel<CartonModel>(
  model: new CartonModel(),
  child: new MaterialApp( // some code )

i am using ScopedModelDescendant on an Icon Button :
ScopedModelDescendant<CartonModel>(
      builder: (context, child, CartonModel model) =>
          new IconButton(
            icon: new Image.asset(imageUrl),
            iconSize: dimenRatio * 0.25,
            onPressed: () {
              Future<void> bottomSheetAwaitClose =
                  showModalBottomSheet<void>(
                context: context,
                builder: (BuildContext context) {
                  return MusicR();
                },
              );

              bottomSheetAwaitClose.then((void value) {
                model.stateOff();
              });
            },
          ),
    ),

I have imported all required packages and provided types to ScopedModel<> and ScopedModelDescendant<> , but still getting this runtime error :
Could not find the correct ScopedModel.
is there any thing wrong in this code ? please help

A: If your CartonModel class is declared in your main.dart, move it to a different file.
And make sure you declare your imports in the form 'package:<projectname>/cartonmodel.dart'


text:
Q: solr - search with a trailing wildcard does not return the expected results I have this document indexed on Solr:
{
    "UUID": "4380",
    "QueryTerm": "stl3023",
    "Type": "unspecified",
    "HitCount": 1,
    "FieldName": "_suggest"
}

I am trying to retrieve this document by querying on QueryTerm field.
This field is defined as this in the schema.xml file:
<field indexed="true" name="QueryTerm" stored="true" type="textSplitConcat"/>
<fieldType class="solr.TextField" name="textSplitConcat" positionIncrementGap="100">
  <analyzer>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
    <filter catenateAll="1" catenateNumbers="1" catenateWords="1" class="solr.WordDelimiterFilterFactory" generateNumberParts="0" generateWordParts="0" splitOnCaseChange="0"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
  </analyzer>
</fieldType>

If I run a query with these parameters:
q=QueryTerm:l3023*
qt=standard
fl=*
q.op=AND
wt=javabin
version=2

I get no results.
But if I run a query without the trailing * it correctly retrieves the document I need:

Why does this happen? Shouldn't the trailing * match 0 or more characters (as stated here)?
I'm using Solr version 4.8.1.
The trailing * is added automatically by the web application and I'm not able to remove it, so I must get that document even with that trailing *. However I am able to change Solr's configuration in schema.xml file, if it may help in any way.

EDIT #1
After @MatsLindh's answer, I have tried to switch from WordDelimiterFilter to NGramFilter:
<fieldType class="solr.TextField" name="textSplitConcat" positionIncrementGap="100">
  <analyzer>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
    <filter class="solr.NGramFilterFactory" minGramSize="3" maxGramSize="256"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
  </analyzer>
</fieldType>

But I still don't get any results when I run the query with the trailing *:

This is a screenshot from the analysis tool:

I still don't get it. The analysis tool shows a match, but the query does not return any result. What am I not getting about this?
Instead, the query without the trailing wildcard still returns the document.

EDIT #2
After EDIT #1 I have not re-indexed my content and that was the problem. Now I have done it and Solr correctly finds the document I expect with the query QueryTerm:l3023*.

A: When you're using a wildcard most of the analysis chain is skipped (only filters that are multiterm aware are applied - which means that usually only the LowercaseFilter).
In your case the WordDelimiterFilter changes the tokens in a way that there are no tokens stored that begins with l3023. You can use the Analysis page under the Solr admin to see how the incoming text is processed and see what tokens are generated.
The matching content in your example is 3023 - the stl part doesn't generate a hit (and since your query is for l3023 and not stl3023 the concatenate part of the word delimiter filter doesn't matter (since the token stored is stl3023, not l3023.
If you want to perform matches inside a token, you might want to look at generating ngrams instead.
PS: For 8.x you should probably use the graph filter version of the word delimiter filter instead.


text:
Q: CakePHP how to modify validation from shell script I'm using CakePHP v2.6 and I'm writing a shell script which needs to have slightly different validation rules then those in the $validates property of the model.
I've read the section of the book about modifying validations on the fly, but all the examples are from within a model. And when I try to do $this->MyModel->validator() in the shell script, I get:
Fatal Error Error: Call to undefined function validator()

Why is this?
Update: Strangely, the following code DOES work:
unset($this->MyModel->validate['fieldName'] );

My code:
<?php
App::uses('AppShell', 'Console/Command');
App::uses('CakeSchema', 'Model');

class ScrapeShell extends AppShell {

    public $uses = array('Listing', 'Neighborhood', 'ListingPhoto');

    function __construct() {
       parent::__construct();
       //initialize some variables
   }

   public function myMethod() {

       #bypass validation on description to allow HTML
       unset($this->Listing->validate['description'] ); //this works
       //$this->Listing->validator()->remove('description', 'noTags'); //this errors
       ...

A: At least part of the problem is that you've broken CakePHP's shell construction.
You need to change your __construct method to read as follows:
public function __construct($stdout = null, $stderr = null, $stdin = null) {
    parent::__construct($stdout, $stderr, $stdin);
    //your code here
}

As for the model's child objects, it's hard to say what could be interfering with that instantiation without seeing your model code, but if you've overwritten model constructors too, that can interfere with the proper model setup.

A: Are you sure your shell and web app are running the same CakePHP core version? Try to debug the CAKE_CORE_INCLUDE_PATH.
I'm using a global version myself, so when I just call "cake" it will execute the global version, if I call .\bin\cake it will use the one from the repo (3.0 in this case)
And are you sure the app is finding the right core version? The second line of core in question will work in any case because it was there before 2.6. I'm pretty sure your model does not exist the correct version of the core Model class.


text:
Q: Modify protected value with structure I've got a class:
class Fruit
{
protected:
    int Vitamins
    [...]
public:
    [...]
}

a structure:
struct InTheMatrixFruit
{
  int           vitamins;
  virtual       ~InTheMatrixFruit();
};

and a function which takes a reference on Fruit:
void function(Fruit &fruit);

in this function if I write:
reinterpret_cast<InTheMatrixFruit&>(fruit).vitamins = 300;

It does modify the vitamins protected value.
But, If I remove the virtual like this:
struct InTheMatrixFruit
    {
      int           vitamins;
      ~InTheMatrixFruit();
    };

It doesn't work anymore.
Why it works with virtual and not without ?
I'm thinking about the VTables.
Thanks in advance :)

A: Because the size of the class instance changes and, with it, the offset to the vitamins member. This is beacuse a virtual function will cause a vtable pointer to be stored inside the instance before the memory allocated to the member, as you guessed.
Beware! reinterpret_cast could kill your kittens!

A: Your declaration of Fruit probably contains at least a virtual function.
In common implementations of virtual functions a virtual table is used. A pointer to the virtual table is stored as the first element in the memory representation of your object. It doesn't matter where you declare a virtual function, the virtual table will always be at the beginning.
So by declaring a virtual function in InTheMatrixFruit you create a "padding" before the int vitamins so it matches with the vitamins of Fruit.


text:
Q: GCC Linker Script Ignore PHDR / PHDRS? I'm trying to target a flat file for the output of my code, where I don't want PHDR.  But it seems no matter how I set things up, in modern GCC versions, I can't avoid PHDR.
Either I get PHDR segment not covered by LOAD segment or if I define a PHDRS property as in my linker script as follows:
PHDRS
{
    header PT_NULL FILEHDR;
    text PT_NULL PHDRS;
    data PT_NULL FILEHDR;
}

but throw it out, I get the error no sections assigned to phdrs
I can't seem to find any way to force GCC to just trust me and not emit the PHDRs.  What can I put in my linker script to tell GCC that I really mean it.
EDIT
I found this: https://sourceware.org/bugzilla/show_bug.cgi?id=25585
If I add the following to my GCC invocation, it seems to output the binary anyway: -Wl,--noinhibit-exec
But, it now includes extra header data in the middle of the binary image.

A: I found a solution!
Either have an empty PHDRS {...} definition at the top (or it seems maybe you don't need it).
Then, in your sections, be sure to discard phdr and contain all the troublesome sections.
/* If we're on a newer compiler */
/DISCARD/: {
  *(.interp)
  *(.dynsym)
  *(.dynstr)
  *(.hash)
  *(.gnu.hash)
  *(.header)
} : phdr

A: If you want to generate a flat binary file, then you could just specify the output format to be "binary".
Not sure it's what you want
A long time a ago, when I was looking into bootloaders, I was generating the MBR using exactly that.


text:
Q: How to write ceil and floor in latex? Is there a macro in latex to write ceil(x) and floor(x) in short form? The long form
\left \lceil{x}\right \rceil

is a bit lengthy to type every time it is used.

A: *

*You can define your own macro via the \def command anywhere in
your    document. For example
\def\lc{\left\lceil}
\def\rc{\right\rceil}

and then just write \lc x \rc.

*Or you use the \providecommand in the preamble, e.g.
\providecommand{\myceil}[1]{\left \lceil #1 \right \rceil }

to simply use \myceil{x} in your document.

*Use an editor, like vim, that allows for defining shortcuts for
quick and efficient editing.

*And, finally, don't forget about readability of your tex document. Check out this
thread
for some instructive comments on how to write efficient and readable
tex math docs.

A: Using \DeclarePairedDelimiter from mathtools, you could define macros \ceil and \floor, which will scale the delimiters properly (if starred):
\documentclass{minimal}
\usepackage{mathtools}
\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}

\begin{document}
  \begin{equation*}
    \floor*{\frac{x}{2}} \leq \frac{x}{2} \leq \ceil*{\frac{x}{2}}
  \end{equation*}
\end{document}

Result:

A: This will also work fine without using mathtools.
\newcommand{\floor}[1]{\lfloor #1 \rfloor}

A: There is no need to use mathtool here:
\newcommand{\floor}[1]{\left\lfloor #1 \right\rfloor}
\newcommand{\ceil}[1]{\left\lceil #1 \right\rceil}

is better than mathtool.


text:
Q: Allow multiple iTerm2 window I'm using iTerm2 with XtraFinder. XtraFinder allow you to open a terminal in the current folder.
In version <= 2.1.4, it works great.
When I upgraded to version 3.0.9, it never opens a new iTerm2 window.
Instead, it activates the iTerm2 window, no new tab, no new window, so it's not functioning at all.
Anyone know how to fix that?


text:
Q: How to make sure an Android App works on most smartphones? How can i make sure that my android app works on majority of the devices in the market. What testing tools do i have to use? Obviously if there are 12 or more smartphones in the market then i cannot buy each of them to test my app.So what should i do? Wonder if "Dvice Anywhere"(http://www.deviceanywhere.com/) can help us in this regard?
Does firmware or OS version also matters (1.5,1.6, 2.0, etc.)?
Please comment and explain.


text:
Q: Can I modify an app manifest and re-sign the SharePoint .app file? I am building a SharePoint 2013 provider-hosted app using the high-trust model.  This allows a customer to deploy the .app to their App Catalog and make it available to all SharePoint Sites.  The provider-hosted portion of the app runs in an IIS box (cluster) which the customer also deploys (on-premise) with setup instructions and automated tools.
The .app file structure includes the application manifest - which specifies the precise endpoint where the provider-hosted portion resides, and also specifies whitelisted endpoints which the add-in can call.  These are all specified by entering in URLs, hostnames, and port numbers into edit fields in Visual Studio in the 'Deploy App' form just before the .app file is built and digitally signed.
This seems to work just fine for a single app built by IT folks internally, if the org is small enough... but I really want to be able to distribute this solution to more than one customer. In order to do so, I would have to ask the customer for their respective endpoints, enter them into my build tools, and rebuild the .app for them.  This just doesn't seem right... no customer wants to talk to the developer first and have a custom-built app. And why should they? No code is changing...
Upon investigation into the .app file format, it turns out it is really just a simple .zip file - and inside (voila!) there is the app manifest! Unfortunately, if you edit the app manifest and re-zip the file, the digital signature is broken, and the .app no longer works. (grrrr...)
What I want to do is simply reconfigure the app manifest to match the environment where it is deployed. This can happen programmatically during setup/installation time, or perhaps even just prior to download, but cannot be a process that involves developers typing into visual studio and pressing Rebuild. That simply won't scale.
Is there a tool that exists that can help with this problem? If not, does anyone have experience with the signing of .app files programmatically? I'm open to skinning this cat in any way possible.

A: This is a wild idea and not maybe even possible.

*

*Create web ui, where clients enter their endpoints.

*Have internal process that invokes MSBUILD/TFS to package app with endpoint

*

*change app manifest with pre-build powershell

*Then provide app via email or download?
http://www.sharepointconfig.com/2013/10/building-sharepoint-2013-apps-with-tfs-2013/

A: This is more of a workaround than a true answer - but would work:
For on-premise deployments of high-trust SharePoint 2013 apps - build the application with "known endpoints" - essentially hard-coded endpoints that can be deployed locally. Then instruct the customer to redirect those endpoints using DNS records or hosts file entries.  In addition, the client would need to generate a local wildcard certificate signed by their own trusted root in order to satisfy the SharePoint 2013 app model requirements for appdomain and server-to-server communication.
This is by no means ideal, but for certain environments it might be the most practical approach. This also allows scaling for the IIS WebApp to occur at the customer-site, where it realistically belongs for a high-trust app.
This approach avoids the need to automate build tools and also avoids building a separate instance for every customer - both of which are somewhat undesirable. It might, for those reasons, be slightly less costly - but it also pushes some responsibility to the customer. Namely - hard-coding a DNS entry locally for machines in the topology.


text:
Q: Which method in EF5 is in charge of creating database I have a couple of questions:

*

*In EF5 code first API which method is in charge of checks if database exits, and if it's not the case which method creates DataBase?

*if i use EF code first i my DAL project and i want EF to generate other database for testing purpose can i do this by using ef? I've already changed initial catalog in connection string to check if it creates other database but it does not and threw exception

*By using ef Code-First or DataBase-First, we finally have DbContext class, EF5 how knows we used which method for it's internal actions?
Thanks.

A: Api for check if exists Context.Database.Exists();
and Context.Database.CreateIfNotExits();
As soon as you access EF Context it starts doing things.
There is default behavior you can manipulate things.
A context can be Open again different DB Instances yes.
You can even use it to create different DBs on SAME Server.
Careful use of the constructor and corresponsing API.CONFIG setting is required.
<connectionStrings>
<add name="YouCanHaveManyofTheese"
     connectionString="Data Source=localhost;Initial Catalog=DIFFERENT DBNAME ;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework"
     providerName="System.Data.SqlClient" />

Also
Check out Database.SetInitializer();
Ef Knows if it created the DB, or migrated the DB.  The actions are recorded here.
[dbo].[__MigrationHistory]


text:
Q: Select rows from many User I have many people in a table e.g.
Name    Grade (INT)
Jim     50%
John    86%
Jane    65%
Joanne  75%
Stewart 95%
Kate    23%
Betty   98%
Bill    73%
Bobby   54%

I want to SELECT the top 3 people from the table.

A: If you want any three users then it will help you
SELECT * FROM table_name ORDER BY Grade desc LIMIT 3

A: Use in operator and a subquery:
select * from {table} where {column} in (select top 3 {column} from User)

Hope it helps!

A: Try like this

select * from table where column in ('abc','def', ...) limit 3

A: try
select * from table where field LIKE('asd', 'def', ...)


text:
Q: Convert video changing only bitrate I have a mediaplayer program which lags playing one specific file. My assumption is that it is because of too high video bitrate (41.3 Mbps) and too slow CPU (it is embedded system). So, I want to be sure that bitrate is the case.
The question is: how can I convert videofile, changing only video bitrate? I can use avconv or any other package from Debian repos.

A: To keep a stream in file intact while transforming it with avconv (audio in your case), use -codec:[stream_specifier] copy - thus -codec:a copy or -acodec copy in your particular case (see the avconv(1) man page).
However, changing the bitrate means re-encoding the whole video - I take it you are playing something like FullHD. To re-encode it while minimizing the picture quality loss would take significant amount of time even on a fast machine. I would suggest first trying to rule out other things like broken file, display driver speed etc. First try another files with similar bitrate. Then try to scale the picture down: on slow desktop systems, I found it often helps to reduce the frame resolution. In mplayer or mpv this can be achieved with:
$ mpv -vf scale=480 -sws=4

which for FullHD just drops every three out of four pixels (in every direction - hence you'll get every 16th pixel in a plane). If that helps, fiddle with the desired resolution and software scaler algorithm to achieve the best still watchable result.
Last but not least, you are not mentioning what kind of system you have. These days many come with hardware assisted decoding (and encoding) capabilities - are you sure your system lacks it or has it enabled?


text:
Q: Listview with objectdatasource Delete not working i have one Listview in my Usercontrol & 1 objectdatasource binded with the ListView.
now in objectdatasource's Deletemethod i have taken businessobject as argument but at runtime i am not getting value in my businessobject's properties...
i also tried to use "Bind" instead of "eval" in ItemTemplate. but not getting any value at runtime in my DeleteMethod provided in objectdatasource's Deletecommand...
can anybody help to know weather i am mising anything or what?
my Listview's ItemTemplate
 <ItemTemplate>
            <asp:HiddenField ID="hidUserAchievementInfoId" runat="server" Value='<%# Bind("UserAchievementInfoId") %>' />
            <asp:HiddenField ID="hidUserIdField" runat="server" Value='<%# Bind("UserId") %>' />

                    <asp:Label ID="AwardLabel" runat="server" Text="Award "></asp:Label>

                    <asp:Label ID="lblAward" runat="server" Text='<%# Bind("Awards") %>'></asp:Label>

                    <asp:Label ID="FieldofAwardLabel" runat="server" Text="Field of Award "></asp:Label>

                    <asp:Label ID="lblFieldofAward" runat="server" Text='<%# Bind("FieldofAward") %>'></asp:Label>

                    <asp:Label ID="TournamentLabel" runat="server" Text="Tournament "></asp:Label>

                    <asp:Label ID="lblTournament" runat="server" Text='<%# Bind("Tournament") %>'></asp:Label>

                    <asp:Label ID="AwardYearLabel" runat="server" Text="Award Year "></asp:Label>

                    <asp:Label ID="AwardYear" runat="server" Text='<%# Bind("AwardYear") %>'></asp:Label>

                    <asp:Label ID="AwardDescriptionLabel" runat="server" Text="Description "></asp:Label>

                    <asp:Label ID="lblAwardDescription" runat="server" Text='<%# Bind("AwardDescription") %>'></asp:Label>

                    <asp:LinkButton ID="EditButton" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>

                    <asp:LinkButton ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete"></asp:LinkButton>

        </ItemTemplate>

Delete Method used in objectdata
  source's Deletecommand

    public void DeleteUserAchievementInfo(UserAchivementInfoBO BOInstance)
    {
        try
        {
    Int64 UserAchievementInfoId=BOInstance.UserAchievementInfoId
            objUserBasicInfoServiceClient.DeleteUserAchievementInfo(UserAchievementInfoId);
        }
        catch (Exception ex)
        {
            HandleException.LogError(ex);
        }
    }

A: Try to add the business object key field(e.g id, key...) to the listview datakeynames property. By doing this, you can at least get the key value in the deleting event.


text:
Q: Why is the derivative Operator defined over $C^2([-1,1])$ not closed? The question is: Let A be the Operator defined by $A:C^2([-1,1])\subset C([-1,1])\to C(-1,1]),\; x\mapsto x'$. Show that the operator is not closed.
I suppose an example where a derivative sequence converge to a point that is not in the graph of A would suffice, but isn't a property of a sequence of differentiable functions $f_n$, that if the sequence of derivatives $f'_n$ converges uniformly to a function $g$, then the sequence of functions converges to a function $f$ with $f'=g$?
Thank you in advance.

A: Comment: "Not closed" would be shown by an example where
$$
f_n \to f,\qquad f_n' \to g,\qquad f' \ne g
\tag1$$
Of course the derivative operator is closed in the $C^2$ metric.  But perhaps the way of stating it $$C^2([-1,1])\subset C([-1,1])\to C(-1,1])$$ is meant to mean in the $C$ topology, that is: uniform convergence.
So find an example of $(1)$ where $f_n, f \in C^2$, $f_n',g \in C$, and $\to$ means uniform convergence.


text:
Q: Solution to $x^2 \equiv 1$ (mod $pq$), $p,q \geq 3$ primes. Found the following piece online and got stuck:
Let $p,q \geq 3$ be different primes. Show that there is an integer $x$ such that $x^2 \equiv 1$ (mod pq) with $x$ neither congruent with $1$ or $−1$ (mod pq).
Would appreciate some help.

A: By Bezout we have $Ap+Bq=1$. Now consider $x=Bq-Ap$, modulo $p$ and $q$.

A: By the Chinese Remainder Theorem, there exists $x$ such that $x \equiv 1 \pmod{p}$ and $x \equiv -1 \pmod{q}$.  Then $x^2 \equiv 1 \pmod{p}$ and $x^2 \equiv 1 \pmod{q}$, so again by (the uniqueness part of) the Chinese Remainder Theorem it follows that $x^2 \equiv 1 \pmod{pq}$.  However, we cannot have $x \equiv 1 \pmod{pq}$, or this would imply $x \equiv 1 \pmod{q}$, so $1 \equiv -1 \pmod{q} \Rightarrow q \mid 2$ contradicting the assumption that $q \ge 3$.  Similarly, from $p \ge 3$ we get $x \not\equiv -1 \pmod{pq}$.

A: I prefer somehow to have a "structural" explanation. By the CRT, we have an isomorphism of rings $\mathbf Z/pq\cong \mathbf Z/p \times \mathbf Z/q$. For $x \in \mathbf Z$, let us adopt the obvious notation $x_{pq}=(x_p , x_q)$ in the respective quotient rings. We must solve ${x_{pq}}^2=1_{pq}$ , or equivalently $(x_{pq}-1_{pq})(x_{pq}+1_{pq})=0_{pq}$, but we cannot conclude directly because $\mathbf Z/pq$ admits divisors of zero, i.e. this ring is not a domain. Working in $\mathbf Z/p \times \mathbf Z/q$ instead, we get immediately the necessary and sufficient condition $x_p=\pm 1_p$ and $x_q=\pm 1_q$ because $\mathbf Z/p$ and $\mathbf Z/q$ are fields. Moreover, $x_{pq}=1_{pq}$ iff $x_p=1_p$ and $x_q=1_q$. This means that, if $p$ and $q$ are odd, the non trivial solutions (viewed in $\mathbf Z/pq\cong \mathbf Z/p \times \mathbf Z/q$ ) are $(1_p , {-1}_q), ({-1}_p , 1_q)$ and $({-1}_p , {-1}_q)$ .


text:
Q: Using laravel {{ }} in @foreach Could someone explain to me why this syntax doesn't work?
@foreach({{ ($arrayOfProducts->count()/3 == 0) ? '$arrayOfProducts as $item' : '$arrayOfProducts->chunk(($arrayOfProducts->count()/3)) as $chunk' }})

@endforeach

A picture of the code

A: You need to learn basic syntax.
@foreach($arrayOfProducts as $product)
  {{ $product->someAttr }}
@endforeach

This would work just fine, behind the scenes it's just basic PHP foreach loop, and {{ }} is just echo, also try to keep that conditional logic in your controller for more readable code.

A: If you look at the documentation you need to use the @foreach / @endforeach in a similar way as the standard php foreach loop.
In your code you are actually passing strings as arguments of your loop. if you want to make it work you need to pass your condition on $arrayOfProductsand then loop over it.
@foreach(($arrayOfProducts->count()/3 == 0) ? $arrayOfProducts : $arrayOfProducts->chunk(($arrayOfProducts->count()/3))) as $item)

{{ dump($item) }}

@endforeach

A: Why not :
@if($arrayOfProducts->count()/3 == 0)
   @foreach($arrayOfProducts as $item)
     {{$item}}
   @endforeach
@else
   @foreach($arrayOfProducts->chunk(($arrayOfProducts->count()/3)) as $chunk)
     {{$chunk}}
   @endforeach
@endif

Don't try to use ternary operator in that way, it's cleaner like this and it's readable for you for the future, at least everytime you'll see the code you'll instantly know what it does

EDIT: ->count() is there like this only because arrayOfProducts is actually a collection?