text:
Q: Filename image as Automatic caption I am using this script to display random images from a folder. I have hundreds of images  with significant filenames, So I'm looking for a way to display each image file name as an image caption. Is this possible?
this is the script Im using:
<?php
/*
By Matt Mullenweg > http://photomatt.net
Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
Latest version always at:

http://photomatt.net/scripts/randomimage

*/// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';

// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';

$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';

$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along

header('Location: '.$folder.$files[$rand]); // Voila!
?>

A: If all you want to do is continue to display a single random image then remove (or comment out so you can restore it if you later want to) the header line and at the end of the file add the following lines underneath it:
//header('Location: '.$folder.$files[$rand]); // Voila!
echo $files[$rand];
?>

<img src="<?php echo $folder.$files[$rand] ?>" />

You might want to add some css styling to set the display size of the image, and to format the caption above it.


text:
Q: Будет ли утечка памяти, если конструктор бросит исключение? Есть некая фабрика:
TBar * foo()
{
    return new TBar();  // здесь конструктор TBar бросает исключение
}

Если конструктор TBar бросит исключение, мы получим утечку памяти, выделенной для нового объекта TBar. Верно?

A: Вот что написано в стандарте С++ 2011
15.2.2

An object of any storage duration whose initialization or destruction is
terminated by an exception will have
destructors executed for all of its
fully constructed subobjects
(excluding the variant members of a
union-like class), that is, for
subobjects for which the principal
constructor (12.6.2) has completed
execution and the destructor has not
yet begun execution. Similarly, if the
non-delegating constructor for an
object has completed execution and a
delegating constructor for that object
exits with an exception, the object's
destructor will be invoked. If the
object was allocated in a
new-expression, the matching
deallocation function (3.7.4.2, 5.3.4,
12.5), if any, is called to free the storage occupied by the object.

В общем, если конструктор был прерван исключением, то  вызываются деструкторы всех уже созданных объектов, а динамическая память, выделенная под основной класс, будет освобождена соответствующим delete.
Итого, утечки не будет, в том числе и при наличии базового класса, если, конечно, нет внутренних утечек памяти.
A: Нет, неверно.
Если не рассматривать выделения памяти внутри конструктора TBar, то утечек не будет. В языке C++ объект считается созданным только в тот момент, когда его конструктор завершит выполнение без ошибок. Здесь этого не происходит, поэтому объект никогда не был создан, а, значит, и память под него "как бы" не выделялась. Т.е. компилятор обязан корректно освободить память, в которой будет находится объект, в случае исключения в его конструкторе.
A: Утечка будет, если у класса TBar есть хотя бы один базовый класс. В этом случае, если будет брошено исключение в конструкторе TBar, то деструкторы для всех базововых классов вызваны не будут. Поскольку объект еще полностью не был создан.
Если есть опасение, что в конструкторе будет сгенерировано исключение и это приведет к фатальным последствиям для программы, то рекомендуется весь код всех конструкторов помещать в блог try. И придумать способ извещения о корректности создания объекта (типа IsValid()).
TBar::TBar()
{
    try {
        ...
    }
    catch (...)
    {
    }
}

A: Если исключение на перехватывать, то утечки не будет, так как программа аварийно завершится, если же его просто как-нибудь обработать, то утечка будет по понятным причинам,
а если его обработать правильно (с очисткой памяти), то утечки тоже не будет.
имхо

redpajama_set_name: RedPajamaStackExchange


text:
Q: Question on coproducts and products Given a family of modules $\{A_i\}_{i \in I}$, I always understood that the main difference between an element of the product $\Pi A_i$ and the direct sum $\oplus A_i$ to be that if you take an element of the direct sum, it will have only finitely many of the terms coming from each module can be non-zero, where with the product, you can have as many terms as you want to be non zero.
Products and coproducts are basic concepts in category theory and the definitions are given as follows:
The product of a set of objects $\{C_i\}_{i \in I}$ in the category $C$ is an object $\Pi_{i \in I}C_i$ in $C$ together with maps $\pi_j: \Pi C_i \rightarrow C_j$ such that that for all object's $A \in C$ and every family of morphisms $\alpha_i: A \rightarrow C_i$, there exists a unique morphism $\alpha: A \rightarrow \Pi C_i$ such that $\alpha_i=\pi_i \alpha$
The coproduct of a set of objects $\{C_i\}_{i \in I}$ in the category $C$ is an object $\coprod C_i$ in $C$ together with maps $i_j: C_j \rightarrow \coprod C_i$ such that for every family of morphisms $\alpha_j: C_j \rightarrow A$ there is a unique morphism $\alpha: \coprod C_i \rightarrow A$
such that $\alpha i_j =\alpha_j$.

In the category of modules, the direct sum is the coproduct and the product is the product. I'm wondering, where in the category theoretic definitions of product and coproduct is my previous understanding (of an element of a direct sum being expressed as all but finitely many entries are non-zero where as in a product you can have an arbitrary number of the entries non-zero) expressed?.
Thanks.

A: Suppose that we wanted to determine $M=\coprod_{i\in I}C_i$ from the category theory definition. Think about what we know:

*

*$M$ is a module.

*For each $i$, there is a morphism $\iota_i : C_i \rightarrow  M$.
You can think of this defining an algebraic structure - just like the definition of a group or ring or module. So, we know that, if $c_1\in C_1$ and $c_2\in C_2$ then we know that $\iota_1 c_1 + 3\cdot \iota_2 c_2$ has to be in $M$, since it's a combination of elements we know must be in there. To be more explicit, the objects we are sure must be in the coproduct would have the form
$$\alpha_{1}\iota_{i_1}c_{1}+\alpha_{2}\iota_{i_2}c_{2}+\ldots + \alpha_{k}\iota_{i_k}c_{k}$$
where the $\alpha_j$ come from the ring of coefficients and $c_j$ come from the corresponding $C_{i_j}$. We can always group any pair of terms with the same $\iota_{i_1}$ and could move the $\alpha_i$ inside of the $\iota$s to just get that the only element's we're sure must be in such a structure a of the form
$$\iota_{i_1}c_1+\ldots + \iota_{i_k}c_k$$
for distinct $i_j$. While there are plenty of structures containing all this data (for instance: $M$ could be the zero module and all of these things could be equal!), the coproduct is the "freest" (initial) such structure, and hence contains only the elements that must be in $M$ and does not impose any extra relations between them. Since the set of expressions of the prior form do form a module under the right operations, we can find out that that is indeed the coproduct. Then, we can move to a less natural definition where we note that "finite sums of elements of $c_i$ under the inclusion maps" is easily isomorphic to "elements of the cartesian product $\prod_i C_i$ with only finitely many non-zero terms."
The product $M = \prod_i C_i$ invokes a different structure:

*

*$M$ is a module.

*For each $i$, there is a map $\pi_i : M\rightarrow C_i$.
This definition doesn't so much tell us about what the elements of $M$ are, but rather what we can do with them: for any element $m\in M$, we can extract an element of the cartesian product (of sets) $\prod_i C_i$ by applying each of the functions $\pi_i$ to $m$. The universal property says that $M$ is a terminal example of such an object, meaning that defining a map to $M$ is the same as defining a map to $\prod_i C_i$ such that each map to a coordinate is a morphism the corresponding to $C_i$. Of course, since this Cartesian product has the structure of a module where the morphisms into it are the same as the functions whose coordinates are each morphisms, this means that the product has to be $\prod_i C_i$.
Another, more formal way to deal with this is to note that in the category of $R$-modules,
$$\operatorname{Hom}(R, M) \cong M$$
where we can regard the set of maps between two modules as a module by pointwise operations. Note that this is essentially considering the family maps $f_m(r)=r\cdot m$ for $m\in M$. The universal property essentially says
$$\operatorname{Hom}(R, \prod_{i\in I}C_i) \cong \prod_{i\in I }\operatorname{Hom}(R, C_i) \cong \prod_{i \in I}C_i$$
where the later two products are products of sets, not modules - but where module structure can then be imposed in a natural way. This level of indirection is necessary since the universal property of a product specifies the maps out of a module, which doesn't inherently tell us much about the elements of that module - so we need to find a way to identify the elements of a module by knowing the maps out of it, and the relation $\operatorname{Hom}(R, M) \cong M$ encodes what we need to reason about elements.

