text:
Q: How do I center an object in java I want to make a simple program that will have one button and multiple fields. When I was planning this out in my head I wanted to use a gridlayout, or at least cent the button at first since I am learning. Here is what I have so far, my question that I am leading to is where do I put in my grid layout, or do I set the alignment center in the panel, frame or button?
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Normal {
    public static void main(String[] args) {
        JFrame frame = new JFrame("test");
        JButton button = new JButton("why");
        JPanel panel = new JPanel();
        JTextField field= new JTextField();

    //button
    button.setSize(50, 50);

    //Field
    field.setSize(250, 25);

    //Frame
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.add(panel);
    frame.add(field);
    frame.add(button);

        }
}

A: Always add the components in a Container of the JFrame. Set the Layout of Container as GridLayout. For example You can change your code as follows:
import java.awt.GridLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Normal {
    public static void main(String[] args) {
        JFrame frame = new JFrame("test");
        JButton button = new JButton("why");
        JPanel panel = new JPanel();
        JTextField field= new JTextField();
        Container c = frame.getContentPane();
        c.setLayout(new GridLayout(3,1));//Devides the container in 3 rows and 1 column
        c.add(panel);//Add in first row
        c.add(button);//Add in second row
        c.add(field);//Add in third row
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        }
}

A: In an approach where you extend your class from JFrame, you could simply set where you would like to add the components. If you have a panel with ex. a button, you could add it like this:
add(panel, BorderLayout.CENTER);

Hope this helps.


text:
Q: How do you set up multiple variable regression with no intercept term? Can anyone help with the set up of a multiple variable regression function that does not have an intercept (no beta hat 0)? I've tried to figure it out based on class notes for one variable regression without an intercept and multiple variable regression with an intercept but my answers seem way way off.
This is the specific question:

A: Ditch the intercept term and fit as usual. Unlike in regression with an intercept, the model matrix (typically denoted by $X$) will not have a column of $1$s. However, if you make a matrix $X$ with each vector of variable values as a column, then the usual equation works: $\hat\beta=(X^TX)^{-1}X^Ty$.
At least in R software, the reported $R^2$ sneakily uses a different formula than usual. While this choice can be defended, it is worth knowing that it does this and that other software might, too. Their $R^2$ in this situation is:
$$
R^2=1-\dfrac{\sum\left(
y_i-\hat y_i
\right)^2}{
\sum y_i^2
}
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Picard iterations of a matrix I need help with this problem. I think i got the first three questions of the exercise, but i'm stuck at the fourth one.
We consider the map $T:{\mathbb{R}^2}\longrightarrow{\mathbb{R}^2}$ defined by:
$T(a,b):= \left( \begin{array}{cc}
cos(\alpha) & sin(\alpha)  \\
-sin(\alpha) & cos(\alpha)  \end{array} \right)$$\left( \begin{array}{c}
a \\
b  \end{array} \right)$
Prove that:
1-T has only one fixed point,$(0,0)$.
2-T maps $B[(0,0),1]$ to itself.
3-Picard iterates $(T^n(a,b))$ don't converge to the fixed point, unless $(a,b)=(0,0)$
4-If we consider $U=\frac{1}{2}(I+T)$ (where I is the identity matrix), prove that $U$ has the same fixed point, that still maps  $B[(0,0),1]$ to itself, but in this case, the iterates $(U^n(a,b))$ converge to $(0,0)$.

A: Show that, for $v\in B[(0,0),1]$, $||U(v)||< k||v||$ for some $k\in (0,1)\subset\mathbb{R}$.
This will mean that $U$ is a contration; therefore its image does not abandon $B[(0,0),1]$.
If you don't know what a contraction is, try showing that
$$
||U^n(v)||< k^n||v||
$$
and since $k<1$, when $n\rightarrow\infty$, $||U^n(v)||\rightarrow 0$. Now, since $U(0,0)=(0,0)$ in $B[(0,0),1]$ and $U$ is linear, the last limit, through continuity, implies that $U^n(x,y)\rightarrow (0,0)$.
If you're using the contraction argument, since $(0,0)$ it's the unique fixed point of $U$ and is a contraction, $U^n(v)$ converges to $(0,0)$ as $n\rightarrow\infty$ for every $v\in B[(0,0),1]$.
NOTE: To compute $||v||$ just use the Euclidean metric, that is, if $v=(x_1, x_2,...,x_n)\in\mathbb{R}^n$, then
$$
||v||=\sqrt{x_1^2+x_2^2+...+x_n^2}
$$
To compute $||U(v)||$, write $U(v)$ as a vector and apply the above expression. You will get a lot of numbers but since you're dealing with sines and cosines, remember that $cos(x)^2+sin(x)^2=1$.

A: It might be helpful to get a geometric understanding of this transformation. This makes 1,2,3 obvious.

$T$ is the rotation of angle $-\alpha$.

For 4, use the observation above to translate this in $\mathbb{C}$.

$$T(z)=e^{-i\alpha}z\qquad\Rightarrow\qquad U(z)=\frac{1+e^{-i\alpha}}{2}z.$$

You will see that for $\alpha\not\in 2\pi\mathbb{Z}$, $U$ is a strict contraction ($M$ Lipschitz for some $0<M<1$). Of course, 4 is false when $\alpha\in 2\pi\mathbb{Z}$.
If you don't feel comfortable using the isometry between $\mathbb{R}^2$ Euclidean and $\mathbb{C}$, just perform the more tedious trigonometric reductions that show $U$ is a contraction, using the Euclidean norm.


text:
Q: Excluding certain attributes from being labeled in ArcMap? I am using ArcMap 10.1, and i am labeling a roadway system but would like to exclude certain road labels from being displayed.

A: Right click add the labeling toolset

Click on 'label manager' the icon next to the Labeling drop down menu...

When the label manager appears choose the layer you want to work on on the left panel, then the label field from the drop down menu on the right. Then at the bottom use the 'SQL Query' option to query the records you want to label.


text:
Q: Cut the url from the questionmark I read the new topics from an IPB forum and I get this result when I want to get the topic link:
http://1234.23123/forum/topic/2-rgewgreg/?do=findComment&comment=2

How can I cut this ?do=findComment&comment=2 from the url?
It is dynamic so it would be nice if it recognize the questionmark and then delete the rest of the url and the questionmark.

A: you dont need to use a regex for that you can use
let id = "http://1234.23123/forum/topic/2-rgewgreg/?do=findComment&comment=2";
let removeStr = id.substr(id.indexOf('?'));
console.log(id.split(removeStr)[0]);

output : http://1234.23123/forum/topic/2-rgewgreg/

A: Could you please try following.
var a = 'http://1234.23123/forum/topic/2-rgewgreg/?do=findComment&comment=2';
console.log(a.replace(/\?.*/g,''));

A: you can use Substring function
like this
string.substring(starposition,length);
example
in case of php
  var str="http://1234.23123/forum/topic/2-rgewgreg/?do=findComment&comment=2";
    var res= str.substring(0,str.indexof("?")-1);
console.log(res);


text:
Q: HSV shows black as green I am trying to detect a (what I assume) black line.
However when I look at the HSV image it shows me that the line is green.
When I make the image black or white, the line can't distinguish itself from the white background.

How come the black line is showing up as green when I convert to HSV? and if so, what colour range is green in HSV?
This is how I filter black as of now:
            hsv = cv.cvtColor(self.frame, cv.COLOR_BGR2HSV)
            self.frame = hsv
            # define range of black color in HSV

            lower_val = np.array([0,0,0])

            upper_val = np.array([179,100,130])

            # Threshold the HSV image to get only black colors
            mask = cv.inRange(hsv, lower_val, upper_val)

            res = cv.bitwise_and(self.frame,self.frame, mask= mask)

            # invert the mask to get black letters on white background

            res2 = cv.bitwise_not(mask)

            # display image

            cv.imshow("img", res)

            cv.imshow("img2", res2)


text:
Q: Express with AngularJS - How to parse data directly into an html template? I have an Express / Angular app and I am trying to add a title via the app.get() method, rather than adding it via angular. Is there a way to do this without using a template engine?
My server.js file:
app.use(express.static(path.join(__dirname, 'public')));

My route (using express.Router)
// Default load public index.html
publicRouter.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, '../../../public', 'index.html'));
});

I am pretty sure I am doing this wrong. I would like to do something like this:
publicRouter.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, '../../../public', 'index.html'), {
        title: "My Webpage",
    });
});

So that then in my index.html, I can render the title directly into the template:
<title>{{ title }}</title>

... without it being part of the route scope. This is because the title is rendered before angular is loaded, and if I load it in Angular, the tags show momentarily while angular loads. This isn't cool.

A: I might have a solution to your problem.
Maybe try creating a custom directive for it.
Something like this
<title my-title=" 'title' "><\title>

Will be rendered to
<title ...>{{title}}<\title>

This way, the title tag will be empty as long as angular isn't loaded.

A: Depending on how complex index.html is, and given your requirement of not using a server-side templating engine, you could use template literals (i.e., strings wrapped in backticks instead of quotes which lets you do multiline strings nicely; available in ES6 or TypeScript compiled to ES5) to interpolate your page title.
publicRouter.get('/foo', function(req, res) {
    res.send(getHtml('My webpage'));
});

publicRouter.get('/bar', function(req, res) {
    res.send(getHtml('My other webpage'));
});

function getHtml(title) {
    return `
        <!doctype html>
        <html>
            <head>
                <title>${title}</title>
            </head>
            <body ng-app="myApp">
                <div ng-view></div>
                <script src="js/app.js"></script>
            </body>
        </html>
    `;
}


text:
Q: Making a latex table from systemfit model? I am using systemfit to model respondents' prioritization of certain local projects. Their priorities are categorized into six categories.
model1<-prior1~ fem+ party_id2 + unemployed

model2<-prior2 ~ fem+ party_id2 + unemployed

model3<-prior3 ~ fem+ party_id2 + unemployed

model4<-prior4 ~ fem+ party_id2 + unemployed

model5<-prior5 ~ fem+ party_id2 + unemployed

model6<-prior6 ~ fem+ party_id2 + unemployed

fitsur_ind <- systemfit(list(project1 = model1, project2 = model2, project3 = model3, project4=model4, project5=model5, project6=model6), data= dat)

summary(fitsur_ind)

result1 <- texreg::extract(fitsur_ind)

I want to make a Latex table where each column is a different priority (DV) but when I extract the object using texreg it extracts the coefficients for every equation. Is there a way to use texreg to extract the results separately?