A: The direct sum of modules satisfies a number of universal properties: it's the coproduct, it's a direct sum in a more general sense, it's a weak direct product, etc.  Since universal properties only characterize objects in a category up to isomorphism, we shouldn't expect to see the description of the direct sum in terms of tuples with cofinitely many nontrivial entries in every universal property, since this description isn't invariant under isomorphism.  Your original understanding of the direct sum fits very well with its description as a weak direct product, slightly less well with its description as a generalized direct sum, and not very well with its description as a coproduct.
Here's what I mean.  The weak direct product is defined as a colimit over products:
$$
\mathrm{WP}_{i \in I} A_{i} = \mathrm{colim}_{F \in \mathrm{Fin}(I)} \prod_{i \in F} A_{i}
$$
where I've written $\mathrm{Fin}(I)$ for the poset of finite subsets of $I$, ordered by inclusion.  Now this poset is filtered, so the weak direct product is made up of filtered colimits and products.  The underlying set functor commutes with filtered colimits and products, so the underlying set of the weak direct product of some modules is the weak direct product of the underlying sets of the modules.  Now recall the standard construction of filtered colimits and products in the category of sets.  According to these constructions, an element of the weak direct product is an equivalence class of the form $[(F, a_{i})]$, where $F$ is a finite subset of $I$ and $a_{i}$ is an element of $\prod_{i \in F} A_{i}$.  Two pairs $(F, a_{i})$ and $(F', a'_{j})$ are equivalent if $a_{i}$ and $a'_{i}$ are equal when they are extended to the product $\prod_{i \in F \cup F'} A_{i}$ by filling in with zeros where necessary.  So we can think of the equivalence class $[(F, a_{i})]$ as being an element of $\prod_{i \in I} A_{i}$ that vanishes for indices other than those in $F$, and this is where the finiteness comes from.
It's not too hard to show that the weak direct product of modules satisfies the universal property of the coproduct, and since this characterizes it up to isomorphism any construction of the coproduct will be isomorphic to the one we just constructed.  However, the universal property of the coproduct doesn't interact very helpfully with the forgetful functor to the category of sets, so it doesn't give us a good formula for the underlying set.


text:
Q: How would you approach unknown states/variables in steady-state or equilibrium? Consider a linear state space system $\dot{x}=Ax+B$, with $x$ being a $n\times 1$ vector of $n$ state variables, and $A$ and $B$ being known matrices with dimensions $n\times n$ and $n\times m$, respectively. For this example, $n=6$.
The controllability matrix of the system is a full rank matrix and thus, the system is controllable.
However, only $3$ out of $n=6$ state variables appear on the right-hand side. In other words, the system is controlled by just half of the state variables. When performing a linearization $\dot{x}=0$, the linearized state vector $\bar x$ is defined, but just values for the three controlling states are found, whilst the other three are undefined. How can I approach these undefined states in order to find their steady-state value?
For example, say $x=[x_1,x_2,\ldots,x_6]$, with linearization by Taylor's Series leading to linearized states $\bar x=[\bar x_1,\bar x_2,\dots,\bar x_6]$. Solely $x_1,x_2$ and $x_3$ appear in the right-hand side of the state space system. Therefore, solely a value for $\bar x_1,\bar x_2$ and $\bar x_3$ can be found. The other three linearized states $\bar x_4,\bar x_5$ and $\bar x_6$ remain undefined, as they are not necessarily zero. The question in this example would then be: how can I define the linearized states $\bar x_4,\bar x_5$ and $\bar x_6$?


text:
Q: Import Image to ImageButton I'm trying to import image to my app into ImageButton. When the user clicks on it will go to the Gallery and select the photo. But it doesn't appear after I select the image from the Gallery or external storage.
xml code
<ImageButton
    android:id="@+id/foodimbutton"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:onClick="ibC"
/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/itemName"
    android:hint="enter the item Name"
 />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/itemDesc"
    android:hint="enter the item Descrption"
/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/itemPrice"
    android:hint="enter the item Price"
/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Add the Item"
    android:onClick="AddtheItemButtonClcied"
/>

java code
public class AddFood extends AppCompatActivity {

    ImageButton imageButton;
    Intent galleryIntent;
    private static final int GALLREQ = 1;
    private EditText name,desc,price;
    private Uri uri = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_food);

        name = (EditText)findViewById(R.id.itemName);
        desc = (EditText)findViewById(R.id.itemDesc);
        price = (EditText)findViewById(R.id.itemPrice);
    }

    public void ibC (View view) {
        galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("Image/*");
        startActivityForResult(galleryIntent,GALLREQ);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLREQ && resultCode == RESULT_OK ) {
            uri = data.getData();
            imageButton = (ImageButton)findViewById(R.id.foodimbutton);
            imageButton.setImageURI(uri);
        }
    }
}

AndroidManifest
I didn't forget the permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

A: I think the button you mentioned is the image button you showed above. If that is the case you need to implement onClickListener() for that button. That is where you call your method by passing that view. There are a tone of examples on the web on how to implement that. Here is a sample,
// Create an anonymous implementation of OnClickListener
private OnClickListener myListener = new OnClickListener() {
    public void onClick(View v) {
       ibC(v);
    }
};
//call this inside your onCreate() method
imageButton.setOnClickListener(myListener);

Let me know if you have any other questions.

A: Try the following:
public class Demo2 extends AppCompatActivity {

private ImageButton ib;
private final int GALLREQ = 1;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.demo4);
}

public void ibC (View view) {

    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent , GALLREQ);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLREQ && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        ib = (ImageButton) findViewById(R.id.ib);
        Log.e("Uri", "*******" + uri.getPath());
        ib.setImageURI(uri);
    }

}
}

demo4.xml:------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageButton
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:id="@+id/ib"
    android:onClick="ibC"/>

</android.support.constraint.ConstraintLayout>


text:
Q: Hibernate Database connection Error I am new to hibernate, I have created a rest web service for login page. I am using hibernate with JDBC for database connectivity. I am using MYSQL database.My web service works fine when I retrieve data from localhost mysql. But,I want to access data from the unix server (MYSQL). When I try to access the database from unix server, I am getting the following error:
Jul 13, 2015 11:02:01 AM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
org.hibernate.exception.JDBCConnectionException: Cannot open connection
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
    at dao.Database.DbConnection(Database.java:27)
    at webservice.Login.Login_check(Login.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused: connect

STACKTRACE:

java.net.SocketException: java.net.ConnectException: Connection refused: connect
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:283)
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2541)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1474)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:264)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
    at dao.Database.DbConnection(Database.java:27)
    at webservice.Login.Login_check(Login.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

** END NESTED EXCEPTION **

Last packet sent to the server was 0 ms ago.
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2607)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1474)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:264)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
    ... 45 more

Jul 13, 2015 11:02:01 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [ServletAdaptor] in context with path [/Automation_test1] threw exception
org.hibernate.exception.JDBCConnectionException: Cannot open connection
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
    at dao.Database.DbConnection(Database.java:27)
    at webservice.Login.Login_check(Login.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused: connect

STACKTRACE:

java.net.SocketException: java.net.ConnectException: Connection refused: connect
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:283)
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2541)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1474)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:264)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
    at dao.Database.DbConnection(Database.java:27)
    at webservice.Login.Login_check(Login.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

** END NESTED EXCEPTION **

Last packet sent to the server was 0 ms ago.
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2607)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1474)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:264)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
    ... 45 more

Jul 13, 2015 11:02:39 AM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/Automation_test1] has started
Jul 13, 2015 11:02:39 AM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/Automation_test1] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Jul 13, 2015 11:02:40 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(C:\java_workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Automation_test1\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
Jul 13, 2015 11:02:41 AM org.apache.catalina.startup.TaglibUriRule body
INFO: TLD skipped. URI: urn:com:sun:jersey:api:view is already defined
Jul 13, 2015 11:02:41 AM com.sun.jersey.api.core.servlet.WebAppResourceConfig init
INFO: Scanning for root resource and provider classes in the Web app resource paths:
  /WEB-INF/lib
  /WEB-INF/classes
Jul 13, 2015 11:02:41 AM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class webservice.Login
Jul 13, 2015 11:02:41 AM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Provider classes found:
  class org.codehaus.jackson.jaxrs.JacksonJsonProvider
  class org.codehaus.jackson.jaxrs.JsonMappingExceptionMapper
  class org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider
  class org.codehaus.jackson.jaxrs.JsonParseExceptionMapper
Jul 13, 2015 11:02:41 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.18.1 02/19/2014 05:15 AM'
Jul 13, 2015 11:02:42 AM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/Automation_test1] is completed