A: In your texreg, htmlreg, screenreg etc. call, add the argument beside = TRUE to display multiple equations as separate columns. This works in some of the models, and the help pages (e.g., ?extract.systemfit in this case) show details for the respective model implementations.


text:
Q: How to display images from a folder in a gridview? How to display images from a folder in a gridview whose path is stored in ms sql database?

A: This is a pretty common task, and Microsoft has code examples.  See here: http://msdn.microsoft.com/en-us/library/aa479350.aspx

A: how to display different images in gridview C# .NET
http://www.eggheadcafe.com/community/aspnet/2/10065396/how-to-display--different-images-in-gridview.aspx
Display Images In GridView From DataBase C# VB.NET
http://csharpdotnetfreak.blogspot.com/2009/07/display-images-gridview-from-database.html


text:
Q: Homology generated by lifts of simple curves Let $\Sigma$ be a compact connected oriented surface and $p:\tilde{\Sigma}\to\Sigma$ a finite regular cover.
Consider the set $\Gamma$ of simple closed curves on $\tilde{\Sigma}$ obtained as a connected component of $p^{-1}(\gamma)$ where $\gamma$ is a simple curve in $\Sigma$.
My question is: is it true that $\Gamma$ generates $H_1(\tilde{\Sigma},\mathbb{Z})$ and if not, can we identify the subspace it generates?

A: I just posted a paper with Justin Malestein entitled "Simple closed curves, finite covers of surfaces, and power subgroups of $\text{Out}(F_n)$" that gives a nearly complete answer to this question.  It can be downloaded here.
In this paper, we construct examples of finite covers of punctured surfaces where the first rational homology is not spanned by lifts of simple closed curves.  We can deal with any surface whose fundamental group is a nonabelian free group, though we do not know how to deal with closed surfaces.
In fact, we prove a much more general result.  Let $\mathcal{O}$ be a subset of a nonabelian free group $F_n$ that is contained in the union of finitely many $\text{Aut}(F_n)$-orbits.  For instance, if $F_n$ is the fundamental group of a punctured surface then $\mathcal{O}$ could be the set of all simple closed curves (or even for some fixed $m \geq 0$ the set of all closed curves with at most $m$ self-intersections).  Then there exists a finite-index normal subgroup $R$ of $F_n$ such that $H_1(R;\mathbb{Q})$ is not spanned by the homology classes of powers of elements of $\mathcal{O}$.
I also should point out two related papers (see the introduction to my paper above for a more complete summary of the literature).  The paper
T. Koberda, R. Santharoubane,
Quotients of surface groups and homology of finite covers via quantum representations,
Invent. Math. 206 (2016), no. 2, 269–292.
constructs examples of finite covers $\widetilde{S}$ of surfaces $S$ such that $H_1(\widetilde{S};\mathbb{Z})$ is not spanned by lifts of simple closed curves on $S$.  They can deal with any orientable surface whose fundamental group is nonabelian (including closed surfaces).  However, unlike us they cannot ensure that lifts of simple closed curves do not span a finite-index subgroup of $H_1(\widetilde{S};\mathbb{Z})$.  This is why they only deal with integral homology as opposed to rational homology.
Another interesting paper along these lines is
B. Farb, S. Hensel,
Finite covers of graphs, their primitive homology, and representation theory,
New York J. Math. 22 (2016), 1365–1391.
Among other things, this paper proves that the "rational simple closed curve homology" is everything for abelian covers.  It also constructs counterexamples to this for genus $1$ surfaces with $1$ or $2$ punctures.

A: As far as I know, this is open.
In fact, I think the following weaker question is open.
Let $\Theta$ be the set of loops $\gamma$ in $\widetilde \Sigma$ such that the image of $\gamma$ in $\Sigma$ is not a filling curve.  If $\Sigma$ is not a pair of pants, is $H_1(\widetilde \Sigma ; \mathbb{Z})$ generated by $\Theta$?
This weaker statement would give a new proof of the congruence subgroup problem for the mapping class group of a genus two surface (which is a theorem of Boggi).
I don't know the answer even when $\Sigma$ is the 5-punctured sphere.  I do know that if $\Sigma$ is the 5-punctured sphere, then the answer to the weak question is yes provided the deck group is generated by a subgroup carried by an embedded pair of pants.

A: If $\Sigma$ is a sphere, disk, annulus or torus, then this is true.
If $\Sigma$ is a thrice-punctured sphere, then this is false.
The only simple closed curves on a thrice-punctured sphere are
parallel to the three boundary curves. In the preimage of a
finite-sheeted cover, one obtains only boundary parallel curves,
and therefore the subspace of homology is the subspace generated
by boundary components.
I'm not sure what happens for more complicated surfaces in general. It
seems to work for index two covers and planar covers.


text:
Q: Rails: Marking content as complete for individual users, when content is common across them I'm relatively new to Rails, so apologies in advance if this is an obvious question. I could not find an answer through searching.
I'm building a basic application which acts as an educational course - users can view lessons, take in the content, and mark lessons as 'complete' accordingly.
I would like users to be able to see which lessons are complete, by marking them as such in the course overview.
I have a Users model and a Lessons model, and the lessons are identical per user at present. If lessons were unique per user, this would presumably be solvable with a boolean 'complete' column for each lesson. This is not the case in this application, however - some users will have completed a lesson; others will not have.
How would I best go about a solution to this? All suggestions and ideas welcome.

A: Use many-many association and establish relationship among the 3 models.
class Student < ActiveRecord::Base
   has_many :progresses
   has_many :subjects, through: :progresses
end

class Subject < ActiveRecord::Base
  has_many :progresses
  has_many :students, through: :progresses
end

class Progress < ActiveRecord::Base
  belongs_to :student
  belongs_to :subject
end

To be precise use this link to get good understanding on many-many association :)

A: Third model, say Progress or Completion or Grades or UserLessons... that will belong to user and lesson, and have a field called complete or score or grade....

A: It's a classic case of many-to-many relation.
User can read multiple lessons
Lessons could be read/complete by multiple users

So to do this is to create another model with   column user_id lesson_id as a foreign key for user and lesson and create an additional column completed boolean


text:
Q: Cannot persist data using kotlin and spring data I wanted to take advantage of inheritance in JPA. I have three classes:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(
        name = "MY_DISC",
        discriminatorType = DiscriminatorType.STRING
)
open class BaseClass(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long? = null,
        ...shared things
)

@Entity
@DiscriminatorValue(value = "FIRST_VALUE")
class FirstClass(...shared) : BaseClass(...shared things ) {

}

@Entity
@DiscriminatorValue(value = "SECOND_VALUE")
class SecondClass(...shared) : BaseClass(...shared things ) {

}

I have also created repositories:
@Repository
interface FirstClassRepo : CrudRepository<FirstClass, Long> {
}
... other similar

However, whenever I am trying to save FirstClass using save on the repository I get:
org.postgresql.util.PSQLException: The column index is out of range: 4, number of columns: 3.

I have already checked a lot of links, however none of them were working, is there any tutorial for kotlin + spring data jpa + inheritance? Or am I missing something in that solution?

A: Apparently, the only thing that was working, was adding a field with the annotation
@Column("MY_DESC", insertable = false, updatable = false)

It solves all of my concerns.


text:
Q: How to make a windows service that has a task tray icon for managing it? I'm familiar with writing windows service applications. I've written a few using various approaches - third party libs, the .NET-provided approach, etc. None of my prior service applications had any way to interact with them, though.
I'm needing now to write a windows service application, but it will need a task tray icon that perhaps brings up a "management GUI" when you click on it.
What is the appropriate pattern for doing this?
Should the service be its own application, but is able to be interacted with through external means - perhaps a database that it polls for config changes? Should it use IPC or something?
Is there a way to make a windows service also have a GUI so that the management GUI and the service are all just the same application?

A:
Is there a way to make a windows service also have a GUI

No; a windows service doesn't have an (interactive) desktop by definition. Anything that points to getting that to work will be a very dirty hack at the very best.

Is there a way to make a windows service also have a GUI so that the management GUI and the service are all just the same application?

You can share code by putting common stuff in a library or something. You can even share the entire codebase and run the application with an --service commandline argument (for example) and the GUI part without (or with --gui) argument(s).

interacted with through external means - perhaps a database that it polls for config changes?

That is a possibility but not the fastest or most efficient

Should it use IPC or something?

I would opt for that. You can use whatever you want; a REST API, WCF, TCP/UDP connections, sockets, (named) pipes, memory mapped I/O... whatever you choose, it will be some sort of IPC. You can even send custom commands to your service but that is very, very limited.
If it were up to my I'd implement it using WCF. But I'm kinda biased, I do lots of WCF stuff.

A: Summary
Yes, your Windows service can have a GUI. However, that GUI has to be a separate project (say a Windows Forms project). It's just that the Windows Forms project and your Windows service project have to use whatever is common in between such as database, APIs (e.g. WCF), library, etc. Typically, you would carry out the necessary functionality inside your Windows service and update state / settings in your Windows Forms application.
Adding Your GUI to Task Tray along with a Shortcut Menu
In the Main method of your Windows Forms application, create an object of the NotifyIcon class. You can also create a ContextMenu object and assign it to the ContextMenu property of the NotifyIcon object to allow the tray icon to have shortcut menu. Here is a sample:
[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    using (var icon = new NotifyIcon())
    {
        icon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);

        var contextMenu = new ContextMenu();
        var mnuProperties = new MenuItem()
        {
            Text = "Properties"
        };
        var mnuQuit = new MenuItem()
        {
            Text = "Quit"
        };

        mnuProperties.Click += mnuProperties_Click;
        mnuQuit.Click += mnuQuit_Click;

        contextMenu.MenuItems.Add(mnuProperties);
        contextMenu.MenuItems.Add(mnuQuit);

        icon.ContextMenu = contextMenu;
        icon.Visible = true;

        Application.Run();
    }
}

private static void mnuQuit_Click(object sender, EventArgs e)
{
    Application.Exit();
}

private static void mnuProperties_Click(object sender, EventArgs e)
{
    var propertiesForm = new PropertiesForm();
    propertiesForm.Show();
}

Needless to mention, you can add as many menu items to the context menu, add forms, etc.
One last point, it doesn't have to be a Windows Forms application. It can very well be a WPF application instead.


text:
Q: SSH asking for password after ssh-copy-id I created a key on my machine with ssh-keygen. I copied the key to remote machine using ssh-copy-id.
Tried to connect to remote machine but it asked me the password. Both machines are ubuntu (local 11.04, remote 8.04)
EDIT (Output with extra verbose)
Here is the verbose from ssh:
    OpenSSH_5.8p1 Debian-1ubuntu3, OpenSSL 0.9.8o 01 Jun 2010
debug1: Reading configuration data /home/leandro/.ssh/config
debug1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 192.168.1.217 [192.168.1.217] port 22.
debug1: Connection established.
debug3: Incorrect RSA1 identifier
debug3: Could not load "/home/leandro/.ssh/id_rsa" as a RSA1 public key
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /home/leandro/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /home/leandro/.ssh/id_rsa-cert type -1
debug1: identity file /home/leandro/.ssh/id_dsa type -1
debug1: identity file /home/leandro/.ssh/id_dsa-cert type -1
debug1: identity file /home/leandro/.ssh/id_ecdsa type -1
debug1: identity file /home/leandro/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_4.7p1 Debian-8ubuntu1
debug1: match: OpenSSH_4.7p1 Debian-8ubuntu1 pat OpenSSH_4*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.8p1 Debian-1ubuntu3
debug2: fd 3 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "192.168.1.217" from file "/home/leandro/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /home/leandro/.ssh/known_hosts:6
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsa
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsa,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-dss-cert-v00@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 132/256
debug2: bits set: 527/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 72:d5:e9:a2:09:46:e5:f2:e9:65:39:56:ba:f8:bc:38
debug3: load_hostkeys: loading entries for host "192.168.1.217" from file "/home/leandro/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /home/leandro/.ssh/known_hosts:6
debug3: load_hostkeys: loaded 1 keys
debug1: Host '192.168.1.217' is known and matches the RSA host key.
debug1: Found key in /home/leandro/.ssh/known_hosts:6
debug2: bits set: 555/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/leandro/.ssh/id_rsa (0x21ef1040)
debug2: key: /home/leandro/.ssh/id_dsa ((nil))
debug2: key: /home/leandro/.ssh/id_ecdsa ((nil))
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/leandro/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/leandro/.ssh/id_dsa
debug3: no such identity: /home/leandro/.ssh/id_dsa
debug1: Trying private key: /home/leandro/.ssh/id_ecdsa
debug3: no such identity: /home/leandro/.ssh/id_ecdsa
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
optimaster@192.168.1.217's password:

leandro@FiberWork72:~$ cd ~/.ssh/
leandro@FiberWork72:~/.ssh$ ls
config  id_rsa  id_rsa.pub  known_hosts  known_hosts.bkp  known_hosts.old

EDIT:
Ok. I notice something here. I was looking at the ~/.ssh/authorized_keys and realized that in the end of the key it's written this:
me@my_computer_name

instead of:
me@my_computer_ip

I don't know if have something to do with it, but...

A: This tag wiki has good information about ssh and how to troubleshoot some basic problems.
My first guess would be to check the permissions on ~/.ssh and ensure it is not writable by any user other than you. You can read more on that here.

A: Did you name your key something different than id_rsa, id_dsa or id_ecdsa?
By default, ssh will only try with these key names. If you have chose another one, no panic, you can either specify the key name using -i or specify it once and for all in your ~ssh/config file.
Example with -i (perhaps you need to add the ~/.ssh/ before the key name, I can't recall):
ssh -i <your_priv_key_name> myuser@192.168.1.217

Example of ~/.ssh/config
Host 192.168.1.217
  IdentityFile ~/.ssh/<your_priv_key_name>

A: Assuming that "myuser" is a valid user on the remote system, the key needs to be placed in that users ~/.ssh/authorized_keys (if using the default configuration).
Check your sshd_config on the remote server to ensure what the authkey file should be, look for the line AuthorizedKeysFile.


text:
Q: How can I update the issue body of a github issue via the api? I can't seem to find documentation regarding this.
I want to update the body or title of an issue via the API.
Any help would be greatly appreciated.

A: I actually found the documented solution. It is using the PATCH method.
See here: https://developer.github.com/v3/issues/#edit-an-issue
PATCH /repos/:owner/:repo/issues/:number

Request Parameters: https://developer.github.com/v3/issues/#parameters-3

A: You also have an alternative (which still uses the GitHub API): GitHub CLI gh 1.6 (Feb. 2021)

GitHub CLI now supports editing issues and pull requests, and pull request auto-merge

GitHub CLI 1.6 now includes support for editing issues and pull requests, allowing you to:

*

*Edit the title or body

*Add metadata like labels, assignees, reviewers, projects, and milestones

This latest release also supports enabling auto-merge for pull requests.


text:
Q: why my git bash root command not working? I uploaded nodejs project using nestjs and typeform to awsec2 and used pm2 startnpm -- start command.
My server is working well now.
Since then, however, the pm2 command has not been heard at all and the pm2 input speed has been very slow.
Why did this happen?


text:
Q: ListView with custom layout for hidden fields? Currently I have a listview bound to an adapter (in a DialogFragment):
adapter = new SimpleCursorAdapter(getActivity(),
                                  android.R.layout.simple_list_item_2,
                                  null,
                                  new String[] { "_id", "name" },
                                  new int[] { android.R.id.text1, android.R.id.text2 },
                                  0);
listView.setAdapter(adapter);

However, I would like to show only the name, but still keep the id, because when the user selects an item, the id is returned to the calling activity.
Would I need to have a custom layout with a hidden TextView or is there a better way to get the id from the current item?

A: Ok You may go with Custom adapter.
But if you don't want to do it.
You can change the default behavior of your code by Overriding a bindView().
            adapter = new SimpleCursorAdapter(NavDrawer.this,
                    android.R.layout.simple_list_item_1,
                    null,
                    new String[] { "_id", "name" },
                    new int[] { android.R.id.text1},
                    0){
                @Override
                public void bindView(View view, Context context, Cursor cursor) {
                    super.bindView(view, context, cursor);
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    String _id = cursor.getString(cursor.getColumnIndex("_id"));
                    TextView tv = (TextView) view.findViewById(android.R.id.text1);
                    tv.setText(name);
                    //here you can store your id on textview tag
                    tv.setTag(_id);
                }
            };

for getting the id
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        String _id = tv.getTag().toString();
     }
});

A: You can use this layout for your SimpleCursorAdapter :
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/txt_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/txt_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

</RelativeLayout>

Name it as custom_layout then change your SimpleCursorAdapter as follows:
    adapter = new SimpleCursorAdapter(getActivity(),
                                  R.layout.custom_layout,
                                  null,
                                  new String[] { "_id", "name" },
                                  new int[] { R.id.txt_id, R.id.txt_name},
                                  0);
listView.setAdapter(adapter);

The txt_id TextView will be hidden and only the txt_name will be visible to the user.

A: Instead creating again a wheel, you could use CursorAdapter.
Below example how to use it in fragment (I'm using getActivity() to get context).
//test: generating elements
ArrayList<String> values = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    values.add("word" + values.size());
}

//test: adding elements to cursor
MatrixCursor mc = new MatrixCursor(new String[]{"_id", "name"});
for (int i = 0; i < values.size(); i++) {
    mc.addRow(new Object[]{i, values.get(i)});
}

listView = (ListView) inflate.findViewById(R.id.listView);
adapter = new CursorAdapter(getActivity(), mc, false) {

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ((TextView) view.findViewById(android.R.id.text1)).setText(cursor.getString(cursor.getColumnIndex("name")));

        //just example how to get _id
        Log.d("xxx", "it's id is " + cursor.getString(cursor.getColumnIndex("_id")));
    }

};

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d("xxx", "clicked id:" + id);
    }
});

listView.setAdapter(adapter);

A: Simply , just donot set text for the item that you donot want to show.. hope this works..
thanks


text:
Q: Cached immutable value: avoid lock Suppose I have the following code:
struct Obj {
    mutable bool valueIsCached_;
    mutable int value_;
    const int parameter_;

    Obj (int parameter) : valueIsCached_ (false), parameter_ (parameter) {
    }

    int getValue () const {
        if (!valueIsCached) {
            value_ = calculateValue ();  // #1
            valueIsCached_ = true;       // #2
        }
        return value_;
    }

 private:
    int calculateValue () {
        /* calculate value based on parameter and return it;
           return value only depends on value of parameter_
           (no side effects; no dependence on global state)
        */
    }
 };

This code is, obviously, thread-safe if the compiler does not reorder the lines marked #1 and #2. The worst thing which can happen is multiple calculation of value_. The code, however, gets thread-unsafe as soon as we cannot guarantee that #2 happens after #1.

*

*How can we avoid this?

*Do things get worse if the type of value_ is, e.g., a struct?

A: You need to insert a barrier. Here's code for VC++:
int getValue () const {
    if (!valueIsCached_) {
        value_ = calculateValue ();  // #1
        _WriteBarrier();             // force value_ to be written first.
        valueIsCached_ = true;       // #2
    }
    return value_;
}

Note that this is assuming calculateValue is thread-safe, because it can be called by multiple threads, and that writing to value_ and valueIsCached_ more than once is safe.


text:
Q: Introducing backslash and quote at beginning of string I want to convert "her" to "\"her".
I've tried using insert method:
>> "her".insert(0,'\"')
=> "\\"her"

and
>> "her".insert(0,'"')
=> ""her"

None of them gives me what I want: "\"her"

A: "her".insert(0,'"')

actually returns "\"her", which is what you said you wanted in the first place.
If you want to obtain "\"her\"", you might want to use Object#inspect:
"her".inspect
=> "\"her\""

Or, you can simply concatenate quotes at the beginning and at the end:
'"' + "her" + '"'
=> "\"her\""

A: If you just want "\"her"
a = "her".insert(0,'\"')
#=> "\\\"her"
puts a
#=> \"her

If you want output "\"her\""
a = "her"
#=> "her"
b = '\"'+a+'\"'
#=> "\\\"her\\\""
puts b
#=> \"her\"

A: I think your code is fine, you just don't know the meaning of \\ in console.
The first \ is escape character and second \ is character itself.
You will see \"her in the text foo.txt as you expected by:
File.write("foo.txt", "her".insert(0,'\"'))