A: These need investigated:
1) server port (call it 3306, whatever) is not open (protected by server firewall)
2) server mysql my.conf needs to be tweaked setting bind-address to 0.0.0.0
This is because for security purposes it defaults to localhost until you change it (and do a mysqld restart). Also comment-out skip-networking if present.
3) mysql user grants need to allow dbuser to connect from host %.
GRANT ALL PRIVILEGES ON mydbname.* TO 'db-user-name'@'%'


text:
Q: Hostname from Red Hat Enterprise Linux Server I am using given below java code to get the Hostname from RHEL Using IBM JDK 1.8
import java.net.InetAddress;
public class Hostname {

    public static void main(String[] args) {
        try{
             String hostname  = InetAddress.getLocalHost().getHostName();
             System.out.println("Hostname is :"+hostname);

        }
        catch(Exception e){
            System.out.println(" Exception  :"+e);
            System.out.println(" Exception Msg :"+e.getMessage());
        }
    }

}

*

*Hostname from RHEL 6.9 /IBM JDK 1.8 = vas2cxn00001122.

*Fully qualified hostname from RHEL 7.6 / IBM JDK 1.8 = vas2cxn00003344.cloud.vd.org.

Why is there a difference between 6.9 vs 7.6?  Where we have to update or modify the hostname in RHEL 7.6, in order to get only hostname, instead of fully qualified hostname.

A: I could not able to find out the root cause of RHEL 7.6 . So i have changed my java logic
from

InetAddress.getLocalHost().getHostName()

to
Runtime.getRuntime().exec("hostname")


text:
Q: Azure - Switch host name for ssl certificate I have just bought an SSL Certificate for my website from azure. when setting up a certificate under "Naked domain hostname" i entered the domain name WITHOUT "www".
Currently if i were to view my website with https://xyz.ca, it works just fine and it says it is secure, but if enter www.xyz.ca i do not see anything.
To atleast view the website with www.xyz.ca, i have removed HTTPS:// only request. However now this makes website un-secure.
Question
1. what will be the best way to make www.xyz.ca secure using the same certificate that i have bought?
2. if there is any other solution available, that will be fine too.
I am attaching some screenshots to understand better:

A: A valid SSL certificate must match the access FQDN domain name.
One Standard certificate only could be used for one FQDN domain name, such as www.xyz.ca while one WildCard certificate could be used for all like *.xyz.ca FQDN domain name, so usually we use the same WildCard certificate for all different services. More information about SSL Certificate Names
As the comment point it out, instead of buying one via the Azure Portal, you can get a free one via letsencrypt.org
Update
When you purchase an app service certificate in Azure for a root domain, by default, Azure supports hostname as a root domain name and www subdomain. You do not need to purchase another certificate. In this case, you already have two hostnames assigned to the site. You just bind the certificate for each. If you don't see the domain name(s) in the Hostname dropdown, try refreshing the browser page or change another browser.

A: In fact a cert CAN support MANY domains.  Now, whether this is something that you can add for free with the SSL provider you have chose is a different question.  Certificate Subject Alternate Name(s) are what is used for this.  For example the cert for this site allows stackexchange.com AND stackoverflow.com and a number of others and sub-domains too.


text:
Q: Nagios: Dependency from service to different host We have a server "zibal" that is running several Selenium checks for websites on multiple hosts. At the moment, when one of the servers hosting a website goes down, the failing selenium check will also generate an (unnecessary) notification.
From the Nagios documentation, it seems like it is only possible to add a dependency from a service to another service, or from a host to another host, but not from one service on "zibal" to server B as a host.
Another answer states to use a parent definition (not sure if that case applies here). I have added such a parent definition (multiple hosts) to "zibal", but this doesn't look right: When server B goes down, there should be no notification for the failing Selenium check, but in case "zibal" goes down as well, there of course should be a notification.
How does this have to be configured correctly?

A: You want service dependencies for each Selenium check, in this case.
The Selenium check for "server B" depends on a service check that's on server B (for example, a check of the web server using check_http).
You can simplify the configuration using host and/or servicegroups with dependencies. See the time-saving tips and tricks docs page for more info.


text:
Q: Handle text input view movement with keyboard pan gesture in iOS Swift I am developing an iOS app and
I have a messaging view where I want to handle this situation:
-> I have a input view at the bottom of the view, that needs to be visible all the time except for some criteria where user is blocked/restricted to send message.
-> when the input view is focused, keyboard appears, I want to move the view along with keyboard frame.
-> I want keyboard to dismiss interactively with table view scrolling. With this being said, the view should respond to keyboard pan gesture and move along with as well
-> I tried using input accessory view but problem with that was when keyboard gets dismissed with table view scrolling, input view gets dismissed as well.
-> I also tried using willShow/willHide/willChangeFrame observers but with this, response is not to the point and it doesn't respond to keyboard interactive dismissal.
Anybody got solution to this...
Thanks for your time.

A: Swift 3+:
I have take a view into textview background and set the constraint of view (leading, trailing, bottom, fixed height). Create a @IBOutlet for bottom constraint and manage that below code:
class ViewController: UIViewController {