text:
Q: Creating Flash application using WebOrb Ruby/Rails Ok, this may seem like a stupid question (for Flash Developers) but I really can't figure this out.
So, I want to create somekind of an API for Flash/Flex applications so a user can use my lib in order to connect to my WebOrb Rails server.
I don't have any problem with the rails part but things get a little bit difficult with the flash part.
So, I saw from the example that Flex is using the RemoteObject to connect/retrieve data.
The question is how can I create a Flash file that connects/retrieves data from WebOrb (i couldn't find the RemoteObject - is an include I should make?).
If that is not possible, can I create some sort of library in Flex, that can be linked in Flash in order to achieve the same result?
Thx

A: What you're looking for is most likely the NetConnection Actionscript class. Depends on the format of your API though. If it's just XML over HTTP, you could easily just use the URLLoader class as well.
NetConnection
link text
URLLoader
link text


text:
Q: Build a third dataframe based on rows in two different dataframes matched by multiple selection criteria I want to check if there is any row in one dataframe ("apx") where an entry from the "AD" column in apx matches an entry in the "AD" column in another dataframe ("npx"), AND, where the SD entry from the matched row is within 13 units of the other.
I've checked several different references on SO, but couldn't find an answer due to my need to build a third dataframe (and other reasons).
My working trial is this...
       npx <- data.frame(TN = c(111, "Z2", 4, "fox", 34256, 4782, "ZGJU45"),
              SD=c( 100, 200, 100, 600, 500, 115, 455),
              AD=c( "34YY", "37PD", "123M", "235W", "37PD", "123M", "1WW"))

       apx <- data.frame(TN = c(222, "X34", 5, "bear", 47789, 37281, "VF456"),
              SD = c(101, 201, 310, 450, 515, 660, 505),
              AD = c("123M", "23XY", "5S S", "1WW", "27 30R", "14M", "37PD"))

Note: The AD entries "123M" "1WW", and "37PD" appear in apx and in npx. The first and third of these appear twice in npx.
Insure factors are changed to characters:
       i <- sapply(apx, is.factor)
       apx[i] <- lapply(apx[i], as.character)
       i <- sapply(npx, is.factor)
       npx[i] <- lapply(npx[i], as.character)

My fifth try...(forcing SD entries to integers)...
      test5 <- apx[which(apx$AD == npx$AD &
                 as.integer(npx$SD) - as.integer(apx$SD) < 13)
         %in% as.integer(npx$SD), ]

One of my earlier tries....
      test3 <- apx[which(apx$AD == npx$AD &
                 as.integer(npx$SD) - as.integer(apx$SD) < 13)
         %in% setequal(npx$SD, apx$SD), ]

What I am looking for in a third dataframe is....
             TN     SD     AD
      [1]    222   101    123M

because 123M (first row of apx) is found in the third row of npx and the corresponding entries for SD are within 13 units of each other (100 and 101); However, at the second occurence of 123M in npx (in row six), the difference between the corresponding entries for SD are 15 units apart.  Actually, I'm looking for only those instances where the SD entry in npx is < 13 greater (only) than the corresponding SD entry in apx.
       [2]    bear  450    1WW

because 1WW (4th row of apx) is found in the last row of npx and the corresponding entries for SD are within 13 units of each other (450 and 455).
       [3]    VF456 505    37PD

While 37PD (last row of apx) is found in the second row of npx, that entry doesn't quality 37PD since the corresponding SD values are in excess of 13 units apart (200 and 505); However, the corresponding entries of SD for the other appearance of 37PD in npx (row five) are within 13 units of each other, thereby qualifying 37PD to appear in the resulting dataframe.
I'm gritting my teeth expecting someone to show me a very simple way to do this, but rather suffer that embarrassment than spin more wheels. Thanks in advance.

A: If I understand what you're trying to do, I think we can use the merge and subset functions:
merge_df <- merge(npx, apx, by = 'AD', suffixes = c('npx','apx'))

subset(merge_df, SDnpx - SDapx <= 13 & SDnpx >= SDapx)

   AD  TNnpx SDnpx TNapx SDapx
3 1WW ZGJU45   455  bear   450

But I'll admit that I don't actually quite understand just what your condition you're trying to enforce. If we're interested in rows which have an SD difference <= 13, then we can do the following:
subset(merge_df, abs(SDnpx - SDapx) <= 13)

    AD  TNnpx SDnpx TNapx SDapx
1 123M      4   100   222   101
3  1WW ZGJU45   455  bear   450
5 37PD  34256   500 VF456   505

Then getting the data into your final desired form (which isn't quite clear either) is just renaming and/or dropping columns from the data.frame.


text:
Q: WAS Starting applications with scripting, Which bat or sh file will be called Start the application:
The following example invokes the startApplication operation on the MBean, providing the application name that you want to start.
Using Jacl:
$AdminControl invoke $appManager startApplication myApplication
Using Jython:
AdminControl.invoke(appManager, 'startApplication', 'myApplication')
I wanna know which bat or which sh file will get invoked as a result of the above script which is invoked implicitly by WAS Integrated Solution Console when anyone try to:

*

*Navigate to http : // IP:PORT /ibm/console/login.do

*Applications > Application Types > WebSphere enterprise applications

*Highlight/Checkbox/Select Any Enterprise Application fro the list of Enterprise Applications listed.

*Press Stop/Start
I was expecting this action to invoke %WAS_HOME%\profiles\AppSrv01\bin\startServer.bat
But I couldn't find the echo messages I put in that file in any log file

A: This is all implementation details, but the admin console doesn't actually use any scripts.  Instead, it uses JMX directly to invoke the same MBean ApplicationManager start/stopApplication operation that the Jacl snippet does.


text:
Q: how to print a really big datastructure in clojure? When I try to print a really long array, it gets cut off at a certain length
[-1 -40 -1 -32 0 16 74 70 73 70 0 1 1 0 0 1 0 1 0 0 -1
 -37 0 67 0 8 6 6 7 6 5 8 7 7 7 9 9 8 10 12 20 13 12 11
 11 12 25 18 19 15 20 29 26 31 30 29 26 28 28 32 36 46 39
 32 34 44 35 28 28 40 55 41 44 48 49 52 52 52 31 39 57 61
 56 50 60 46 51 52 50 -1 -37 0 67 1 9 9 9 12 11 12 ...]

I would like it not to do that if I'm persisting a data structure to file. How can this be done?

A: The special variable *print-length* determines how much of a given structure is printed. Like any other dynamic var, you can use binding to set its value in a block.
user> (binding [*print-length* 2] (prn (range 200)))
(0 1 ...)
nil
user> (binding [*print-length* nil] (prn (range 200)))
(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199)
nil


text:
Q: AWS function policy is bigger than the limit I have an Amazon API gateway linking to AWS java Lambda back end.
I am trying to add a new Method to a Resource and I get the following error when choosing the integration point for the new method.
The error is:
" The function policy is bigger than the limit. Please manually update policy via lambda cli."
How do I go about updating the policy and why is this error occurring ?
Many thanks,
Richard

A: Ok as suggested the issue is with a 20kb limit with the Policy document. You can get the policy document via the Cli though for me it didn't help much as unless there is a way to overwrite it and a way to optimise it then its pretty useless. That said there may be I couldn't find it.
Note this is a Lambda issue in this case not a API Gateway one. In short I had a lot of endpoints (~30/50) which for an API is nothing in the wild however each endpoint needs a relevant few lines in the policy document where its linking the Lambda Code to the API Gateway endpoint. at around 30 to 50 endpoints this fills the Policy document.
There may be better ways to do this .... but at that limit even when I deleted a few unused endpoints it didn't help. The solution was to delete the Lambda Function code and remake it.
However this will only clear the Policy document until you recreate the links again. In order to avoid this problem occurring again I had to reduce the endpoints to the core ones then use a passed parameter to trigger the correct code within Lambda.
    Instead of  https://www.something.com/cars/iswindowopen
    do
    Instead of  https://www.something.com/cars
    {
     "call":"iswindowopen"
    }

In sort pass the many endpoints as a parameter. This was porbably my fault for not reading enough of the documentation but this limit is well hidden in my opinion so watch out =)

A: If you use python, you can use the Boto3 lambda API get_policy to see what resource-based policies are attached with your lambda functions and then use remove_permission to clean up duplicate policies or policies that aren't needed. You can also use AWS Lambda CLI get-policy and remove-permission to inspect and clean up your policies.
You can check out this article for information on how to fix this issue.
After you fix this issue, you should configure the permission for your API to invoke Lambda using a resource based policy or an IAM role to prevent getting this error in the future.


text:
Q: Find index position of partial or entire Array2 in Array1 (sequential order) Here is what I am trying to do:
String[] Array1 = { "the", "quick", "brown", "fox", "jumps",
                     "over", "the", "lazy", "dog", "in", "the",
                     "barn" };

String[] Array2 = { "in", "the", "barn", "next", "to",
                     "the", "chickens" };

int index = Array.IndexOf(Array1, Array2);
Console.WriteLine("The first occurrence of partial Array2 is at index {0}.", index);

Obviously, the code above returns a value of -1, since the entire Array2 is not found within Array1.
I'd like the result of index to be 9.
What would be the most efficient way to find a partial array within another array?

A: We can compare the first element of the second array and find it's index in the first array and then iterate over it comparing successive elements for both to check if the Array2 is completely contained in Array1.
Something like this should work:
String[] Array1 = { "the", "quick", "brown", "fox", "jumps",
                 "over", "the", "lazy", "dog", "in", "the",
                 "barn" };

String[] Array2 = { "in", "the", "barn", "next", "to",
                 "the", "chickens" };

int index = Array.IndexOf(Array1, Array2[0]);
int subArrayFlag = 1;

if(Array2.Length + index > Array1.Length)
{
    Console.WriteLine("Array2 cannot be sub array of Array1!");
}
else
{
    for(int i =0;i<Array2.Length; i++)
    {
        if(Array.IndexOf(Array1, Array2[i]) >= 0)
        {
            if(Array2[i] == Array1[index + i])
                continue;
            else
                subArrayFlag = 0;
                break;
        }
        else
        {
            subArrayFlag = 0;
        }
    }
    if(subArrayFlag == 1)
    {
        Console.WriteLine("Array2 is subarray of Array1!");
    }
    else
    {
        Console.WriteLine("Array2 is not sub array of Array1!");
    }
}

Console.WriteLine("The first occurrence of partial Array2 is at index {0}.", index);

The above code can detect if the entire Array2 is contained in Array1 or not!

A: You can create a loop and use IndexOf until you got a result:
String[] Array1 = { "the", "quick", "brown", "fox", "jumps","over", "the", "lazy", "dog", "in", "the","barn" };

String[] Array2 = { "in", "the", "barn", "next", "to","the", "chickens" };

int index = -1;

for (int j=0; j < Array2.Length; j++){
    index = Array.IndexOf(Array1, Array2[j]);
    if(index >= 0)
       break;
}

A: You can use the below method to get the first occurrence index in the Array1. In this way, you don't have to worry about values that exist in Array2 but not Array1.
private int GetFirstOccurenceIndex(string[] arr1, string[] arr2)
    {
        var keyIndexDict = new Dictionary<string, int>();

        for (var i = 0; i < arr1.Length; i++)
        {
            var key = arr1[i];
            if (!keyIndexDict.ContainsKey(key))
                keyIndexDict[key] = i;
        }

        foreach (var key in arr2)
        {
            if (keyIndexDict.TryGetValue(key, out var arr1Index))
                return arr1Index;
        }
        return -1;
    }

Example:
string[] arr1 =
{
        "the", "quick", "brown", "fox", "jumps",
        "over", "the", "lazy", "dog", "in", "the",
        "barn"
};

string[] arr2 =
{
       "someValueDoesntExistInArray1", "in", "the", "barn", "next", "to",
        "the", "chickens"
};

int index = GetFirstOccurenceIndex(arr1, arr2);
Console.WriteLine("The first occurrence of partial Array2 is at index {0}.", index);


text:
Q: Elasticsearch: search/order by overall tag weight I have to solve a problem that exeeds my very basic knowhow of elasticsearch.
I have a set of objects - each one has a set of tags. Like:
obj_1 = ["a", "b", "c"]
obj_2 = ["a", "b"]
obj_3 = ["c", "b"]

I want to search the objects using weighted tags. For example:
search_tags = {'a': 1.0, 'c': 1.5}

I want the search tags to be an OR query. That is - I don't want to exclude documents that don't have all of the queried tags. But I want them to be ordered by the one that has the most weight (sort of: each matched tag multiplied by its weight).
Using the example above the order of the ducuments returned would be:

*

*obj_1 (score: 1.0+1.5)

*obj_3 (score: 1.5)

*obj_2 (score: 1.0)

What would be the best approach to this regarding the document's structure and the correct way to query ES?
There is a similar question here: Elastic search - tagging strength (nested/child document boosting) only that I do not want to specify the weight when indexing - I want it done when searching.
My current setup is as follows.
The objects:
[
   "title":"1", "tags" : ["a", "b", "c"],
   "title":"2", "tags" : ["a", "b"],
   "title":"3", "tags" : ["c", "b"],
   "title":"4", "tags" : ["b"]
]

And my query:
{
    "query": {
        "custom_filters_score": {
            "query": {
                "terms": {
                    "tags": ["a", "c"],
                    "minimum_match": 1
                }
            },
            "filters": [
                {"filter":{"term":{"tags":"a"}}, "boost":1.0},
                {"filter":{"term":{"tags":"c"}}, "boost":1.5}
            ],
            "score_mode": "total"
        }
    }
}

The problem is that it only returns object 1 and 3. It should match object 2 (has tag "a") as well, or am I doing something wrong?
UPDATE AS SUGGESTED
Ok. Changed boost to script to calculate the minimum. Removed minimum match. My request:
{
    "query": {
        "custom_filters_score": {
            "query": {
                "terms": {
                    "tags": ["a", "c"]
                }
            },
            "filters": [
                {"filter":{"term":{"tags":"a"}}, "script":"1.0"},
                {"filter":{"term":{"tags":"c"}}, "script":"1.5"}
            ],
            "score_mode": "total"
        }
    }
}

Response:
{
    "_shards": {
        "failed": 0,
        "successful": 5,
        "total": 5
    },
    "hits": {
        "hits": [
            {
                "_id": "3",
                "_index": "test",
                "_score": 0.23837921,
                "_source": {
                    "tags": [
                        "c",
                        "b"
                    ],
                    "title": "3"
                },
                "_type": "bit"
            },
            {
                "_id": "1",
                "_index": "test",
                "_score": 0.042195037,
                "_source": {
                    "tags": [
                        "a",
                        "b",
                        "c"
                    ],
                    "title": "1"
                },
                "_type": "bit"
            }
        ],
        "max_score": 0.23837921,
        "total": 2
    },
    "timed_out": false,
    "took": 3
}

Still getting wrong order and one result missing. obj_1 should be before obj_3 (because it has both tags) and obj_2 is still missing completely. How can this be?

A: There were 2 problems with my example.

*

*The "a" term is a stopword so it was discarded and only "c" term was being used.

*The custom_filters_score query has to include "constant_score" query so that all terms have the same weight before boosting.

Now it works!


text:
Q: XSL: nested  in RTF Template I'm having trouble getting my RTF template to accept a nested choose in my first cell.  I have:
<?choose?>
  <?when: FIRST_COLOR='Red'?>
    <?FIELD_VALUE?>
  <?end when?>
  <?otherwise?>
    <?choose?>
      <?when: SECOND_COLOR?>
        <?xdofx:FIELD_VALUE_2||'Z'?>
      <?end when?>
      <?otherwise?>
        <?FIELD_VALUE_2?>
      <?end otherwise?>
    <?end choose?>
  <?end otherwise?>
<?end choose?>

I also tried without the colon in the when statements, but instead of an error, I only get two out of 50 records.

A: I found that a nested if worked instead.
<?xdofx:if FIRST_COLOR='Red' then
    FIELD_VALUE
  else
  if SECOND_COLOR!='' then
    FIELD_VALUE_2||'Z'
  else
    FIELD_VALUE_2
end if?>

A: If your original example was the code you were actually using, you were missing colons.  It should be:
<?otherwise:?>
That would cause an issue, but I cannot say whether it would have caused your issue since you did not specify the exact error you were getting.


text: Q: Routing is disabled for LAN users while choosing all-net for IPSec tunnel I have VPN with L2TP/IPSec server and tunnel configured. When I choose all-nets 0.0.0.0/0 to allow connection from any computer in the world, all LAN users with subnet 10.0.0.0/8 are disconnected from internet. How can I exclude local subnet from being listed in all-net?


text:
Q: Android WebView - NTLM Authentication I have a WebView embedded in my application. I am trying to view a webpage that uses NTLM authentication. How can I perform the NTLM authentication using the WebView and view this page?
I was successfully able to authenticate to this page using DefaultHttpClient and the JCIFS Library. But how can I do it for the WebView?

A: It has been two years since I asked this question. In the meantime, I figured out the answer to this question -
WebView supports NTLM authentication out-of-the-box. The onReceivedHttpAuthRequest callback in WebViewClient has a method parameter a method parameter named handler. This is of the type HttpAuthHandler. handler.proceed(username, password) will automatically authenticate to the web server using NTLM protocol. This handler abstracts the authentication protocol used. Both Basic and NTLM authentication work using the same line of code.

A: I'm having the same problem! There is another indirect way. You get the HttpResponse and then save the html file to the internal storage and then load the file into the WebView. I never tried this before, though.


text:
Q: Is there a hook available when creating a tag in Subversion? I think the question explains it all, but let me explain what I want to do.
I am playing around with the idea of whenever a tag is created in my repo, all the commit messages entered since the previous tag are entered into a wiki page.  That way, people do not need access to the subversion server to see what commits were made for each tag.
Perhaps there is an easier way, but I was thinking that I could do it by wiring in a hook for tag creation.  Thoughts?  Advice?
Thanks

A: There is no operation "tag creation" for svn, all folders' names such as tags, trunk, etc - are just convention on standard SVN repository layout. What you call "tag creation" is in truth - a creation of a new svn location (which is specially known on a server side as copied from another location). All operations on files - uploading changes, adding new files, deletion, even changing svn properties - are commit operations. That is why what you need is to write a script and set it as a pre-commit or post-commit hook on SVN server.
According to your well described task I can give an idea on how I see the implementation.
This script should check the path being commited (or after) whether it looks like
some_svn_path/tags/tag_name
, then find the previous tag in this folder
some_svn_path/tags/tag_name_prev
and get the svn revision of it, then get the original path from current transaction (path from which this tag is copied from), probably
some_svn_path/trunk
, and finally get log messages from original svn path from revision of the previous tag till the current revision.


text:
Q: Организация указателей элементов двумерного массива Здравствуйте. Допустим у меня динамически выделенный двумерный массив 3*5 (пусть будет матрица):
int** mat = malloc(sizeof(int*)*3);
for(int i = 0; i < 3; i++)
    mat[i] = malloc(sizeof(int)*5);

Я хочу пробежаться не по всей матрице, а только по всем элементам от начальной точки (1,2) (вверх и вправо соотвественно).
Верна ли подобная аритметика указателей в данном случае:
int** ptr = &(&mat[1][2]);
ptr[0][0] == mat[1][2]; /// верно ли равенство ?
ptr[0][1] == mat[1][3]; /// "
ptr[1][1] == mat[2][3]; /// "

со сдвигом вправо в целом проблем меньше, так как можно просто взять original_mat + i и тогда например mat[0][5] = original_mat[0+i][5] является верным использованием ариметики, как на счет сдвига вверх? То есть верно ли сказать что расстояние между адрессами 2 строки в ширь явяется расстоянием "одного передвижения" размером соответвующего указателя. Или это совсем не обязательно и они разбросаны.
Или же разбросаны только в случае динамического выделения, а например при стандарте с99 если определить матрицу mat[length][width], то выше изложенный метод доступа с определенной точки к суб-матрице будет работать ?
Или единственный способ это сделать, это создать новый двумерный массив с соответсвующими размерами и переместить указатели всей строки (каждый указатель является указателем на сплошной ряд элементов всего столбца или части его - зависит от второй координаты) вручную в массив указатель друг за другом ?
Насколько понятна задача (доступ к суб-матрице с определнной точки), насколько понятны предложения о решение ?

A: Сейчас Вы выделяете память сначала на указатели строк, затем каждому такому указателю выделяете место для самой строки. Верно, что выделенные куски памяти под строки не обязаны располагаться друг за другом.
Не могу подсказать, как работает выделение памяти сразу под двумерный массив, но точно могу сказать, что подобный способ не единственный. Советую использовать линейный массив как двумерный — в нём легко будет перепрыгивать по указателям.
int h = 3;
int w = 5;
int* mat = malloc(sizeof(int) * h * w);

Тогда обращаться к элементу с индексами (1,2) можно будет как mat[1*w+2].
UPD. В целом, первые два Ваши равенства логически правильны. С третьим не согласен, думаю, при итерации первого индекса второй как бы переходит в ноль. То есть:
ptr[1][1] == mat[2][1];

Но стоит учесть нюанс, что адрес (&) мы можем брать у переменной в памяти. Брать указатель указателя не получится, ибо это не переменная, а значение. Не компилируется, в общем.
Дальше я сделал такую программку, чтобы проверить, как выделяется память при объявлении сразу двумерного массива:
int h = 3;
int w = 5;
int mat[h][w];
for (int i = 0; i < h * w; i++) {
    mat[i / w][i % w] = i + 1;
}
int* ptr = mat[0];
for (int i = 0; i < h * w; i++) {
    int val = ptr[i];
    printf("%d ", val);
}
printf("\n");

Получаем красивый вывод:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Подтверждает предположение о монолитном выделении памяти под двумерный массив.

A: Я тоже составил небольшую проверку:
int main() {

    int** mat = (int**)malloc(sizeof(int*) * 3);
    for (int i = 0; i < 3; i++) {
        mat[i] = (int*)malloc(sizeof(int) * 5);
        printf("mat[%d] = %p ", i, mat[i]);
        for (int j = 0; j < 5; j++) {
            mat[i][j] = i * 3 + j;
            printf("mat[%d][%d] = %d\n", i, j, mat[i][j]);
        }
    }
    int* elem = &mat[1][2];
    int **ptr = &elem;
    ptr++;
    printf("mat[1] = %p", ptr); // Абсолютно другой адресс чем у mat[1]
    ptr++;
    printf("mat[2] = %p", ptr); // Абсолютно другой адресс чем у mat[2]

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            printf("mat[%d][%d] = %d\n",i, j, ptr[i][j]);
}

То есть единственный способ выделить суб-матрицу в данном случае, это вручную переписать адресса всей нужной строки, как я и писал в вопросе.


text:
Q: Problema en procedimiento almacenado de mysql (Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '=') Tengo un procedimiento almacenado, que intenta validar que el usuario y el correo que se está ingresando no exista en la base de datos antes de crear el registro (insertarlos) en la base de datos. El código que tengo es este:
CREATE DEFINER=`root`@`localhost` PROCEDURE `ups_crearEmpresa`(IN `_usuario` VARCHAR(16), IN `_nombre` VARCHAR(30), IN `_ap1` VARCHAR(30), IN `_email` VARCHAR(50), IN `_password` TEXT, IN `_ip` TEXT)
BEGIN
set @token =SHA(_email+now()+_nombre);
set @pass = _password;

#Se valida que el correo no exista actualmente en la tabla de usuarios para empresa
SET @validaremail = (select email from empresas_usuariosprincipales where email=_email) ;
#Se valida que el usuario de la empresa no exista en la tabla de usuarios para empresa
set @validarusuario = (select usuario from empresas_usuariosprincipales where usuario=_usuario) ;

IF (_usuario  = @validarusuario ) THEN
set @a = 2;
SELECT @a codigo, 'El nombre de usuario ya existe.' as mensaje;

ELSE IF (_email =  @validaremail) THEN
set @a = 3;
SELECT @a codigo, 'La cuenta de correo electrónico ya existe.' as mensaje;
ELSE
#Se insertan los datos en la tabla empresas para obtener el id de la empresa
INSERT INTO empresas (TOKEN, fecharegistro, id_paquete) values (@token, now(), 1);
set @idempresa = (SELECT MAX(id) FROM empresas);

#se insertan los datos en la tabla de usuarios para empresas
INSERT INTO empresas_usuariosprincipales  (id_empresa, usuario, password, email, nombre, apellido1, ip)
values (@idempresa, _usuario, _password, _email, _nombre, _ap1, _ip);

#se crea registro que contiene los privilegios para la empresa con las características del plan gratuito.
INSERT INTO  empresas_privilegios(id_empresa, perfilpublico, vercvpostulados, publicarofertas, ofertasmensuales, ofertasconsumidas, usuariosadicionales, usuariosconsumidos, mascaracorreo, mailbox, topofertas)
values (@idempresa, 1, 1, 1, 10, 0, 0, 0, 0, 0, 0);

#se crea el registro de la tabla de configuraciones
INSERT INTO empresas_config (id_empresa) values (@idempresa);

set @a = 1;
SELECT @a codigo, 'La cuneta se creó con éxito.' as mensaje, @token token;

END IF;
END IF;
END

En localhost me funciona de maravilla pero en el servidor de producción me arroja el siguiente error que no logro reparar :(
Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='
Realice un testo y el problema está en los if, me está mandando ese error al comparar el valor de la variable que recibo con el valor que le asingo de la consulta.
IF (**_usuario  = @validarusuario** ) THEN

En este enlace dicen posibles soluciones:
https://stackoverflow.com/questions/11770074/illegal-mix-of-collations-utf8-unicode-ci-implicit-and-utf8-general-ci-implic
Ya actualicé mis tablas, una por una corriendo este comando, pero sigue sin funcionar:
ALTER TABLE users CHARACTER SET utf8 COLLATE utf8_general_ci;

Gracias por sus comentarios. Un abrazo.

A: Ya encontré el problema. Por alguna razón, al exportar e importar la base de datos al servidor de producción se había cambiado el motor de la tabla. Tenía InnDB, solo lo cambié a MyISAM y quedó resuelto :)
prnt.sc/ko2gls
GRACIAS POR TODO!


text:
Q: resolver lista de nombres metodo burbuja python Buenas tengo un trabajo que hacer de programacion en python tengo la mitad acabada pero nesesito ayuda con el metodo burbuja para que ordene una lista de nonbres alfabeticamente dada por el usuario tengo la parte de la lista preguntandole al usuario los nombres eh imprimirlos pero el motodo burbuja tengo entendido que solo sirve en nombres, una recomendacion que escuche es poner el metodo brubuja con ascii pero no entiendo como funciona ascii le pondre un ejemplo al final gracias por su ayuda:
ejemplo:
"Ponga un nombre"
Juan
Alejandro
Esmeralda
Kevin
Resultado:
"4 numeros fueron dados"
Alejandro
Esmeralda
Juan
Kevin

A: Es muy sencillo, solo tienes que conocer como se hace el ordenamiento en burbuja
aquí te pongo un pedazo de código que hace el ordenamiento, no se si sirva pero puedes probarlo y adaptarlo a lo que necesitas.
 def ordenamientoBurbuja(lista,tam):
      for i in range(1,tam):
          for j in range(0,tam-i):
              if(lista[j] > lista[j+1]):
                     k = lista[j+1]
                     lista[j+1] = lista[j]
                     lista[j] = k;

Como te digo, no se si funciona, lo he escrito aquí y no tengo como probarlo.


text:
Q: What's wrong with this simplest jflex code? I'm learning jflex, and wrote a simplest jflex code, which makes a single character #:
import com.intellij.lexer.FlexLexer;
import com.intellij.psi.tree.IElementType;

%%

%class PubspecLexer
%implements FlexLexer
%unicode
%type IElementType
%function advance
%debug

Comment = "#"

%%

{Comment} { System.out.println("Found comment!"); return PubTokenTypes.Comment; }
.                                        { return PubTokenTypes.BadCharacter; }

Then I generate a PubspecLexer class, and try it:
public static void main(String[] args) throws IOException {
    PubspecLexer lexer = new PubspecLexer(new StringReader("#!!!!!"));
    for (int i = 0; i < 3; i++) {
        IElementType token = lexer.advance();
        System.out.println(token);
    }
}

But it prints 3 nulls:
null
null
null

Why it neither return Comment nor BadCharacter?

A: It's not jflex problem, actually, it's because the idea-flex changes original usage.
When use jflex to write intellij-idea plugins, we are using a patched "JFlex.jar" and "idea-flex.skeleton", later defines the zzRefill method as:
private boolean zzRefill() throws java.io.IOException {
    return true;
}

Instead of original:
private boolean zzRefill() throws java.io.IOException {

  // ... ignore some code

  /* finally: fill the buffer with new input */
  int numRead = zzReader.read(zzBuffer, zzEndRead,
                                          zzBuffer.length-zzEndRead);
  // ... ignore some code

  // numRead < 0
  return true;
}

Notice there is a zzReader in the code, and which holds the string #!!!!! I passed in. But in the idea-flex version, which is never used.
So to work with idea-flex version, I should use it like this:
public class MyLexer extends FlexAdapter {
    public MyLexer() {
        super(new PubspecLexer((Reader) null));
    }
}

Then:
public static void main(String[] args) {
    String input = "#!!!!!";
    MyLexer lexer = new MyLexer();
    lexer.start(input);
    for (int i = 0; i < 3; i++) {
        System.out.println(lexer.getTokenType());
        lexer.advance();
    }
}

Which prints:
match: --#--
action [19] { System.out.println("Found comment!"); return PubTokenTypes.Comment(); }
Found comment!
Pub:Comment
match: --!--
action [20] { return PubTokenTypes.BadCharacter(); }
Pub:BadCharacter
match: --!--
action [20] { return PubTokenTypes.BadCharacter(); }
Pub:BadCharacter


text:
Q: De Rham Cohomology of the tangent bundle of a manifold I would like to compute the de Rham cohomology of the tangent bundle $TM$ of a manifold $M$. It seems to me that we can just homotopy each fibre to a point, and that this would give a homotopy equivalence between $TM$ and $M$. Since de Rham cohomology is a homotopy invariant, this would imply that $H^*_{\text{dR}}(TM) \cong H^*_{\text{dR}}(M)$.

Is it always true that the tangent bundle of a manifold is homotopic to the manifold itself by the homotopy of each fibre with a point?

A: Yes, that's true. In fact every vector bundle is homotopy equivalent to the base space, and in fact deformation retracts onto the base space. To prove this:
Let $p : E \to M$ be a smooth vector bundle, and $s : M \to E$ the zero section. It's a general fact that $s$ is an embedding, so we can identify $M$ with the image of $s$. Define a deformation retraction $H_t : E \to E$ by:
$$H_t(\xi) = t \cdot \xi.$$
It follows directly from the definition of a vector bundle that each $H_t$ is smooth. Indeed look at a trivializing chart $(U, \varphi)$ where $U \subset M$ is an open set and $\varphi : p^{-1}(U) \to V \times \mathbb{R}^k$ is a homeomorphism (with $V \subset \mathbb{R}^n$ an open set) Then if $\varphi(\xi) = (x, \vec{v})$, then $\varphi(H_t(\xi)) = (x, t \vec{v})$. This is obviously smooth on the chart, so by definition it's smooth on the whole bundle.
Besides, $H_0$ is the projection onto $M$, $H_1$ is the identity, and each $H_t$ is the identity on $M$ (remember that it's the zero section of $E$, and $t \cdot \vec{0} = \vec{0}$). So $E$ deformation retracts onto $M$, thus $E$ and $M$ are homotopy equivalent.


text:
Q: select duplicate combination of columns in Oracle I know that some records in my database are in duplicates for the same date in some columns. I need to find out these duplicates and the number of times they have been duplicated so I have written this query:
select tran_date,foracid, TRAN_PARTICULAR,part_tran_type, tran_amt, count(*) as COUNTS
from tbaadm.htd,tbaadm.gam
where gam.acid=htd.acid and tran_particular like '%FEE%'
AND tran_date between '03-Mar-2014' and '11-Mar-2014'
and htd.acid in(select gam.acid from tbaadm.gam where gam.acct_ownership<>'O')
GROUP BY  tran_date, foracid, TRAN_PARTICULAR, tran_particular,
part_tran_type, tran_amt
HAVING COUNT(*) > 1
order by 2 desc;

My count Columns is not correct because I can see at some point it points that the rows are 2 while I have one. Sometimes the rows are 10 while I only have one row for the same Combination.
How can I get the five columns which are in duplicate and the number of rows for the combination of the columns?

A: Try this:
SELECT tran_date, foracid, TRAN_PARTICULAR, part_tran_type, tran_amt, count(*) as COUNTS
FROM tbaadm.htd, tbaadm.gam
WHERE gam.acid=htd.acid and tran_particular like '%FEE%'
  AND tran_date between '03-Mar-2014' and '11-Mar-2014'
  AND htd.acid IN (SELECT gam.acid FROM tbaadm.gam WHERE gam.acct_ownership <> 'O')
GROUP BY  tran_date, foracid, TRAN_PARTICULAR, part_tran_type, tran_amt
HAVING COUNT(*) > 1
ORDER BY 2 DESC;


text:
Q: EF 6 Configured for one-to-one relationship sometimes violates the constraint I'm using Fluent API in EF 6.1.3 to define a one-to-one relationship between the entity User and the entity EcommerceCart. Everything seems to work fine 99.9% of the time, but every once in a while our exception logger tells us that while trying to access User.Cart the following exception is thrown:
A relationship multiplicity constraint violation occurred: An EntityReference can have no more than one related object, but the query returned more than one related object.
We checked the database, and it seems that Entity Framework managed to create 2 Carts for the same User, despite the one-to-one relationship of the entity types.
And what strikes me the most is that the exception never occurs when the entities are created, but when the code tries to access User.Cart, finding more than one result in the database.
Any idea of how this could happen?
PS: I'm using Lazy Loading, although I don't think this should make a difference.
These are my entities:
public class User
{
    public Guid Id { get; set; }
    public virtual EcommerceCart Cart{ get; set; }
}

public class EcommerceCart
{
    public Guid Id { get; set; }
    public virtual User User { get; set; }
}

These are my configuration files:
public class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
        HasOptional(x => x.Cart).WithOptionalPrincipal(y => y.User).Map(x => x.MapKey("User_Id"));
    }
}