    @IBOutlet var bottomConstraint: NSLayoutConstraint!
    @IBOutlet var view_TextViewBg: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardDidShow(_:)),
            name: NSNotification.Name.UIKeyboardWillShow,
            object: nil)
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardDidHide(_:)),
            name: NSNotification.Name.UIKeyboardWillHide,
            object: nil)

        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
        //  tap.delegate = self
        view.addGestureRecognizer(tap)

    }
    func handleTap(sender: UITapGestureRecognizer? = nil) {
        //dissmiss your keyboard here
    }

    //MARK: Keyboard show

    func keyboardDidShow(_ notification: Notification) {
        let params = notification.userInfo
        let rect: CGRect? = (params?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
        bottomConstraint.constant = (rect?.size.height)!
    }

    //MARK: Keyboard hide

    func keyboardDidHide(_ notification: Notification) {
        bottomConstraint.constant = 0
    }

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


text:
Q: Function called from another package cannot access to parameters Here is my problem :
I'm having two classes: class A contains some @Value("${param.username}") and @Value("${param.password}"), I have a function using those 2 params, and I a use @GetMapping(path = "/functionA") to run the functionA (this function is a Post request to a server to authentificate)
Username and password are on application-contextual-values.properties
When I run on browser localhost:8080/app/functionA => it works !
I have another class B, on another package B, I want to call the first class A and use the fuctionA to authentificate. => I'm having an error : Username must not be null
It means that I cannot get username and password that are stored in application-contextual-values file.
Here is my code of class A :
public class A {

    @Value("${param.username}")
    private String username;

    @Value("${param.password}")
    private String password;

    @GetMapping(path = "functionA")
    public AuthentificationModel getClient() {
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(this.username, this.password);
        String jwt = getJWT(); <======  this function is also in this class A

        ...

        I'm doing a construction of params, to send on POST

        return token;
     }

The AuthentificationModel  is just what is sent back after the POST request (access_token, client_id, token_type)
My class B is :
import fr.ag2rlamondiale.ytb.rest.A; <==== class A

public class B {

   private static Map<String, String> getRequestHeader() {

       Map<String, String> requestHeaders = new HashMap<>();
       try{
         final A objA = new A(); <===== instance of my class A here
           String token = objA.getClient().getAccessToken(); <==== getClient() is the funct that returns token on class A

           requestHeaders.put("Authorization", "Bearer ", + token);

           ... many other put for header
         } catch (CommonException e) {
        e.printStackTrace();
    }
    return requestHeaders;
}

My application-contextual-values.properties :
param.username="kljkjsdf555sdf"
param.password="xxx222xxx"

Is it because I'll need to add constructor on class A with params username and password ? what is the proper way to make it work in my context ?
Edit :
In class A I added : @Controller
In class B : I added @Authowired A objA and no new A();
But now, having a new error : Cannot make a static reference to the non-static field objA
Meaning that elements on class A are non-static and I'm using objA as a static object ?

A: Use Dependency injection and @Autowired Your A instance in B and don't create new Instance of A in your B class.

A: Spring can process only the objects that it manages (read creates), including resolution / injection of data annotated with @Value of course.
When you create the instance of class A by yourself from class B:
final A objA = new A();

Spring has no idea that this class must be processed, in fact it doesn't even know that this class exists, hence the "value" in not injected/set.
In  general to solve this, you need to refactor your code.
Its not clear why do you create the class of Controller (I assume that A is a controller because it's method getClient is annotated with @GetMapping which makes sense only in controllers).
However, you don't have to create an instance of A, but rather inject it and make sure that both A and B are managed by Spring

A: Since you are creating instance of A using A objA = new A() in class B, spring does not inject any value in class A as it is new object. To use property injection in class A, you need to use dependency injection and use bean of A already instantiated using spring application context.
I assume Class A is annotated with @Controller.
@Controller
public class A {

and use autowiring in class B like below to inject instance of A
public class B {

   @Autowired
   A objA;

   private static Map<String, String> getRequestHeader() {

       Map<String, String> requestHeaders = new HashMap<>();
       try{
         //final A objA = new A(); <===== instance of my class A here
           String token = objA.getClient().getAccessToken(); <==== getClient() is the funct that returns token on class A


text:
Q: How to add 'all' CASE when group by CASES in SQL I have a query like this:
select
case when  sp.provider='prv1' and    sp.status_code = 404 then 'failed'
     when  sp.provider='prv1' and    sp.status_code = 200 then 'success'
     when  time_taken is null or sp.status_code in (503) or sp.status_code is null then  'unavailable'
     else 'other'
    end as result,
    count(*)
from services_serviceprofile sp
where
service_type = 'type1' and
sp.provider = 'prv1' and
sp.start_time >= '2022-08-22 00:00'
group by
  case when  sp.provider='prv1' and    sp.status_code = 404 then 'failed'
         when  sp.provider='prv1' and    sp.status_code = 200 then 'success'
         when  time_taken is null or      sp.status_code = 503  or sp.status_code is null then  'unavailable'
         else 'other'
    end
order by count(*) desc;

Which gives the result:

How can I add a row for 'all' requests in CASES? If we add a when sp.provider='prv1' with no more detailed condition then all cases become one 'all' case because and other cases are ignored.

A: You can't do that inside the CASE, as it behaves like a series of IF.
You need to compute the total separately and append it using UNION or delegate the total calculation to whatever tool uses those data.
WITH RequestStats
AS (
     SELECT
           CASE
               WHEN sp.provider = 'prv1' AND sp.status_code = 404 THEN 'failed'
               WHEN sp.provider = 'prv1' AND sp.status_code = 200 THEN 'success'
               WHEN time_taken IS NULL OR sp.status_code IN (503) OR sp.status_code IS NULL THEN 'unavailable'
               ELSE 'other'
               END AS Result
           ,count(*) AS RequestCount
     FROM services_serviceprofile sp
     WHERE
          service_type = 'type1'
          AND sp.provider = 'prv1'
          AND sp.start_time >= '2022-08-22 00:00'
)

SELECT
      Result
     ,RequestCount
FROM RequestStats

UNION ALL

SELECT
     'All' AS Result
     ,SUM(RequestCount) AS RequestCount
FROM RequestStats

A: If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function for add last row total:
select results = ISNULL(result, 'All'), Counts = sum(Counts)  from (
select
case when  sp.provider='prv1' and    sp.status_code = 404 then 'failed'
     when  sp.provider='prv1' and    sp.status_code = 200 then 'success'
     when  time_taken is null or sp.status_code in (503) or sp.status_code is null then  'unavailable'
     else 'other'
    end as result,
    count(*) as Counts
from services_serviceprofile sp
where
service_type = 'type1' and
sp.provider = 'prv1' and
sp.start_time >= '2022-08-22 00:00'
group by
  case when  sp.provider='prv1' and    sp.status_code = 404 then 'failed'
         when  sp.provider='prv1' and    sp.status_code = 200 then 'success'
         when  time_taken is null or      sp.status_code = 503  or sp.status_code is null then  'unavailable'
         else 'other'
    end
) as Final


text:
Q: refer doc id using where condition in snapshotChanges() I am fetching data using snapshotChanges(). I want to add where condition to it and fetch data of only 1 doc from collection.
Below is my code:
this.firestore.collection('notifications' , ref => ref
 .where(document id , "==" , "1")  // giving error
)
.snapshotChanges()
.subscribe(response => {
  if(!response.length){
    console.log("no data available");
    return false;
  }
  this.notifyarr = [];
  for(let item of response){
    this.notifyarr.push(item.payload.doc.data());
    console.log(this.notifyarr);
    this.notification_length = this.notifyarr.length;
    console.log(this.notification_length);
  }
})

This line of code is giving error .where(document , "==" , "1")  // giving error
How do we refer a document using .snapshotChanges() ?

A: If you want to query to check a documentid is equal to the value then you should do the following:
where(firebase.firestore.FieldPath.documentId(), "==" , "1")

A: If you know you only want a single document using its ID, why don't you just build a AngularFirstoreDocument to the desired document and call snapshotChanges on that reference?
this.firestore.collection('notifications').doc(id).snapshotChanges()...

No need to bother building a query that only gives you a single document.


text:
Q: pandas: conditionally select a row cell for each column based on a mask I want to be able to extract values from a pandas dataframe using a mask. However, after searching around, I cannot find a solution to my problem.
df = pd.DataFrame(np.random.randint(0,2, size=(2,10)))
mask = np.random.randint(0,2, size=(1,10))

I basically want the mask to serve as a index lookup for each column.
So if the mask was [0,1] for columns [a,b], I want to return:
df.iloc[0,a], df.iloc[1,b]
but in a pythonic way.
I have tried e.g.:
df.apply(lambda x: df.iloc[mask[x], x] for x in range(len(mask)))

which gives a Type error that I don't understand.
A for loop can work but is slow.

A: With NumPy, that's covered as advanced-indexing and should be pretty efficient -
df.values[mask, np.arange(mask.size)]

Sample run -
In [59]: df = pd.DataFrame(np.random.randint(11,99, size=(5,10)))

In [60]: mask = np.random.randint(0,5, size=(1,10))

In [61]: df
Out[61]:
    0   1   2   3   4   5   6   7   8   9
0  17  87  73  98  32  37  61  58  35  87
1  52  64  17  79  20  19  89  88  19  24
2  50  33  41  75  19  77  15  59  84  86
3  69  13  88  78  46  76  33  79  27  22
4  80  64  17  95  49  16  87  82  60  19

In [62]: mask
Out[62]: array([[2, 3, 0, 4, 2, 2, 4, 0, 0, 0]])

In [63]: df.values[mask, np.arange(mask.size)]
Out[63]: array([[50, 13, 73, 95, 19, 77, 87, 58, 35, 87]])


text:
Q: How to find the end of a DEFLATE block For self education purposes I am trying to create a program that will convert a png file into an array of RGBA values. However I am having a problem with decoding the IDAT sections which are encoded with zlib using the deflate format. The problem I am having is I do not know how to find where the end of a compressed block is. The only place in the documentation where a length is shown is just for decompressed blocks however for block with the default huffman tables and the huffman tables supplied there does not seem to be a way to find out where the block ends. How should i go about finding the end of a block in the deflate format.

A: Per the PNG Deflate/Inflate Compression documentation

The compressed data within the zlib datastream is stored as a series of blocks, each of which can represent raw (uncompressed) data, LZ77-compressed data encoded with fixed Huffman codes, or LZ77-compressed data encoded with custom Huffman codes. A marker bit in the final block identifies it as the last block, allowing the decoder to recognize the end of the compressed datastream. Further details on the compression algorithm and the encoding are given in the deflate specification [RFC-1951].
...
In a PNG file, the concatenation of the contents of all the IDAT chunks makes up a zlib datastream as specified above. This datastream decompresses to filtered image data as described elsewhere in this document.
It is important to emphasize that the boundaries between IDAT chunks are arbitrary and can fall anywhere in the zlib datastream. There is not necessarily any correlation between IDAT chunk boundaries and deflate block boundaries or any other feature of the zlib data. For example, it is entirely possible for the terminating zlib check value to be split across IDAT chunks.*"

And per RFC 1951: "DEFLATE Compressed Data Format Specification version 1.3":

A compressed data set consists of a series of blocks, corresponding to successive blocks of input data.  The block sizes are arbitrary, except that non-compressible blocks are limited to 65,535 bytes.
Each block is compressed using a combination of the LZ77 algorithm and Huffman coding. The Huffman trees for each block are independent of those for previous or subsequent blocks; the LZ77 algorithm may use a reference to a duplicated string occurring in a previous block, up to 32K input bytes before.
Each block consists of two parts: a pair of Huffman code trees that describe the representation of the compressed data part, and a compressed data part.  (The Huffman trees themselves are compressed using Huffman encoding.)  The compressed data consists of a series of elements of two types: literal bytes (of strings that have not been detected as duplicated within the previous 32K input bytes), and pointers to duplicated strings, where a pointer is represented as a pair <length, backward distance>.  The representation used in the "deflate" format limits distances to 32K bytes and lengths to 258 bytes, but does not limit the size of a block, except for uncompressible blocks, which are limited as noted above.
Each type of value (literals, distances, and lengths) in the compressed data is represented using a Huffman code, using one code tree for literals and lengths and a separate code tree for distances. The code trees for each block appear in a compact form just before the compressed data for that block.

So, to determine the end of a given block, you would have to parse the block's Huffman codes to know the location and type of each element within the compressed data, and then you can process each element as needed until you find the end of the last element in the block.  Section 3.2 goes into the technical details of how the compressed blocks are formatted, particularly Section 3.2.3:

3.2.3. Details of block format
Each block of compressed data begins with 3 header bits containing the following data:
first bit       BFINAL
next 2 bits     BTYPE

Note that the header bits do not necessarily begin on a byte boundary, since a block does not necessarily occupy an integral number of bytes.
BFINAL is set if and only if this is the last block of the data set.
BTYPE specifies how the data are compressed, as follows:
00 - no compression
01 - compressed with fixed Huffman codes
10 - compressed with dynamic Huffman codes
11 - reserved (error)

The only difference between the two compressed cases is how the Huffman codes for the literal/length and distance alphabets are defined.
In all cases, the decoding algorithm for the actual data is as follows:
do
    read block header from input stream.
    if stored with no compression
        skip any remaining bits in current partially
            processed byte
        read LEN and NLEN (see next section)
        copy LEN bytes of data to output
    otherwise
        if compressed with dynamic Huffman codes
            read representation of code trees (see
                subsection below)
        loop (until end of block code recognized)
            decode literal/length value from input stream
            if value < 256
                copy value (literal byte) to output stream
            otherwise
                if value = end of block (256)
                    break from loop
                otherwise (value = 257..285)
                    decode distance from input stream

                    move backwards distance bytes in the output
                    stream, and copy length bytes from this
                    position to the output stream.
        end loop
while not last block

Note that a duplicated string reference may refer to a string in a previous block; i.e., the backward distance may cross one or more block boundaries.  However a distance cannot refer past the beginning of the output stream.  (An application using a preset dictionary might discard part of the output stream; a distance can refer to that part of the output stream anyway) Note also that the referenced string may overlap the current position; for example, if the last 2 bytes decoded have values X and Y, a string reference with <length = 5, distance = 2> adds X,Y,X,Y,X to the output stream.


text:
Q: как отправить текст из edittext main activity в edit text second activity? как отправить текст из edittext main activity в edit text second activity?для kotlin не  java. я новичок поэтому не знаю java можете пример показать пожалуйста! с помощью shared preference.

A: Вообще у вас есть несколько вариантов отправки, и SharedPreferences не является совсем идеальным для вашей задачи как мне кажется, либо вы предоставили неполную информацию. Начнем с SharedPreferences так как вам нужен именно этот вариант. У вас есть поле для ввода и вам нужно взять с него текст:
var editTextHello = findViewById(R.id.editTextHello) as EditText
val text = editTextHello.text

дальше вы сохраняете данные в память как было указано в комментариях:
val sharedPref = activity?.getSharedPreferences("your_storage", 0)
sharedPref.edit.putString("text_from_field", editTextHello.text).commit()

дальше в активности где вам нужно получить эти данные, вы их вытаскиваете:
 val sharedPref = activity?.getSharedPreferences("your_storage", 0)
val text = sp.getString("text_from_field", "")

так же есть и второй вариант - использовать Intent для передачи данных из активности в активность, при условии что эти данные нигде больше не будут задействованы кроме как в процессе данной передачи. В активности с полем для ввода текста:
val intent = Intent(this, NextActivity::class.java)
intent.putExtra("text", editTextHello.text)
startActivity(intent)

и дальше извлекаем этот текст:
var : String = intent.getStringExtra("text")


text:
Q: Use AntiForgeryToken with ASP.NET 5 and Angular On an ASP.NET 5 RC1 I have the following
[HttpPost]
public async Task<IActionResult> Create([FromBody]Post post) {
  // Create post
}

I have a CreatePost.html template used by angular with the form:
<form ng-controller="CreatePostController" ng-submit="create()">
  Title
  <input type="text" name="title">
  Content
  <input type="text" name="content">
  <button type="submit">Create</button>
</form>

*

*The is in an HTML page. How to render the ASP.NET AntiForgeryToken?
Can I create one on page head and use on all my website forms?

*How to send the token when I call the API and verify it?

A: *

*Setting in the header the antiforgery token  once using AngularJS
$http service

*Expose a web api method to return the antiforgery
token .

take a look this article: http://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/

A: There is a antiforgery middleware available in asp.net core rc1. you can use that. here is a simple blog I wrote on how you can achieve that.
http://fiyazhasan.me/angularjs-anti-forgery-with-asp-net-core/

A: If you're using ui-router you can do something like the following. The beauty of this approach is that it only happens on state change not on every request to the server. If you're developing a SPA, and using any templates this will come in handy:
       $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (IsAuthenticated()) {
                SetAntiForgeryCookie();
            }
        });

SetAntiForgeryCookey just does a $http GET request that calls a simple action:
    [HttpGet]
    public IActionResult Get()
    {
        var context = Request.HttpContext;
        var tokens = _antiForgery.GetAndStoreTokens(context);
        context.Response.Cookies
            .Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });

        return new ObjectResult(true);
    }

Then I create an attribute to apply to my actions:
public class ValidateApiAntiForgeryTokenAttribute : ActionFilterAttribute
{
    private readonly IAntiforgery _antiForgery;

    public ValidateApiAntiForgeryTokenAttribute(IAntiforgery antiForgery)
    {
        _antiForgery = antiForgery;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        await _antiForgery.ValidateRequestAsync(context.HttpContext);
        await base.OnActionExecutionAsync(context, next);
    }
}

The only thing I dont like about this approach is that in order to inject into the attribute I have to use the ServiceFilterAttribute on the action:
[ServiceFilter(typeof(ValidateApiAntiForgeryTokenAttribute))]

Also dont forget the middleware in ConfigureServices:
 services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");


text:
Q: Converting FASTQ to FASTA with SED/AWK I have a data in that always comes in block of four
in the following format (called FASTQ):
@SRR018006.2016 GA2:6:1:20:650 length=36
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGN
+SRR018006.2016 GA2:6:1:20:650 length=36
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!+!
@SRR018006.19405469 GA2:6:100:1793:611 length=36
ACCCGCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
+SRR018006.19405469 GA2:6:100:1793:611 length=36
7);;).;);;/;*.2>/@@7;@77<..;)58)5/>/