public class EcommerceCartConfiguration : EntityTypeConfiguration<EcommerceCart>
{
    public EcommerceCartConfiguration()
    {
        HasKey(a => a.Id);
        Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
    }
}

And this is how the EcommerceCarts table looks like:

A: Following adam0101 advice, I created the following migration, which forces
 the foreign key User_Id to be unique:
public partial class EcommerceCart_User_Index : DbMigration
{
    public override void Up()
    {
        DropIndex("dbo.EcommerceCarts", new[] { "User_Id" });
        Sql(
            @"CREATE UNIQUE NONCLUSTERED INDEX IX_User_Id
            ON dbo.EcommerceCarts(User_Id)
            WHERE User_Id IS NOT NULL");
    }
}

Unfortunately, I couldn't find any other solution using Fluent API, because it seems like there is no way to create a unique index on Navigation properties without using SQL.
If anyone knows a better solution, please let me know.


text:
Q: jquery code I am unable to understand The following piece of code is from https://github.com/tsi/inlineDisqussions/blob/master/inlineDisqussions.js
What is this piece of code doing please? I'd appreciate a plain English translation. Student here.
  // Hide the discussion.
  $('html').click(function(event) {
    if($(event.target).parents('#disqussions_wrapper, .main-disqussion-link-wrp').length === 0) {
      hideDisqussion();
    }
  });

A: What this code does is register a mouse button click event on the whole of the page.  If someone clicks on the page, the function is called.  The function is passed an event (which will be the click event).  Within the event there is a property called "target" which is the HTML element that was actually clicked.  We then ask if the clicked element has a parent ancestor element that is either an element with "id" of "disqussion_wrapper" or has a class of "main-disquission-link-wrp".   If neither of these are true, we call the function called hideDisqussion().

A: I'm not sure where you're stuck, but I'd suggest:
// Binding a click-handler to the <html> element,
// passing that event to the anonymous function:
$('html').click(function(event) {
      // if the element that was clicked does not have any ancestor elements with the
      // 'id' of 'disqussions_wrapper' or a class of 'main-disqussion-link-wrp
      if ($(event.target).parents('#disqussions_wrapper, .main-disqussion-link-wrp').length === 0) {
          // we (presumably, from the function name) hide the disqussion/disqus element(s):
          hideDisqussion();
      }
});

References:

*

*click().

*event.target.

*parents().

A: Kolban's answer is accurate.
In plain english you could also say that we simply check if the clicked element is not a child (or simply - outside) of '#disqussions_wrapper, .main-disqussion-link-wrp' - if that's the case, we call hideDisqussion().


text:
Q: Does my charm need both a relation-changed and relation-joined hook? I see a lot of charms with both a relation-changed and a relation-joined hook for their relations.  Sometimes the two hooks are even the same file, with one being a symlink to the other.  However, the juju docs say that both the relation-joined and relation-changed hooks run when a relation is joined.
Should my charm include only one hook or the other, not both?

A: This depends on the use case for the charm. Here's a good way to think of what each relation hook does and when it's executed:
relation-joined
This is always the first hook to be executed, it's also only executed once during the lifespan of that specific service to service relation. There's now guarantee on which of the two services hook will fire first, but it will always be the first of the set of relation hooks to fire off. A lot of charms don't need this, but some charms this is very important. If you have any set-up details you need to execute first, then this is where they will happen. Take a database server for example: Most database server charms use the relation-joined hook to create the database, user, password, and other details that the other service will be waiting on. It could do this during the relation-changed hook, but it would add more complexity to make sure it didn't recreate the database and user over and over again (more on why that would happen in a second).
relation-changed
This gets run once right after a successful relation-joined execution. Then every time data is sent on the wire between the services this hook is executed again. As such, it really needs to be idempotent as it will likely be executed more than once. So a lot of charms will gather the expected relation-get data and make sure it exists before continuing. As to why both the relation-joined AND relation-changed hooks fire one after the other on the joined event is likely to allow for ease of use and not require a relation-joined hook explicitly.
As to what should your charm include, that's entirely up to you and the use case for your charm. Not every charm has a relation-joined, in fact few do considering the size of the store. It's really only used when there's an explicit need to do something only once during the lifecycle of that relation. Just so we're clear, when I mean "only once", I'm speaking about executing of the juju add-relation. If you add another relation to another service the relation-joined hook and the whole lifecycle starts over again. (since you can theoretically connect multiple services to one relation on one service)


text:
Q: Form submit fails in Gmail, Yahoo, Hotmail I am in receipt of an forwarded email that has a form to be filled & submitted for a course/event registration. The form has a studentId, emailId, mobileNo, password, Confirm password  fields & a submit button.
On Gmail, I fill in details & submit, nothing happens.
In yahoo, as I type the password (after typing other fields), I get a popup that says that the form is not being submitted to yahoo & yahoo never asks password. I do a OK on the popup & submit the form, nothing happens
In hotmail, as I try to type in characters in any of the above fields the cursor disappears, so nothing to submit.
A 'view source' of the page does not show a 'form' element that I was expecting. When I do a inspect element I am able to see the static labels against each of the fields above though no form element. See a lot of tr, td wrapped in table/tbody.
I have tried reading various forums, they seem to mention that having such forms in html emails is a bad idea & better option is to provide a link. None of them say that it will not work on gmail or yahoo.
This mails with the form has been sent to many people & some of them at least have been able to submit. I am just unable to figure out the reason for the failure of the submit. I have tried IE, Mozilla & Chrome.
Any views on what the solution to the problem would be very helpful.

A: On some newer email readers the form tag is stripped out because of security issues. It's better to have the form on the Internet and a link to it from the email document.


text:
Q: SQL Select x from a set of value Hi guys i have a problem about how to select value from a set of value in SQL and my code look like this:
Select distinct subreddit from reddit
where author = (select distinct author from reddit where link_id = 't3_j56j2');

Code in the () return more than one author but when i run this query it only gets the value of one author. What should i do to get value from all the authors () part returns?

A: Use
Select distinct T.subreddit from reddit T
 where EXISTS
        (select author from reddit where link_id = 't3_j56j2'and author = T.author);

A: I guess you simply want IN instead:
Select distinct subreddit from reddit
where author IN (select author from reddit where link_id = 't3_j56j2');

Note: No need for distinct in the sub-query.

A: I would recommend to using EXIST instead of IN statement.
The IN statement will execute the full query inside the IN-statement. In the below example the (select author from reddit where link_id = 't3_j56j2') will be executed and then compared to the value in author
Select subreddit from reddit
where author IN (select author from reddit where link_id = 't3_j56j2');

If you use EXISTS instead:
Select subreddit from reddit t
where EXISTS(select rownum from reddit where link_id = 't3_j56j2' and author = t.author);

The query in exist will stop executing at the first match and will be the better option for performance.


text:
Q: java.lang.OutOfMemoryError: Failed to allocate erro Está a acontecer este erro na minha aplicação:

java.lang.OutOfMemoryError: Failed to allocate

o meu código de imagem:
URL url1 = null;
    try {
        url1 = new URL("http://www.cm-mgrande.pt" + cabecalho);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    try {
        InputStream input = url1.openConnection().getInputStream();
        Bitmap bmp = BitmapFactory.decodeStream(input);
        input.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(url1.openStream()));
        in.close();
        imgcabecalho.setImageBitmap(bmp);
        imgcabecalho.setScaleType(ImageView.ScaleType.FIT_XY);
    } catch (IOException e) {
        e.printStackTrace();

    }

o meu Android Manifest :
<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:largeHeap="true"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".Index"
    android:configChanges="orientation|screenSize"
        android:largeHeap="true"
        android:label="@string/app_name" >