Is there a simple sed/awk/bash way to convert them into
this format (called FASTA):
>SRR018006.2016 GA2:6:1:20:650 length=36
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGN
>SRR018006.19405469 GA2:6:100:1793:611 length=36
ACCCGCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

In principle, we want to extract the first two lines in each block-of-4
and replace @ with >.

A: sed ain't dead.  If we're golfing:
sed '/^@/!d;s//>/;N'

Or, emulating http://www.ringtail.tsl.ac.uk/david-studholme/scripts/fastq2fasta.pl posted by Pierre, which only prints the first word (the id) from the first line and does (some) error handling:
#!/usr/bin/sed -f
# Read a total of four lines
$b error
N;$b error
N;$b error
N
# Parse the lines
/^@\(\([^ ]*\).*\)\(\n[ACGTN]*\)\n+\1\n.*$/{
  # Output id and sequence for FASTA format.
  s//>\2\3/
  b
}
:error
i\
Error parsing input:
q

There seem to be plenty of existing tools for converting these formats; you should probably use these instead of anything posted here (including the above).

A: As detailed in Cock, et al (2009) NAR, many of these solutions are incorrect since "the '@' marker character (ASCII 64) may occur anywhere in the quality string. This means that any parser must not treat a line starting with '@' as indicating the start of the next record, without additionally checking the length of the quality string thus far matches the length of the sequence."
See http://ukpmc.ac.uk/articlerender.cgi?accid=PMC2847217 for details.

A: just awk , no need other tools
# awk '/^@SR/{gsub(/^@/,">",$1);print;getline;print}' file
>SRR018006.2016 GA2:6:1:20:650 length=36
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGN
>SRR018006.19405469 GA2:6:100:1793:611 length=36
ACCCGCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