    </activity>
</application>

A: Provavelmente o Bitmap é grande demais para a memória alocada pelo seu app. A documentação recomenda diversos cuidados ao lidar com criação de Bitmaps, especialmente em função da memória. Aqui tem bastante informação útil.
Recomendo que você crie um bitmap de acordo com o tamanho que será exibido. Para isso você precisa primeiro marcar o bitmap como inJustDecodeBounds, assim você só pegara as informações dele para fazer uma redução de escala e não o carregará na memória.
    BitmapFactory.Options options = new BitmapFactory.Options();

    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath , options );

    // faça o cálculo da sua escala
    int imageWidth = options.outWidth;
    scale   = Math.round( imageHeight / width );
    options.inSampleSize    = scale;

    //Remove marcação e inicia o trabalho no bitmap
    options.inJustDecodeBounds  = false;

    // Cria o bitmap com o tamanho reduzido
    Bitmap scaledBitmap = BitmapFactory.decodeFile(filePath , options);

Esta operação é custosa e não recomendo que você a faça na UI. Cria um AsyncTask ou algo assim.
Uma dica é que existem diversas librarys muito boas que fazem este serviço. A Universal Loader funciona muito bem.
Espero ter ajudado.


text:
Q: Как прочитать цифры из файла, чтоб вернулись типом int? Например read() класса FileInputStream возвращает байтовые значение симолов. Мне нужно, чтобы 3 в массива заносилась как 3.
Примечание: файл передается аргументом главной функции (args[0])

A: Может, так:
try (Scanner scanner = new Scanner(new FileReader(path)))
{
    while (scanner.hasNextInt())
        list.add(scanner.nextInt());
}


text:
Q: Insert generic element at a specific index in Doubly linked List java I have a function in my Doubly linked list class to insert an element is given index. So I made some codes that did not work.The error they said is "Cannot read field "prev" because "current" is null" .
Here is my code:
public void add(int key, E data){
    if(key<0 || key>size){
        return;
    }
    else{
        Node current = head;
        if (key==0){
            Node newLink = new Node(data);

            if (size==0)
                tail = newLink;
            else
                head.prev = newLink;
            newLink.next = head;
            head = newLink;
        }
        else{
            for(int i=0;i<key;i++){
                current= current.next;
            }
            Node newNode= new Node(data);
            newNode.next=current;
            newNode.prev=current.prev;
            size++;
        }
    }
}

Please help me how can I get the way to overcome this problem.

A: There was a few problems I saw in the code you provided. Firstly you are not advancing size in every place needed. Secondly, the for loop to advance the current is going one step further than needed.
Here is my take:
public void add(int key, E data){
    if(key<0 || key>size)
        return;
    Node current = head;
    if (key==0){
          Node newLink = new Node(data);
          if (size==0)
              tail = newLink;
          else
              head.prev = newLink;
          newLink.next = head;
          head = newLink;
   } else{
          for(int i=0;i<key-1;i++){
              current= current.next;
          }
          Node newNode= new Node(data);
          newNode.next=current;
          newNode.prev=current.prev;
  }
  size++;
}