A: See fastq2fasta.pl in http://www.ringtail.tsl.ac.uk/david-studholme/scripts/

A: I'd write
awk '
    NR%4 == 1 {print ">" substr($0, 2)}
    NR%4 == 2 {print}
' fastq > fasta

A: This is an old question, and there have been many different solutions offered.  Since the accepted answer uses sed but has a glaring problem (which is that it will replace @ with > when the @ sign appears as the first letter of the quality line), I feel compelled to offer a simple sed-based solution that actually works:
sed -n '1~4s/^@/>/p;2~4p'

The only assumption made is that each read occupies exactly 4 lines in the FASTQ file, but that seems pretty safe, in my experience.
The fastq_to_fasta script in the fastx toolkit also works.  (It's worth mentioning that you need to specify the -Q33 option to accommodate the now common Phred+33 qual encodings.  Which is funny, since it's throwing away the quality data anyway!)

A: This is the fastest I've got, and I stuck it in my .bashrc file:
alias fq2fa="awk '{print \">\" substr(\$0,2);getline;print;getline;getline}'"

It doesn't fail on the infrequent but not impossible quality lines that start with @... but does fail on wrapped FASTQ, if that's even legal (it exists though).

A: You might be interested in bioawk, it is an adapted version of awk which is tuned to process fasta files
bioawk -c fastx '{ print ">"$name ORS $seq }' file.fastq

Note: BioAwk is based on Brian Kernighan's awk which is documented in "The AWK Programming Language",
by Al Aho, Brian Kernighan, and Peter Weinberger
(Addison-Wesley, 1988, ISBN 0-201-07981-X)
. I'm not sure if this version is compatible with POSIX.

A: awk 'BEGIN{P=1}{if(P==1||P==2){gsub(/^[@]/,">");print}; if(P==4)P=0; P++}' data

>SRR018006.2016 GA2:6:1:20:650 length=36
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGN
>SRR018006.19405469 GA2:6:100:1793:611 length=36
ACCCGCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

below
awk '{gsub(/^[@]/,">"); print}' data

where data is your data file.
I've received:
>SRR018006.2016 GA2:6:1:20:650 length=36
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGN
+SRR018006.2016 GA2:6:1:20:650 length=36
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!+!
>SRR018006.19405469 GA2:6:100:1793:611 length=36
ACCCGCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
+SRR018006.19405469 GA2:6:100:1793:611 length=36
7);;).;);;/;*.2>/@@7;@77<..;)58)5/>/

A: Here's the solution to the "skip every other line" part of the problem that I just learned from SO:
while read line
do
    # print two lines
    echo "$line"
    read line_to_print
    echo "$line_to_print"

    # and skip two lines
    read line_to_skip
    read line_to_skip
done

If all that needs to be done is change one @ to >, then I reckon
while read line
do
    echo "$line" | sed 's/@/>/'
    read line
    echo "$line"

    read line_to_skip
    read line_to_skip
done

will do the job.

A: Something like:
awk 'BEGIN{a=0}{if(a==1){print;a=0}}/^@/{print;a=1}' myFastqFile | sed 's/^@/>/'

should work.

A: I think, with gnu grep this could be done with this:
grep -A 1 "^@" t.txt | grep -v "^--" | sed -e "s/^@/\>/"

A: I know I'm way in the future, but for the benefit of googlers:
You may want to use fastq_to_fasta from the fastx toolkit. It will keep the @ sign, though. It will also remove lines with Ns unless you tell it not to.


text:
Q: Java Abstract Class Method I came across this code in an exercise for declaring an abstract class:
import java.util.ArrayList;

public abstract class Box {

    public abstract void add(Item item);

    public void add(ArrayList<Item> items) {
        for (Item item : items) {
            Box.this.add(item);
        }
    }

    public abstract boolean isInBox(Item item);
}

I am not able to understand what the add(ArrayList<Item> item) method does. I get it that it loops through an ArrayList called items but what does Box.this.add(item) do?
Can someone clarify this?

A: On top of what @ernest_k wrote in a comment there is an actual use-case where you actually need to qualify a method call with the class name like this: If you create an anonymous inner class in a method that accesses fields of its outer class, like the following arbitrary (and quite useless in reality) example:
import java.util.ArrayList;

public abstract class Box {

    public abstract void add(String item);

    public void add(ArrayList<String> items) {
        for (String item : items) {
            Runnable r = new Runnable() {

                @Override
                public void run() {
                    add(item); // works, implicitly accesses Box.this.add
                    this.add(item); // does not work as "add" is not a method of the anonymous runnable
                    Box.this.add(item); // works
                }
            };
            r.run();
        }
    }

    public abstract boolean isInBox(String item);
}

A: That class is declaring an interface with some code already in. Specifically, it is declaring a Box without a detailed implementation, in which you can later create the Box with the underlying code that suits your needs.
For example, you can declare the BoxOnSet class, that implements that declaration with a HashSet<>:
public abstract class BoxOnSet extends Box {
    public BoxOnSet()
    {
        this.items = new HashSet<>();
    }

    public void add(Item item)
    {
        this.items.add( item );
    }

    public boolean isInBox(Item item)
    {
        return this.items.contains( item );
    }

    private HashSet<Item> items;
}

As for your specific question, the add(ArrayList<>) method is equivalent to the collections addAll() method. It just uses the abstract add(Item) in order to insert items in the Box. You can specify add( item ), this.add( item ) or even Box.this.add( item ), and in this example all point to the same method, they are just ways to specify further.


text:
Q: Как реализовать эффект (исчезающего следа) как в игре dark echo Я хочу сделать эффект визуального звука, который отражается от стен и постепенно затухает (как в игре dark echo).
Каким образом я могу это сделать средствами canvas?

Проблема в следующем:
Если я буду делать через создание полупрозрачных копий частицы, то и это слишком будет тормозить отрисовку (след нужен довольно длинный)
Движение WASD или стрелки
Пробел - создать звук