text:
Q: Terraform conditional resource creation by array parameters I want to be able to create a resource depending on what parameter is sent to the module and depends on the values sent in the variable array I will deploy the resource or not.
(pseudo code)
var.example= ["get","post"]
if var.example.contains ("options") {
resource "aws_api_gateway_method" "api_gateway_method_options" {
  http_method = "OPTIONS"
  more_data...
}}
if var.example.contains ("post") {
resource "aws_api_gateway_method" "api_gateway_method_post" {
  http_method = "POST"
  more_data...
}}
if var.example.contains ("get") {
resource "aws_api_gateway_method" "api_gateway_method_get" {
  authorization = "NONE"
  http_method = "GET"
  more_data...
}
}

I think it is quite easy to understand what I want, is that possible with terraform?
Thanks to all
UPDATE: Thanks @Marcin @Luke2302
I put the full code of the module with the count option that is also not working:
    resource "aws_api_gateway_resource" "api_gateway_resource" {

  parent_id = var.parent_id
  path_part = var.rest_api_path_part
  rest_api_id = var.api_gateway_rest_api.id
}

resource "aws_api_gateway_integration" "api_gateway_integration_post" {
  count = contains(var.methods, "post") ? 1 : 0

  rest_api_id = var.api_gateway_rest_api.id
  resource_id = aws_api_gateway_resource.api_gateway_resource.id
  http_method = aws_api_gateway_method.api_gateway_method_post.http_method
  uri = var.lambda_invoke_arn
  integration_http_method = "POST"
  passthrough_behavior = "WHEN_NO_MATCH"
  content_handling = "CONVERT_TO_TEXT"
  type = "AWS_PROXY"
}
resource "aws_api_gateway_integration" "api_gateway_integration_get" {
  count = contains(var.methods, "get") ? 1 : 0

  cache_key_parameters = []
  rest_api_id = var.api_gateway_rest_api.id
  resource_id = aws_api_gateway_resource.api_gateway_resource.id
  http_method = aws_api_gateway_method.api_gateway_method_get.http_method
  uri = var.lambda_invoke_arn
  integration_http_method = "POST"
  passthrough_behavior = "WHEN_NO_MATCH"
  type = "AWS_PROXY"
}
resource "aws_api_gateway_integration" "api_gateway_integration_options" {
  count = contains(var.methods, "options") ? 1 : 0

  rest_api_id = var.api_gateway_rest_api.id
  resource_id = aws_api_gateway_resource.api_gateway_resource.id
  http_method = aws_api_gateway_method.api_gateway_method_options.http_method
  type = "MOCK"
  request_templates = {
    "application/json": "{\"statusCode\": 200}"
  }
}

resource "aws_api_gateway_method" "api_gateway_method_options" {
  count = contains(var.methods, "options") ? 1 : 0

  authorization = "NONE"
  http_method = "OPTIONS"
  resource_id = aws_api_gateway_resource.api_gateway_resource.id
  rest_api_id = var.api_gateway_rest_api.id
  request_parameters = var.options_request_parameters
}
resource "aws_api_gateway_method" "api_gateway_method_post" {
  count =  contains(var.methods, "post") ? 1 : 0

  authorization = "NONE"
  http_method = "POST"
  resource_id = aws_api_gateway_resource.api_gateway_resource.id
  rest_api_id = var.api_gateway_rest_api.id
  request_parameters = var.post_request_parameters
}
resource "aws_api_gateway_method" "api_gateway_method_get" {
  count = contains(var.methods, "get") ? 1 : 0

  authorization = "NONE"
  http_method = "GET"
  resource_id = aws_api_gateway_resource.api_gateway_resource.id
  rest_api_id = var.api_gateway_rest_api.id
  request_parameters = var.get_request_parameters
}

I got this error:
Error: Missing resource instance key
  on ../../modules/apigateway/apigateway_methods/main.tf line 13, in resource "aws_api_gateway_integration" "api_gateway_integration_post":
  13:   http_method = aws_api_gateway_method.api_gateway_method_post.http_method

Because aws_api_gateway_method.api_gateway_method_post has "count" set, its
attributes must be accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_api_gateway_method.api_gateway_method_post[count.index]

A: I think the following should work for you:
variable "example" {
    default = ["get","post"]
}

resource "aws_api_gateway_method" "api_gateway_method_options" {

  count =  contains(var.example, "options") ? 1 : 0

  http_method = "OPTIONS"
  more_data...
}

resource "aws_api_gateway_method" "api_gateway_method_post" {

  count =  contains(var.example, "post") ? 1 : 0

  http_method = "POST"
  more_data...
}

resource "aws_api_gateway_method" "api_gateway_method_get" {

  count =  contains(var.example, "get") ? 1 : 0

  authorization = "NONE"
  http_method = "GET"
  more_data...
}


text:
Q: SCSS @extend in @keyframes is not working im trying to create two keyframes animations which replace the content attribute of a pseudo element. Unfortunately, it looks like the @extend feature of SCSS is not working within @keyframes. Did i miss something?
Code: (open animation does not work, close does).
@keyframes open {
  0% {
    @extend .icon-after-arrow-down;
  }
  50% {
    color: transparent;
  }
  100% {
    @extend .icon-after-arrow-up;
  }
}

@keyframes close {
  0% {
    content: '\e905';
  }
  50% {
    color: transparent;
  }
  100% {
    content: '\e902';
  }
}

A: Solved by comment from @Arkellys
"@extend is when you need to chains classes, you should use mixins for this case."


text:
Q: how to make installable for java in linux i have developed an application in java for linux i need to install it in linux in my system(ubuntu 10.04) and how to make executable for linux .i have the application as jar file

A: echo "java -jar filename.jar" > runme.sh && chmod +x runme.sh

./runme.sh

A: This and this.

A: You can create a simple shell script that run the following command:
java -jar mylib.jar

and then run the script using ./myscript.sh

A: If you're targeting a different machine from the one you've developed on, you'll need to package your JAR into a .deb file and either include a JRE/JDK in the distribution, or else declare a dependency on one of the apt packaged Java distros so that apt-get installs Java at the same time as your application.

A: For Java applications with a GUI, look into Java Web Start.
I never had much luck getting menu items to work on Ubuntu Linux, but desktop shortcuts were no problem.  Maybe you can specify the exact sub-menu that the menu item is to appear under, and it will work.
JWS also works for Windows and Mac.

A: Follow this article and you need to create a file with gedit and name it with your package name.(e.g totem for totem media player listed in Applications Sound & Video) then in that file enter these lines and save to Input directory (mentioned in the above tutorial)
?package(yourpackagename):needs="X11" \
 section="Applications/Sound" \
 title="yourpackagename" \
 command="/usr/bin/yourpackagename" \
 icon="/usr/share/pixmaps/yourpackageicon"

enter your package name accordingly. Icon line is optional you can omit it. then
debian/input/yourpackagename /usr/share/menu/yourpackagename

add this line to install file
there we are adding the above created file into /usr/share/menu dir