<!DOCTYPE html>
<html>
<head>
    <title>шлейф</title>
    <meta charset="utf-8">
    <style>
        canvas {
            border: 2px solid grey;
        }
    </style>
    <script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous">
    </script>
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script type="text/javascript">
    var game_status = 'active';

    var x_cam = 0;
    var y_cam = 0;

    var direction = {
        "37": "left",
        "38": "up",
        "39": "right",
        "40": "down",
        "65": "left",
        "87": "up",
        "68": "right",
        "83": "down",
    };

    var ctx = document.getElementById('canvas').getContext('2d');

    var map = {
        ctx: ctx,
        width: 200,
        height: 200,
        particles: [],
        circle: function (x, y, radius, color, fillCircle=true) {
            this.ctx.beginPath();
            this.ctx.arc(x, y, radius, 0, Math.PI * 2, false);
            if (fillCircle) {
                this.ctx.fillStyle = color;
                this.ctx.fill();
            } else {
                this.ctx.strokeStyle = color;
                this.ctx.stroke();
            }
        },
        clear: function() {
            this.ctx.clearRect(0, 0, this.width, this.height)
        },
        alpha_clear: function(alpha) {
            this.ctx.fillStyle = "rgba(255, 255, 255,"+alpha+")"
            this.ctx.fillRect(0, 0, this.width, this.height);
        }
    }

    var player = {
        x: 100,
        y: 100,
        speed: 2,
        x_vec: 0,
        y_vec: 0,
        angle: 0,
        direction: {
            "up": false,
            "down": false,
            "right": false,
            "left": false
        },
        setDirection: function(dir, status) {
            if (dir == 'up' || dir == 'down' || dir == 'right' || dir == 'left') {
                this.direction[dir] = status;
            }
        },
        setVecs: function() {
            this.x_vec = 0;
            this.y_vec = 0;

            if (this.direction.up) {
                this.y_vec--;
            }

            if (this.direction.down) {
                this.y_vec++;
            }

            if (this.direction.right) {
                this.x_vec++;
            }

            if (this.direction.left) {
                this.x_vec--;
            }

            if (Math.abs(this.x_vec) > 0 && Math.abs(this.y_vec) > 0) {
                this.x_vec *= 0.7;
                this.y_vec *= 0.7;
            }

            // строго наверх
            if (this.x_vec == 0 && this.y_vec == -1) {
                this.angle = 0
            }

            // строго вниз
            if (this.x_vec == 0 && this.y_vec == 1) {
                this.angle = Math.PI;
            }

            // строго вправо
            if (this.x_vec == 1 && this.y_vec == 0) {
                this.angle = Math.PI/2;
            }

            // строго влево
            if (this.x_vec == -1 && this.y_vec == 0) {
                this.angle = Math.PI*1.5;
            }

            // наверх-вправо
            if (this.x_vec == 0.7 && this.y_vec == -0.7) {
                this.angle = Math.PI/4;
            }

            // вниз-вправо
            if (this.x_vec == 0.7 && this.y_vec == 0.7) {
                this.angle = Math.PI*0.75;
            }

            // вниз-влево
            if (this.x_vec == -0.7 && this.y_vec == 0.7) {
                this.angle = Math.PI*1.25;
            }

            // вверх-влево
            if (this.x_vec == -0.7 && this.y_vec == -0.7) {
                this.angle = Math.PI*1.75;
            }
        },
        draw: function() {
            map.circle(this.x-x_cam, this.y-y_cam, 10, "red");
        },
        update: function() {
            this.x += this.x_vec*this.speed;
            this.y += this.y_vec*this.speed;
            x_cam += this.x_vec*this.speed;
            y_cam += this.y_vec*this.speed;
        },
        createSound: function() {
            var angle_step = Math.PI*2/10;
            for (var i=0; i < 10; i++) {
                map.particles.push(new Particle(this.x, this.y, i*angle_step));

            }
        }
    }

    var Particle = function(x=300, y=300, angle=0) {
        this.x= x;
        this.y= y;
        this.angle = angle;
        this.x_vec= Math.cos(angle);
        this.y_vec= Math.sin(angle);
        this.speed = 5;
        this.tail = [];
        for (var i=0; i < 20; i++) {
            this.tail.push({
                "x": x,
                "y": y,

            })
        }
        this.draw= function() {
            map.circle(this.x-x_cam, this.y-y_cam, 3, 'black');
            for (var i=0; i < this.tail.length; i++) {
                map.circle(this.tail[i].x-x_cam, this.tail[i].y-y_cam, 3, 'black');

            }
        };
        this.update= function() {
            this.x += this.x_vec*this.speed;
            this.y += this.y_vec*this.speed;
        }
        this.update_tail = function() {
            for (var j=this.tail.length-1; j > 0; j--) {
                    this.tail[j] = this.tail[j-1];

            }
            this.tail.pop();
            this.tail.unshift({
                "x": this.x,
                "y": this.y,
            })
            //this.tail[0].x = this.x;
            //this.tail[0].y = this.y;
        }

    }

    $("body").keydown(function (event) {
    //console.log(snake);
        if (direction[event.keyCode] != undefined) {
            var pl_direction = direction[event.keyCode];
            player.setDirection(pl_direction, true);
        } else {
            if (event.keyCode== 13) {
                if (game_status == 'active') {
                    game_status = 'pause';
                } else {
                    game_status = 'active';
                }
            } else if (event.keyCode == 32) {
                player.createSound();
            }
        }

    });

    $("body").keyup(function (event) {
    //console.log(snake);
        if (direction[event.keyCode] != undefined) {
            var pl_direction = direction[event.keyCode];
            player.setDirection(pl_direction, false);
        }
    });

    var particle = new Particle();

    var game_loop = function() {
        if (game_status == 'active') {
            window.requestAnimationFrame(game_loop);

            map.clear();
            ctx.fillStyle = "black";
            ctx.fillRect(100-x_cam, 100-y_cam, 100, 100);
            player.setVecs();
            player.update();
            for (var i in map.particles) {
                map.particles[i].update_tail();
                map.particles[i].update();
                map.particles[i].draw()
            }
            particle.update_tail();
            particle.update();
            particle.draw();
            player.draw();
        }
    }

    game_loop();
</script>
</body>
</html>

В примере выше я не стал добавлять полупрозрачность частиц, т.к. и так понятно, что такое кол-во частиц нагружает систему
Однако если я буду неполностью стирать canvas, то во время движения линии будут искажаться (я для имитации viewport (движения камеры) отнимаю условную позицию камеры). Это хорошо видно, если стрелками туда-сюда двигаться
Движение WASD или стрелки
Пробел - создать звук

<!DOCTYPE html>
<html>
<head>
    <title>шлейф</title>
    <meta charset="utf-8">
    <style>
        canvas {
            border: 2px solid grey;
        }
    </style>
    <script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous">
    </script>
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script type="text/javascript">
    var game_status = 'active';

    var x_cam = 0;
    var y_cam = 0;

    var direction = {
        "37": "left",
        "38": "up",
        "39": "right",
        "40": "down",
        "65": "left",
        "87": "up",
        "68": "right",
        "83": "down",
    };

    var ctx = document.getElementById('canvas').getContext('2d');

    var map = {
        ctx: ctx,
        width: 200,
        height: 200,
        particles: [],
        circle: function (x, y, radius, color, fillCircle=true) {
            this.ctx.beginPath();
            this.ctx.arc(x, y, radius, 0, Math.PI * 2, false);
            if (fillCircle) {
                this.ctx.fillStyle = color;
                this.ctx.fill();
            } else {
                this.ctx.strokeStyle = color;
                this.ctx.stroke();
            }
        },
        clear: function() {
            this.ctx.clearRect(0, 0, this.width, this.height)
        },
        alpha_clear: function(alpha) {
            this.ctx.fillStyle = "rgba(255, 255, 255,"+alpha+")"
            this.ctx.fillRect(0, 0, this.width, this.height);
        }
    }

    var player = {
        x: 100,
        y: 100,
        speed: 3,
        x_vec: 0,
        y_vec: 0,
        angle: 0,
        direction: {
            "up": false,
            "down": false,
            "right": false,
            "left": false
        },
        setDirection: function(dir, status) {
            if (dir == 'up' || dir == 'down' || dir == 'right' || dir == 'left') {
                this.direction[dir] = status;
            }
        },
        setVecs: function() {
            this.x_vec = 0;
            this.y_vec = 0;

            if (this.direction.up) {
                this.y_vec--;
            }

            if (this.direction.down) {
                this.y_vec++;
            }

            if (this.direction.right) {
                this.x_vec++;
            }

            if (this.direction.left) {
                this.x_vec--;
            }

            if (Math.abs(this.x_vec) > 0 && Math.abs(this.y_vec) > 0) {
                this.x_vec *= 0.7;
                this.y_vec *= 0.7;
            }

            // строго наверх
            if (this.x_vec == 0 && this.y_vec == -1) {
                this.angle = 0
            }

            // строго вниз
            if (this.x_vec == 0 && this.y_vec == 1) {
                this.angle = Math.PI;
            }

            // строго вправо
            if (this.x_vec == 1 && this.y_vec == 0) {
                this.angle = Math.PI/2;
            }

            // строго влево
            if (this.x_vec == -1 && this.y_vec == 0) {
                this.angle = Math.PI*1.5;
            }

            // наверх-вправо
            if (this.x_vec == 0.7 && this.y_vec == -0.7) {
                this.angle = Math.PI/4;
            }

            // вниз-вправо
            if (this.x_vec == 0.7 && this.y_vec == 0.7) {
                this.angle = Math.PI*0.75;
            }

            // вниз-влево
            if (this.x_vec == -0.7 && this.y_vec == 0.7) {
                this.angle = Math.PI*1.25;
            }

            // вверх-влево
            if (this.x_vec == -0.7 && this.y_vec == -0.7) {
                this.angle = Math.PI*1.75;
            }
        },
        draw: function() {
            map.circle(this.x-x_cam, this.y-y_cam, 10, "red");
        },
        update: function() {
            this.x += this.x_vec*this.speed;
            this.y += this.y_vec*this.speed;
            x_cam += this.x_vec*this.speed;
            y_cam += this.y_vec*this.speed;
        },
        createSound: function() {
            var angle_step = Math.PI*2/10;
            for (var i=0; i < 10; i++) {
                map.particles.push(new Particle(this.x, this.y, i*angle_step));

            }
        }
    }

    var Particle = function(x=300, y=300, angle=0) {
        this.x= x;
        this.y= y;
        this.angle = angle;
        this.x_vec= Math.cos(angle);
        this.y_vec= Math.sin(angle);
        this.speed = 5;
        this.tail = [];
        for (var i=0; i < 20; i++) {
            this.tail.push({
                "x": x,
                "y": y,

            })
        }
        this.draw= function() {
            map.circle(this.x-x_cam, this.y-y_cam, 3, 'black');
            /*for (var i=0; i < this.tail.length; i++) {
                map.circle(this.tail[i].x-x_cam, this.tail[i].y-y_cam, 3, 'black');

            }*/
        };
        this.update= function() {
            this.x += this.x_vec*this.speed;
            this.y += this.y_vec*this.speed;
        }
        this.update_tail = function() {
            for (var j=this.tail.length-1; j > 0; j--) {
                    this.tail[j] = this.tail[j-1];

            }
            this.tail.pop();
            this.tail.unshift({
                "x": this.x,
                "y": this.y,
            })
            //this.tail[0].x = this.x;
            //this.tail[0].y = this.y;
        }

    }

    $("body").keydown(function (event) {
    //console.log(snake);
        if (direction[event.keyCode] != undefined) {
            var pl_direction = direction[event.keyCode];
            player.setDirection(pl_direction, true);
        } else {
            if (event.keyCode== 13) {
                if (game_status == 'active') {
                    game_status = 'pause';
                } else {
                    game_status = 'active';
                }
            } else if (event.keyCode == 32) {
                player.createSound();
            }
        }

    });

    $("body").keyup(function (event) {
    //console.log(snake);
        if (direction[event.keyCode] != undefined) {
            var pl_direction = direction[event.keyCode];
            player.setDirection(pl_direction, false);
        }
    });

    var particle = new Particle();

    var game_loop = function() {
        if (game_status == 'active') {
            window.requestAnimationFrame(game_loop);

            map.alpha_clear(0.15);
            ctx.fillStyle = "black";
            ctx.fillRect(100-x_cam, 100-y_cam, 100, 100);
            player.setVecs();
            player.update();
            for (var i in map.particles) {
                //map.particles[i].update_tail();
                map.particles[i].update();
                map.particles[i].draw()
            }
            //particle.update_tail();
            particle.update();
            particle.draw();
            player.draw();
        }
    }

    game_loop();
</script>
</body>
</html>

Мне обязательно нужно имитировать viewport, т.к. вся карта не помещается в экране
Вопрос: как сделать такой эффект, чтобы он не был сильно тяжёлым и не тормозил бразуер, но при этом выглядел достойно (не как в code shippet №2)


text:
Q: Passing C# Property to a function using ref I have a C# property in "public ClassA "as follows: //assume private fields exist
public String Test
{
    get
    {
        return _test;
    }
    set
    {
        _test= value;
        OnPropertyChanged("Test");
    }
}

If I update the value of Test from ClassA member functions I get notified of its property change.
But if I pass this property to a function belonging to some other class, as a parameter, and change its value from there I don't get notified.
Is it because it's getting passed by value ?
I thought I would try passing this with ref but that doesn't compile.
How do I pass this property to any function and still get notified of the change ?

A: If you pass the property's value to another method as a parameter, then change its value, the value of the property remains unchanged.
How about passing the parent object and manipulating its properties at the receiving end? After all the setter belongs to that object, not to the value it holds.

A: What you are proposing will lead to incredibly smelly code. A simple way to achieve this is to call the function, and assign its return value to your property:
this.Test = SomeObject.CallSomeFunction();

this will achieve the objective of keeping your code nice and simple, and it will trigger the property change notification. You could call the target function and pass a reference of the caller to it (SomeObject.CallSomeFunction(this);), but in 99% of cases you shouldn't be doing this simply so the target function can manipulate the properties of the caller.

A:
Is it because it's getting passed by value ?

Yes

I thought I would try passing this with ref but that doesn't compile

Because only fields and variables can be passed by reference; properties are actually more like methods (actually pairs of methods: get/set). A workaround is to do something like that:
string test = Test;
SomeMethod(ref test);
Test = test;


text:
Q: Using zsh alias to quickly clone a git repository with custom folder name I want an alias shortcut to achieve the following:

*

*Clone a github repository with a custom folder name

*Open it in my fav text editor (atom)

I currently use this inside ~/.zshrc:
alias quickstart="git clone https://github.com/myname/quickstart-html-template.git new_html_project && atom new_html_project"
Can I parameterize new_html_project?

A: You can't define parameters in an alias, you need to use a function:
quickstart() {
    git clone https://github.com/myname/quickstart-html-template.git "$1" && atom "$1"
}

Add that to your .zshrc instead of the alias definition.


text:
Q: Converting days to seconds in MySQL I need to convert the following column into seconds:
+----------------------+
| duration             |
+----------------------+
| 00:15:52.22          |
| 01:15:51.65          |
| 02:15:50.93          |
| 27 days, 06:22:41.11 |
| 27 days, 07:22:40.76 |
| 27 days, 08:22:40.43 |
+----------------------+

The problem is that the TIME_TO_SEC() function works correctly only for the first three rows returning the following result:
+-----------------------+
| TIME_TO_SEC(duration) |
+-----------------------+
|            952.220000 |
|           4551.650000 |
|           8150.930000 |
|             27.000000 |
|             27.000000 |
|             27.000000 |
+-----------------------+

Is there a function I can use that would convert all the rows into seconds?

A: The following answer assumes that every entry in the duration column takes the form of a time component only, or of some number of days followed by a time component.  Assuming this, we can use a CASE expression to selectively parse either type of data.  In the case there is a days component, we can convert to seconds and add this to the number of seconds from the time component.
SELECT
    CASE WHEN duration LIKE '%days%'
         THEN CAST(SUBSTRING_INDEX(duration, ' ', 1) AS UNSIGNED) * 24*60*60 +
              TIME_TO_SEC(SUBSTRING_INDEX(duration, ' ', -1))
         ELSE TIME_TO_SEC(duration)
    END AS duration_in_seconds
FROM yourTable

Output:

Demo here:
Rextester


text:
Q: Member function for typedef I am wondering if the following is possible in C++.
I have a typedef
template<typename T> struct wrapper {};
using vecint = wrapper<std::vector<int>>;

and I want to write a function size for which I can use member function syntax. I.e. write
vecint v{1,3};
v.size();

instead of
vecint v{1,3};
size(v);

Why I want to do this
I do not have access to the struct wrapper.
When there is another way to accomplish this, I am glad to hear about it. But, also then I am still interested whether this is possible in C++ or not.

A: A possible way would be to wrap struct wrapper in a new class where you would add the relevant methods:
template<typename T>
class my_wrapper: public wrapper {
public:
    using wrapper;        // import parent ctors
    int size {
        return ::size(*this);
    }
};
using vecint = my_wrapper<std::vector<int>>;

Then (assuming that the function size is defined somewhere), you could do:
vecint v{1,3};
v.size();


text:
Q: Create Jenkins WorkflowMultibranchProject job with groovy init I am automating the configuration of Jenkins masters to get to a one-click instantiation. We have 6 standard jobs we create for each instance and I'd like to be able to create them via groovy.init.d scripts but haven't found examples for this type of job.
We use the cloudbees Bitbucket Team/Project plugin that ends up creating jobs of type WorkflowMultibranchProject with additional configuration to connect to our on-prem Bitbucket instance.
Does anyone have samples of creating such a job via groovy? Am I better off trying to use JobDSL to create the job (am doing that already for a Mother Seed job)
[UPDATE] : with the help of the answer below came up with a full sample creating an entire Bitbucket Team/Project Job: https://github.com/redfive/jenkins-init/blob/master/init.groovy.d/core-jobs.groovy

A: Having used Job DSL, I'm 50/50 undecided if it is easier compared to using Groovy (as Job DSL lacks support for some of the config options).
An example for the similar OrganizationFolder can be found in @coderanger's article on https://coderanger.net/jenkins/:
  // Create the top-level item if it doesn't exist already.
  def folder = jenkins.items.isEmpty() ? jenkins.createProject(OrganizationFolder, 'MyName') : jenkins.items[0]
  // Set up GitHub source.
  def navigator = new GitHubSCMNavigator(githubOrg)
  navigator.credentialsId = cred.id // Loaded above in the GitHub section.
  navigator.traits = [
    // Too many repos to scan everything. This trims to a svelte 265 repos at the time of writing.
    new jenkins.scm.impl.trait.WildcardSCMSourceFilterTrait('*-cookbook', ''),
    // We have a ton of old branches so try to limit to just master and PRs for now.
    new jenkins.scm.impl.trait.RegexSCMHeadFilterTrait('^(master|PR-.*)'),
    new BranchDiscoveryTrait(1), // Exclude branches that are also filed as PRs.
    new OriginPullRequestDiscoveryTrait(1), // Merging the pull request with the current target branch revision.
  ]
  folder.navigators.replace(navigator)

The next time when I set up an instance, I'd likely give that a try.