text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to select displayed columns in datagrid
I'm working on a .NET Compact Framework 3.5 app that includes a DataGrid. I've created a BindingSource using the designer and added the bindingsource as the source of the datagrid. It automatically created columns for every suitable property of my source object type, but I don't want to display all the properties.
How do I specify which columns to display and which ones to hide? I tried playing around with the TableStyles property of the datagrid (both in code and in designer), didn't seem to have any effect.
A:
That didn't work for me as the TableStyles collection of the DataGrid control was empty at the point you specify and remains so until a DataGridTableStyle collection is added.
Using your suggestion for setting the correct value for the MappingName property, I achieved the desired result by creating and adding a new DataGridTableStyle object containing only the public fields that were required in the DataGrid.
// Create a DataGridTableStyle to hold all the columns to be displayed in the DataGrid
DataGridTableStyle myTableStyle = new DataGridTableStyle();
myTableStyle.MappingName = myBindingSource.GetListName(null); // This is the magic line
myTableStyle.GridColumnStyles.Clear();
// Add some DataGridColumnStyles
DataGridTextBoxColumn columnRowId = new DataGridTextBoxColumn();
columnRowId.MappingName = "idx"; //This must match the name of the public property
ColumnRowId.HeaderText = "Record";
tableStyleReportsSummary.GridColumnStyles.Add(columnRowId);
// Add the table style to the DataGrid
myDataGrid.TableStyles.Clear();
myDataGrid.TableStyles.Add(myTableStyle);
A:
Figured it out. I had to add the following line of code in the form's constructor, right after InitializeComponent():
myDataGrid.TableStyles[0].MappingName = myBindingSource.GetListName(null);
Then I was able to change the datagrid's TableStyles property in order to modify the displayed columns as I please.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Strange route problem in ASP.NET MVC - default route not hit
I have this two routes currently in my application after decommenting out many other ones. Let me first explain that I have quite a big application already but have come to a problem where my application does not start at the root url anymore.
If I set starting page to default.aspx then webapp starts at (example) http://localhost:55421/Default.aspx. I don't want that. I want it without Default.aspx
So I went into app properties and removed Default.aspx as starting page - now it is blank field (just like in a sample new MVC app if you create it in VS 2008).
But now application does start at the required URL but issues an error:
"The incoming request does not match any route."
Also If I use route debugger it also misses all routes and catches it by catchall route.
I don't know how all of this is possible since as I said above I have two default routes configured at this time:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Pages", action = "Display", slug = "Default" }
);
Any help appreciated
A:
Am I right in thinking you are trying to hit
http://server/{controller}/{action}/{id}
with
http://server/
If you are I think you need to provide a default for the last parameter {id}. You have a default for a parameter slug but without a default for {id} I don't think ASP.NET Routing can hit it.
If I'm right
http://server/Pages/Display
should also not hit the default route, because you are expecting id in Display?
HTH
Alex
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sharepoint 2010 reusable workflow cannot get "Start Date" and reverts to 1/1/0001
When trying to apply a reusable workflow on a calendar list to send e.g. an Email containing "Start Time" and "End Time" you will notice that the workflow always reverts this value to 1/1/0001 (the default for a DateTime whereas everything works fine for "End Time".
Setting it up:
The result:
Many solutions have been proposed online but do not work, most notably the suggestion to get the "Start Time" indirectly through an indirect lookup:
But the result is very much the same:
This is a major issue in SP2010 if you ask me...
A:
There is a solution however, even if it is not the most elegant.
To circumvent this bug and preserve the flexibility to use reusable workflows as opposed to list specific workflows (where the issue is not present) you have to create a calculated column "Start Time Text" or something similar.
Next apply following formula:
=TEXT([Start Time],"m/d/yyyy, h:mm:ss AM/PM")
This produces the desired result:
Thats it. Cumbersome, but it works...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Server in Python
I'm looking for a code review and code improvement for my own small server.
The server accepts the requests:
User Join,User Leave,User Text Notify Group Join, Group Leave, Group Notify Request Time.
The syntax for User Join/Left Group Join/Left:
**
DSLP-3.0
User Join
NameOfUser
DSLP-Body
**
The syntax for Group Notify:
**
DSLP-3.0
Group Notify
NameOfGroup
1(<--number of lines you want to send)
DSLP-Body
LineYouWantSend
**
The syntax for User Text Notify:
**
DSLP-3.0
User Text Notify
User1
User2
1(<---number of lines you want to send)
DSLP-Body
LineYouWantSend
**
The syntax for Request Time:
DSLP-3.0
Request Time
DSLP-Body
This is the code:
import socket
from socket import *
from threading import Thread
from datetime import datetime
host="localhost"
port=44444
s = socket(AF_INET, SOCK_STREAM)
SOCK_STREAM
s.bind((host, port))
s.listen(5)
trash=[]
user=["foobar"]
group=["foobar"]
def clientHandler():
platz=""
conn, addr = s.accept()
print ("Connected with", addr)
while True:
data = conn.recv(4096)
#error
if repr(data)!="b'dslp-3.0'":
print(error_firstline())
else:
while True:
data = conn.recv(4096)
platz+=repr(data)
platz+="\r\n"
trash.append(platz)
if len(trash)==2 and platz.count("\r\n")==2:
if "b'dslp-3.0'" in platz:
continue
else:
print(error_search_2nd_line(platz))
if len(trash)>4 and "b'dslp-3.0'" in platz:
pp=platz.rsplit("b'dslp-3.0'\r\n")
trash.clear()
print(error_search_2nd_line(pp[1]))
if len(trash)>6:
trash.clear()
if "request time" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
print(response_time())
platz=""
if len(platz)>31:
print(error_forthline())
if "group join" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'group join'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>33:
print(error_forthline())
platz=""
else:
print(group_join(platz))
platz=""
if "group leave" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'group leave'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>34:
print(error_forthline())
platz=""
else:
print(group_leave(platz))
platz=""
if "user join" in platz:
if len(trash)>4:
trash.clear()
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'user join'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>32:
print(error_forthline())
platz=""
else:
print(user_join(platz))
platz=""
if "user leave" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'user leave'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>33:
print(error_forthline())
platz=""
else:
print(user_leave(platz))
platz=""
if "group notify" in platz:
platz=check_dslp(platz)
for i in range(5):
if str(i) in platz:
if i==1:
if platz.count("\r\n")==5:
print(group_notify(platz))
platz=""
if i==2:
if platz.count("\r\n")==6:
print(group_notify(platz))
platz=""
if i==3:
if platz.count("\r\n")==7:
print(group_notify(platz))
platz=""
if i==4:
if platz.count("\r\n")==8:
print(group_notify(platz))
platz=""
if i==5:
if platz.count("\r\n")==9:
print(group_notify(platz))
platz=""
if "user text notify" in platz:
platz=check_dslp(platz)
for i in range(5):
if str(i) in platz:
if i==1:
if platz.count("\r\n")==6:
print(user_notify(platz))
platz=""
if i==2:
if platz.count("\r\n")==7:
print(user_notify(platz))
platz=""
if i==3:
if platz.count("\r\n")==8:
print(user_notify(platz))
platz=""
if i==4:
if platz.count("\r\n")==9:
print(user_notify(platz))
platz=""
if i==5:
if platz.count("\r\n")==10:
print(user_notify(platz))
platz=""
if "user list" in platz:
if "dslp-body" in platz:
print(user_list())
platz=""
if "group list" in platz:
if "dslp-body" in platz:
print(group_list())
platz=""
for i in range(5):
Thread(target=clientHandler).start()
s.close()
def error_search_2nd_line(platzhalter):
bb=platzhalter.rsplit("b'")
b=bb[1].rsplit("'\r\n")
platzhalter=b[0]
print (platzhalter)
liste=["group join", "group leave", "user join", "user leave", "group notify", "user text notify","user list","group list"]
bedingung=""
for x in range(len(liste)):
bedingung+=liste[x]
if x+1==len(liste):
if platzhalter not in bedingung:
trash.clear()
print(error_secondline())
else:
trash.clear()
def error_firstline():
print("dslp-3.0\r\nerror\r\n1\r\ndslp-body\r\nReceived unexpected text as first line.\r\nConnection closed by foreign host.")
def error_secondline():
print("error")
print("1")
print("dslp-body")
print("Received unexpected message type in second line.")
print("Connection closed by foreign host.")
def error_forthline():
print("dslp-3.0")
print("error")
print("1")
print("dslp-body")
print("Unexpected state while analyzing line 4.")
print("Connection closed by foreign host.")
def group_error():
print("Group is unknown.")
def user_error():
print("Source user is unknown.")
def check_dslp(platz):
if "b'dslp-3.0'\r\n" in platz:
pp=platz.rsplit("b'dslp-3.0'\r\n")
platz=pp[1]
return platz
else:
return platz
def group_join(platzhalter):
print("dslp-3.0")
print("group join ack")
y=platzhalter.split("b'group join'\r\nb'")
y=y[1].split("'")
group.append(y[0])
print(y[0])
print("dslp-body")
def group_notify(platzhalter):
if len(group)==1:
print(group_error())
for x in group:
if x in platzhalter:
pp=platzhalter.rsplit("dslp-body'\r\nb'")
ppp=pp[1].rsplit("'\r\n")
for i in ppp:
print (i)
break
if x=="foobar":
continue
elif x not in platzhalter:
print(group_error())
def group_leave(platzhalter):
y=platzhalter.split("b'group leave'\r\nb'")
y=y[1].split("'")
for x in group:
if y[0] in group:
print("dslp-3.0")
print("group leave ack")
print(y[0])
print("dslp-body")
group.remove(y[0])
break
else:
print(group_error())
def group_list():
print("Groups: ")
for i in group:
print(i)
def user_join(platzhalter):
if "b'dslp-3.0'\r\n" in platzhalter:
z=platzhalter.split("b'dslp-3.0'\r\n")
y=z[1]
y=platzhalter.split("b'user join'\r\nb'")
y=y[1].split("\r\nb'dslp-body'\r\n")
y=y[0].split("'")
user.append(y[0])
print("dslp-3.0")
print("user join ack")
print(y[0])
print("dslp-body")
else:
y=platzhalter.split("b'user join'\r\nb'")
y=y[1].split("\r\nb'dslp-body'\r\n")
y=y[0].split("'")
user.append(y[0])
print("dslp-3.0")
print("user join ack")
print(y[0])
print("dslp-body")
def user_notify(platzhalter):
if len(user)==1:
print(user_error())
for x in user:
if x in platzhalter:
pp=platzhalter.rsplit("dslp-body'\r\nb'")
ppp=pp[1].rsplit("'\r\n")
for i in ppp:
print(i)
break
if x not in platzhalter:
print(user_error())
def user_leave(platzhalter):
y=platzhalter.split("b'user leave'\r\nb'")
y=y[1].split("\r\nb'dslp-body'\r\n")
y=y[0].split("'")
user.remove(y[0])
print("dslp-3.0")
print("user leave ack")
print(y[0])
print("dslp-body")
def user_list():
print("Users are: ")
for i in user:
print(i)
A:
Packet fragmentation
data = conn.recv(4096)
#error
if repr(data)!="b'dslp-3.0'":
To quote the documentation for recv,
The maximum amount of data to be received at once is specified by bufsize.
Emphasis mine. This is a common pitfall that beginners encounter when attempting low-level socket programming. The socket library gives you no guarantee that you will actually get 4096 bytes, or even a complete message. You need to iterate until you think you have enough bytes or a valid message, however you define that.
Put another way, it would be trivially easy to write a client that sends fragmented data to your server that should be valid but will in fact be erroneously rejected.
Though I haven't tried it, socketserver seems like its rfile should be able to abstract this away for you since it handles buffering. In other words, you don't need to worry about packets or buffer sizes; you can ask for rfile.readline(), which is what you actually want given your protocol.
If you do not want the abstraction of socketserver, you can also use makefile - which is called by socketserver anyway.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is an ideal way to put a Java Web Application (Struts) into Maintenace mode?
Like all CMS systems like wordpress, Drupal has maintenance mode where user see custom message indicating site is been offline for maintenance. How can I do that in my web application made using struts?
My ideas:
1) Design separate web application with same context path and live it during maintenance and offline your original site. That second app only contains maintenance page and for page not found too it displays maintenance page.
2) Putting maintenance mode value in properties file or some xml file or database value and on every action call checking it, if it's true then redirecting to maintenance mode page. (Better than first one but there are many actions already made, will consume lot of time to insert condition code in each of them, specially in dispatch action files, but this will be permanent inbuilt app solution.)
What I am looking for?
Creating some sort of global action, which redirects every action path to maintenance page.
something like this:
<action-mappings>
<action path="/*" forward="/jsp/maintenance.jsp"/>
</action-mappings>
Any ideas would be greatly helpful.
Thanks.
A:
To block user during maintenance mode you need to switch a user from normal mode to maintenance mode. A way to intercept all incoming requests and redirect them to the maintenance mode page, is to add a Servlet Filter to your web application. Inside the Servlet Filter you need to check whether the filter is in normal operation mode, or maintenance mode.
If the filter is in normal operation mode, the request is passed on to the web application as normal. If the filter is in maintenance mode the request should be passed on to a maintenance message page instead.
The following link can help you in configuring filter in maintenance mode :
http://tutorials.jenkov.com/java-web-apps/web-app-maintenance.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you subscribe array of FormData object in Angular 2?
Service class:
sendFiles(files: File[]): Observable<any> {
const formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("file", files[i]);
}
return this.httpClient.post(this.url, formData);
}
The Component class:
uploadFile() {
this.service.sendFiles(this.files).subscribe(
response => {
this.files= response;
console.log("Files: " + JSON.stringify(this.files));
});
}
The above subscribe is only for one file.
How to do a POST and subscribe to each file?
A:
I'm not sure I understand the question, but I will attempt an answer regardless.
The observable that you subscribe to maps to a single request. If you make one POST request with your data, you will receive one response. It's up to your backend to decide what response to send back. If the response only contains one file, then your backend might not be returning what you expected.
If you don't care about making multiple requests, you can try a forkJoin or merge.
sendFile(file: File) {
const formData = new FormData();
formData.append("file", file);
return this.httpClient.post(this.url, formData)
.map(response => JSON.stringify(response));
}
const requests = this.files.map(file => this.service.sendFile(file));
forkJoin(requests).subscribe(responses => {
// An array of responses.
});
merge(...requests).subscribe(file => {
// A single response.
});
The forkJoin will individually send each request, wait until each response has returned, then emit an array of each response.
The merge will individually send each request, and emit a response when it receives it.
I don't believe you need to call subscribe multiple times, but tell me if I'm wrong.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Infant crying causes (the) release of stress hormones in both infants and adults
Infant crying causes release of stress hormones in both infants and
adults.
or
Infant crying causes the release of stress hormones in both infants and
adults.
I would use the because it is a countable noun and from what I know it should have some determiner.
A:
From Cambridge Dictionary:
release [noun]
[uncountable] the act of flowing out from somewhere:
"The accident caused the release of radioactivity into the atmosphere."
Cambridge uses the here, so I would say the second form is more correct.
I (a native speaker) would also definitely go with the second form. It feels more correct, and the sentence is easier to read too. Or alternatively:
Infant crying causes stress hormones to be released in both infants and adults.
— that's how I would phrase it if I wrote the sentence myself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting 'ResultSet is closed' when running query second time
I'm trying to pass a sql query but i am getting "java.sql.SQLException: Operation not allowed after ResultSet closed" . I have gone through other conversation based on same exception in stackoverflow but still I don't understand the problem.
Here is the code:
String query="SELECT candidate,pan from hcl_candidates where jngstat='Joined'";
statement=conn.createStatement();
resultset=statement.executeQuery(query);
while(resultset.next()){
statement.executeUpdate("insert IGNORE into allinvoice (candidate,pan,invdate,client) select candidate,pan,CURDATE(),'HCL' from hcl_candidates where jngstat='Joined'");
}
}
//catch block
finally
{
try
{
if(statement!=null)
{
statement.close();
}
if(conn!=null){
conn.close();
}
if(resultset!=null){
resultset.close();
}
}
// catch block
}
here is error:
java.sql.SQLException: Operation not allowed after ResultSet closed
//So on
A:
Re-executing the Statement closes the prior result set.
It's hard to understand what you think you're doing here, executing a statement in a loop that doesn't rely on anything that the loop changes.
NB An SQLException can mean a lot of things besides 'unable to connect'.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are not all my sites shown on the Stack Exchange reputation graph?
Possible Duplicate:
Stack Exchange reputation graph missing
As you can see on my Stack Exchange reputation graph, only the reputation from Stack Overflow is shown, yet I have several linked accounts in the Stack Exchange network.
For other users, I see all their sites are mentioned, even if you have one site with a lot of reputation, and others with only a few points.
Can anyone tell me why this is?
A:
Only those accounts with over 200 reputation are shown in the graph. Area 51 reputation is not shown at all.
The 200 rep requirement also holds true for a site to be shown on your "combined flair" feature (see http://[any SE site you have linked accounts on]/users/<youruseridnumber>/<yourusername>?tab=flair or the Flair tab of your profile)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spark installation - warning and error when running spark-shell command
I have Hadoop 2.7.7, Java JDK 13, and Spark 2.4.4. Hadoop is set-up and running correctly. I have defined my paths correctly, and double-checked them. When I run spark-shell command I get the following list of warnings and errors:
What's causing this?
A:
Using JDK 8 instead of JDK 13 solved the problem without changing anything else, including the path configurations. Spark just does not seem to like any version of Java past version 8.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQLite : insert multiple value (select from) with insert specified value
i'm trying to make sqlite query that can insert multiple values , here's my query that i try :
insert into table1(idy_table1,idx_table1)
values ('1', //specified value insert to idy_table1
(select id_table2 from table2)) //insert value from select id_table2
i'm having some trouble, it just only insert one value,
and my question is how to make a proper query? so i can make it work.
A:
The VALUES clause always adds one row.
(Except when you're using multiple tuples, but this does not work with queries.)
The easiest way to add multiple rows from a query is to use the SELECT form of the INSERT statement:
INSERT INTO Table1(idy_table1, idx_table1)
SELECT '1', id_table2 FROM table2;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using textfile for user input and save with button android studio
Okay, I have a viewpager/slider that for each different page it has some type of information on it. The one I am having problems with is the Message tab. This tab is suppose to let the user input a message and then save it with the button that is pushed. (this information will be later used to send in an text message) But when the button is pushed it crashes and then loops back into the program, starting it over again.
I don't know if this is right but at first I put that button method in the main activity.java and it did not work at all. Then I made a new activity to hold that method and it worked up until the button was clicked. Below is the code and the log.
message activity
package akh.senpro;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
public class MainMenu_Message extends Fragment {
View rootView;
int count = 0;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_main_menu__message, container, false);
//TextView text = (TextView) rootView.findViewById(R.id.text_message);
//text.setText("Message");
return rootView;
}
}
message xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" "
android:id="@+id/text_message"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Enter your emergency message below"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#A4C639" />
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:gravity="top"
android:background="#CCCCCC"
android:ems="10"
android:layout_weight="0.29"
android:inputType="textMultiLine"
>
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="20dp"
android:background="#0099FF"
android:text="save"
android:textColor="#FFFFFF"
android:layout_gravity="right"
android:nestedScrollingEnabled="false"
android:onClick="buttonClicked" />
</LinearLayout>
the new activity that holds the button
package akh.senpro;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FrmActivityMessage extends Activity {
Button mButton;
EditText mEdit;
TextView mText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu__message);
}
public void buttonClicked(View v){
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mEdit = (EditText)findViewById(R.id.editText1);
mText = (TextView)findViewById(R.id.textView1);
mText.setText("Thank you "+mEdit.getText().toString()+"!");
}
});
}
}
new activity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainMenu_Message"
android:onClick="buttonClicked"
android:clickable="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/Save"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="185dp"
android:clickable="true"
android:onClick="buttonClicked" />
</RelativeLayout>
the log
04-13 18:07:25.574 2812-2827/akh.senpro D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-13 18:07:25.582 2812-2812/akh.senpro D/﹕ HostConnection::get() New Host Connection established 0xb3eb3e80, tid 2812
04-13 18:07:25.641 2812-2812/akh.senpro D/Atlas﹕ Validating map...
04-13 18:07:25.939 2812-2824/akh.senpro I/art﹕ Background sticky concurrent mark sweep GC freed 4494(296KB) AllocSpace objects, 0(0B) LOS objects, 34% free, 731KB/1117KB, paused 2.485ms total 166.251ms
04-13 18:07:25.981 2812-2827/akh.senpro D/﹕ HostConnection::get() New Host Connection established 0xb3eb3590, tid 2827
04-13 18:07:26.039 2812-2827/akh.senpro I/OpenGLRenderer﹕ Initialized EGL, version 1.4
04-13 18:07:26.172 2812-2827/akh.senpro D/OpenGLRenderer﹕ Enabling debug mode 0
04-13 18:07:26.223 2812-2827/akh.senpro W/EGL_emulation﹕ eglSurfaceAttrib not implemented
04-13 18:07:26.223 2812-2827/akh.senpro W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3f9b320, error=EGL_SUCCESS
04-13 18:07:26.522 2812-2812/akh.senpro I/Choreographer﹕ Skipped 40 frames! The application may be doing too much work on its main thread.
04-13 18:07:29.519 2812-2827/akh.senpro W/EGL_emulation﹕ eglSurfaceAttrib not implemented
04-13 18:07:29.519 2812-2827/akh.senpro W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5112180, error=EGL_SUCCESS
04-13 18:07:56.778 2812-2812/akh.senpro D/AndroidRuntime﹕ Shutting down VM
04-13 18:07:56.779 2812-2812/akh.senpro E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: akh.senpro, PID: 2812
java.lang.IllegalStateException: Could not find a method buttonClicked(View) in the activity class akh.senpro.MainActivity2Activity for onClick handler on view class android.widget.Button with id 'button1'
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NoSuchMethodException: buttonClicked [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:4000)
at android.view.View.performClick(View.java:4780)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
04-13 18:21:44.539 3005-3005/akh.senpro I/Process﹕ Sending signal. PID: 3005 SIG: 9
04-13 18:21:44.945 3030-3045/akh.senpro D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-13 18:21:44.950 3030-3030/akh.senpro D/﹕ HostConnection::get() New Host Connection established 0xb3eb3ed0, tid 3030
04-13 18:21:44.956 3030-3030/akh.senpro D/Atlas﹕ Validating map...
04-13 18:21:45.046 3030-3045/akh.senpro D/﹕ HostConnection::get() New Host Connection established 0xb3eb36e0, tid 3045
04-13 18:21:45.074 3030-3045/akh.senpro I/OpenGLRenderer﹕ Initialized EGL, version 1.4
04-13 18:21:45.121 3030-3045/akh.senpro D/OpenGLRenderer﹕ Enabling debug mode 0
04-13 18:21:45.154 3030-3045/akh.senpro W/EGL_emulation﹕ eglSurfaceAttrib not implemented
04-13 18:21:45.154 3030-3045/akh.senpro W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3fda3e0, error=EGL_SUCCESS
A:
FIrst all Sir, your Error is this NoSuchMethodException the specified method could not be found in your activity class MainActivity2Activity.
you have to know that mButton.setOnClickListener() is the same as public void buttonClicked(View v) so you do not need to do
public void buttonClicked(View v){
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mEdit = (EditText)findViewById(R.id.editText1);
mText = (TextView)findViewById(R.id.textView1);
mText.setText("Thank you "+mEdit.getText().toString()+"!");
}
});
}
also if you have Activty A that has xml A is its View content then everything declared in xml A is handled by Activity A so your app is crashing because you have declared android:onClick="buttonClicked" in your xml that is probably being handled by MainActivity2Activity and that activity has no method declared as such. if you want your Fragment class to handle the onclick then go the traditional way mButton.setOnClickListener(//new onclick listener); and put the codes there
second of all please initialise your variables in onStart() or onCreate() instead of initialising them when you click the button.
hope am lucid enough for you
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++: Inheritance and overload resolution
I am reading a C++ puzzle here: http://gotw.ca/gotw/005.htm
I did not understand his explanation on static vs dynamic overload resolution (or default paramaters), so I tried to distill the issue and write some tests myself:
class Base {
public:
virtual void foo() {cout << "base/no parameters" << endl;}
virtual void foo(int a) {cout << "base/int" << endl;}
};
class Derived : public Base {
public:
void foo() {cout << "derived/no parameters" << endl;}
void foo(double a) {cout << "derived/int" << endl;}
};
int main() {
Base* ptr = new Derived;
ptr->foo();
ptr->foo(1.0);
}
The output is:
derived/no parameters
base/int
How come in the call to foo(), C++ seems to recognize that it is pointing to a Derived but in the call foo(1.0), C++ does not see void foo(double a) function in the Derived class?
In my mind there are competing ideas, that C++ has polymorphism, which explains the first call, but that overload resolution is done at compile-time, which explains the second call.
A:
This is classical example for Function Hiding.
A function in dervied class overriddes the Base class function if and only if:
virtual keyword is present atleast on the Base class function.
The function in Derived class has exact same signature as the Base class function.
The second rule has an exception where Covariant return types are allowed.
Given the above two rules:
The no parameter foo() function in derived class overiddes the Base class foo() and hence dynamic dispatch works for it as you expected.
The version of foo(double) with one parameter does not override the Base class foo(int) function it merely Hides it. Since there is no overidding there is no dynamic dispatch, the compiler merely calls the foo(int) function it finds in the scope of the Base class.
A:
C++ does not see void foo(double a) function in the Derived class?
C++ does see the function, but it's not associated with Base::foo's virtualness due to function signature difference:
virtual void Base::foo(int); // 'Base' signature
void Derived::foo(double); // 'Derived' signature
So here there are 2 important facts for Derived::foo(double):
doesn't relate (override) to Base::foo(int)
not a virtual method (even making it virtual doesn't help)
1st point is more important, because when you call
// 'ptr' refers 'Base' method signature; so 'double' implicitly converts to 'int'
ptr->foo(1.0);
Base pointer is used. In the vtable list it has only one entry of Base::foo(int). And thus it's called.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Consume Rails web service through a Rails application
There seem to be a few alternatives for Rails web services. Namely ActiveResource, HTTParty and Nokogiri
Is there a clear winner between these 3 (or others) for getting the job done? The requirements are basic i.e. do a POST without requiring any authentication.
I should mention that I am referring to Rails 3 applications, both at the consumer and the server ends. I know it is a rather general question and that there are plenty of posts out there but there does not seem to be a clear trend as to which one serves simple needs best (gut feeling says go for ActiveResource since it is part of the framework).
A:
If it's a RESTful api (which modern rails app's apis should be), ActiveResource will be by far the simplest to use and will require very little configuration to get running, plus, because it makes the api behave as if it's just another model, it keeps your app's code cleaner and simpler.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android application configuration
Where should I store my Android application's configuration settings?
Coming from the .NET world I was expecting something like a .config file. Do I create a file under res/values, and use that?
A:
There is no res/assets. There are assets/ and res/raw/ for arbitrary files, and res/xml/ for arbitrary XML files. However, all of those are packaged as part of the APK and are not modifiable at runtime.
Take a look at SharedPreferences and the PreferenceScreen system for collecting them from users, if these are user-selected configuration settings.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What can be a faster implementation of trie for the following use case?
I am trying to solve the problem, essentially we need to find all words from dictionary which have the given prefix in lexicographic order.
I am using Trie data structure for the task but my solution just times out on the judge , what can be a more efficient/faster way to solve this problem?
My current implementation is
class trie{
node root=new node();
class node{
node child[]=new node[26];
boolean is_leaf=false;
}
public void add(char c[])
{
node root=this.root;
int pos=0,c1=0;
while(pos<c.length)
{
c1=c[pos]-'a';
if(root.child[c1]==null)
{
root.child[c1]=new node();
}
root=root.child[c1];
pos++;
}
root.is_leaf=true;
}
public ArrayList<String> search(String s)
{
char c[]=s.toCharArray();
node root=this.root;
int pos=0,c1=0;
while(pos<c.length)
{
c1=c[pos]-'a';
if(root.child[c1]==null)
{
root.child[c1]=new node();
}
root=root.child[c1];
pos++;
}
ArrayList<String> ans=new ArrayList<>();
build_recursive(root,s,new StringBuilder(),ans);
return ans;
}
public void build_recursive(node root,String prefix,StringBuilder cur, ArrayList<String> ans)
{
if(root.is_leaf&&cur.length()!=0)
{
String s=prefix+cur.toString();
ans.add(s);
}
for(int i=0;i<26;i++)
{
if(root.child[i]!=null)
{
char c=(char) (i+'a');
cur.append(c);
build_recursive(root.child[i], prefix, cur, ans);
cur.deleteCharAt(cur.length()-1);
}
}
}
}
The function Search returns the sorted list of all words that share the given prefix.
Also is there a better data structure i could use for this?
A:
Tries are great at finding a substring of another string. However, you are searching for words in a dictionary - substring matching is not really necessary. Also, once you find the first word with the prefix, the next word, if it exists, will be right next to it. No complex search required!
Tries also carry a lot of overhead from being built out of nodes, which then need to be referenced with pointers (= extra space requirements). Pointers are slow. In C++, iterating linked lists can be 20x slower than iterating arrays, unless the nodes are all nicely ordered.
This problem can, very probably, be solved via
reading all words into an ArrayList of String: O(n), with n = words
sorting the ArrayList: O(n log n)
and for each prefix query,
using binary search to find the 1st match for the prefix: O(log n), and it is already implemented in the standard library
returning consecutive elements that match until matches are exhausted: O(m), m = number of matches
This is faster than Tries on theoretical complexity, and and a lot faster due to memory layout - messing with pointers, when you don't need to do so, is expensive.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors
I have enabled databinding, but while I execute the code I get this error.
error
e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
I created a fragment class and XML for that class.
Im able to import datbindingutil class.
I have done rebuilt/ sync with gradle files/ invalidate cache and restart, nothing worked.
xml
<layout>
<!--suppress AndroidUnknownAttribute -->
<data class=".databinding.ProfileFragmentBinding">
<variable
name="user"
type="com.sample.sample.user.User" />
<variable
name="vm"
type="com.sample.sample.user.UserViewModel" />
<variable
name="handler"
type="com.sample.sample.user.profile.ProfileFragment" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profileIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/medium"
android:layout_marginTop="@dimen/medium"
android:contentDescription="@null"
android:src="@mipmap/ic_launcher_round"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:url="@{user.avatarUrl}" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="@+id/profileIV"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/profileIV">
<TextView
android:id="@+id/profileNameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/myriad_pro_semibold"
android:text="@{user.name}"
android:textColor="@color/black_transparent_de"
android:textSize="@dimen/text_regular"
tools:text="NAME" />
<TextView
android:id="@+id/badgeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="@font/myriad_pro_semibold"
android:text="@{user.badge}"
android:textColor="@color/grey_000000"
android:textSize="@dimen/text_regular"
tools:text="Superman" />
<TextView
android:id="@+id/profile_Label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="@font/roboto_bold"
android:text="@{user.badge}"
android:textColor="@color/green_39b54a"
android:textSize="@dimen/text_small"
tools:text="farmer_v1" />
</LinearLayout>
<ImageView
android:id="@+id/badgeIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/medium"
android:layout_marginTop="@dimen/medium"
android:contentDescription="@null"
android:src="@mipmap/ic_launcher"
app:error="@{@drawable/ic_profile_default_grey_24dp}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:placeholder="@{@drawable/ic_profile_default_grey_24dp}"
app:url="@{user.badgeUrl}" />
<ImageView
android:id="@+id/locationPinIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/medium"
android:contentDescription="@null"
android:src="@drawable/ic_location_pin"
app:layout_constraintStart_toStartOf="@+id/profileIV"
app:layout_constraintTop_toBottomOf="@+id/profileIV" />
<TextView
android:id="@+id/profileAddressTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/narrow"
android:fontFamily="@font/roboto"
android:textColor="@color/grey_000000"
app:layout_constraintBottom_toBottomOf="@+id/locationPinIV"
app:layout_constraintLeft_toRightOf="@+id/locationPinIV"
app:layout_constraintTop_toTopOf="@+id/locationPinIV"
tools:text="bangalore, Karnataka" />
<ImageView
android:id="@+id/dobIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/standard"
android:layout_marginTop="@dimen/medium"
android:contentDescription="@null"
android:src="@drawable/ic_dob"
app:layout_constraintLeft_toRightOf="@+id/profileAddressTV"
app:layout_constraintTop_toBottomOf="@+id/profileIV" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/narrow"
android:fontFamily="@font/roboto"
android:textColor="@color/grey_000000"
app:layout_constraintBottom_toBottomOf="@+id/locationPinIV"
app:layout_constraintLeft_toRightOf="@+id/dobIV"
app:layout_constraintTop_toTopOf="@+id/locationPinIV"
tools:text="born on 01/01/2000" />
<TextView
android:id="@+id/activityLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/big"
android:fontFamily="@font/myriad_pro_semibold"
android:text="@string/activities"
android:textColor="@color/black_transparent_de"
android:textSize="@dimen/text_regular"
app:layout_constraintStart_toStartOf="@+id/profileIV"
app:layout_constraintTop_toBottomOf="@+id/locationPinIV" />
<View
android:id="@+id/dividerV"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginEnd="@dimen/small"
android:layout_marginStart="@dimen/small"
android:layout_marginTop="@dimen/regular"
android:background="@color/grey_000000"
app:layout_constraintTop_toBottomOf="@+id/activityLabel" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@+id/dividerV">
<!--<com.google.android.material.tabs.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:pager="@{(pager)}"
app:tabGravity="fill"
app:tabIndicatorColor="@color/black"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/black"
app:tabTextAppearance="@style/CustomTextTab"
app:tabTextColor="#b4ffffff" />
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tablayout"
app:handler="@{handler}"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />-->
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
class
class ProfileFragment : Fragment() {
@Inject
lateinit var mFactory: ViewModelProvider.Factory
private lateinit var mBinding: ProfileFragmentBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_profile, container, false);
return mBinding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val vm: UserViewModel = getViewModel(mFactory)
mBinding.vm = vm
//mBinding.handler = this
//mBinding.setLifecycleOwner(this)
}
/*@BindingAdapter("bind:handler")
fun bindViewPagerAdapter(view: ViewPager, activity: MainActivity) {
val adapter = ProfilePagerAdapter(view.context, activity.supportFragmentManager)
view.adapter = adapter
}
@BindingAdapter("bind:pager")
fun bindViewPagerTabs(view: TabLayout, pagerView: ViewPager) {
view.setupWithViewPager(pagerView, true)
}*/
}
A:
in my case I was able to find it when the mouse was hovering that line in the build output, as shown here:
without hover:
with hover:
it's really a shame how they show the error, for the simplest error ever, I was trying 10 different solutions as well invalidating the cache and ...
UPDATE:
you can also click here :
and you'll get something like this:
which is very detailed information about the error, I was missing this button in 7 years of Android Development :D
A:
Run ./gradlew build --stacktrace to check the details, which will tell you where the issue happens, something like:
e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
Could not find accessor xx
file:xxx/app/src/main/res/layout/fragment_xxxx.xml Line:108
Sometimes if you changed the property name, especially when changed by refactor => rename, the property name won't be changed in xml automatically.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do query subdocument from mongoid using Ruby?
I have this document which I only want part of it. But I'm not sure how to do this in Mongoid query.
{
"_id": {
"$oid": "5297d6773865640002000000"
},
"saved_tweets": [
{
"_id": {
"$oid": "52b0856b6535380002000000"
},
"saved_id": "123456",
"tweet_ids": [
"1",
"2"
]
},
{
"_id": {
"$oid": "52b0856b6535380002000001"
},
"saved_id": "78901",
"tweet_ids": [
"3",
"4"
]
}
]}
What I want is all the tweet_ids according to the saved_id. This is what I'm doing right now which I think it's very ineffective.
existing_user = User.find_by(:social_id => social_id)
existing_user.saved_tweets.each do |saved_tweet|
if saved_id == saved_tweet.saved_id
@saved_tweet_ids = saved_tweet.tweet_ids
end
end
A:
did you try something like that?
user.saved_tweets.where(saved_id: user.saved_id).map(&:tweet_ids)
?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create multiple x~y plots for differing (x) and (y) variables?
My data looks like this
data <- structure(list(code = 1:12, outcome1 = c(75L, 76L, 77L, 78L,
80L, 82L, 85L, 84L, 78L, 84L, 84L, 75L), outcome2 = c(50L, 55L,
54L, 52L, 56L, 58L, 59L, 54L, 52L, 56L, 56L, 57L), response1 = c(1500L,
1800L, 1789L, 1200L, 1400L, 1900L, 1800L, 1100L, 1450L, 1750L,
1770L, 1000L), response2 = c(100L, 111L, 120L, 140L, 144L, 156L,
147L, 189L, 165L, 154L, 132L, 171L)), class = "data.frame", row.names = c(NA,
-12L))
I have numerous outcomes = 8 and response variables = 22.
I would like to create a series of regression plots for all outcome * response combination. Is there a fast and easy way to do this?
For example: Outcome1 * Response1, Outcome1 * Response 2, Outcome2 * Response1 and so on.
This is an example code for creating one such outcome1 by response1 graph.
ggplot(data = data, aes(x = outcome1, y = response1)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
Edit: I have thought about faceting but this may not work here because, for each outcome(x) the various responses(y) are in different units. So y axis scales are not comparable across different (y).
A:
Always transform your data to long format before feeding into ggplot. We can then use facet_grid to create the plots:
library(ggplot2)
library(dplyr)
library(tidyr)
data %>%
gather(var1, value1, outcome1:outcome2) %>%
gather(var2, value2, response1:response2) %>%
ggplot(aes(x = value1, y = value2)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE) +
facet_grid(var2 ~ var1, scales = "free", switch = "both",
labeller = as_labeller(c(response1 = "response1 (mm)",
response2 = "response2 (kg)",
outcome1 = "outcome1 (index)",
outcome2 = "outcome2 (index)"))) +
labs(title = "Regression Plot Matrix", x = NULL, y = NULL) +
theme_bw() +
theme(strip.placement = "outside",
strip.background = element_blank())
Notes:
Since the variables can have different scales, we use scale = "free" in facet_grid to allow each axis to scale freely.
switch = "both" changes the facet strip labels to the other side
labeller allows us to supply a named vector and change the strip labels as desired
strip.placement = "outside" sets the strip labels outside of the axis ticks, while strip.background = element_blank() removes the grey strip label background (inspired by this answer by aosmith)
labs(..., x = NULL, y = NULL) removes the default axis labels, effectively treating the modified facet strip labels as axis labels
Output:
> data %>%
+ gather(var1, value1, outcome1:outcome2) %>%
+ gather(var2, value2, response1:response2)
code var1 value1 var2 value2
1 1 outcome1 75 response1 1500
2 2 outcome1 76 response1 1800
3 3 outcome1 77 response1 1789
4 4 outcome1 78 response1 1200
5 5 outcome1 80 response1 1400
6 6 outcome1 82 response1 1900
7 7 outcome1 85 response1 1800
8 8 outcome1 84 response1 1100
9 9 outcome1 78 response1 1450
10 10 outcome1 84 response1 1750
11 11 outcome1 84 response1 1770
12 12 outcome1 75 response1 1000
13 1 outcome2 50 response1 1500
14 2 outcome2 55 response1 1800
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to find the date collection between two dates in SQL Server for mail delinquency?
I have to get the date collection of every month between two dates. I have no more idea in detail for SQL Server.
Example 1:
If my StartDate is '01/20/2017' (MM/dd/yyyy) and EndDate is '12/20/2017' (MM/dd/yyyy) than the expected result should be as given below.
2017-01-20
2017-02-20
2017-03-20
2017-04-20
2017-05-20
2017-06-20
2017-07-20
2017-08-20
2017-09-20
2017-10-20
2017-11-20
2017-12-20
Example 2:
If my StartDate is '01/30/2017' (MM/dd/yyyy) and EndDate is '12/20/2017' (MM/dd/yyyy) than the expected result should be as given below.
In this example StartDate is '01/30/2017' therefor in February month there is no 30th date in calandar so I need last date of this month. If any leap year will come in the range of these given dates than 29th date will be in result set.
Expected result
2017-01-30
2017-02-28
2017-03-30
2017-04-30
2017-05-30
2017-06-30
2017-07-30
2017-08-30
2017-09-30
2017-10-30
2017-11-30
Thanks in advance.
A:
Please try the below solution. Just set the MinDate and MaxDate as per your requirement. Also please check for the February month date in case of MinDate will be 30 or 31.
DECLARE @MinDate datetime,
@MaxDate datetime
SELECT @MinDate = '01/30/2017',
@MaxDate = '12/17/2020'
DECLARE @FilteredDate DATETIME = GETDATE();
;WITH CTE AS
(
SELECT TOP (DATEDIFF(MONTH, @MinDate, @MaxDate) + 1) DATEADD(MONTH, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate) AS CurrentDate
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
)
SELECT * FROM CTE
WHERE CurrentDate > CONVERT(DATE, @FilteredDate) AND
CurrentDate <= CONVERT(DATE, @MaxDate)
ORDER BY CurrentDate ASC
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using Motor Oil as a Transformer Oil Substitute
I need a rather large volume of oil to insulate a few 15 kV wires/coils. Unfortunately, the volume of oil required puts transformer oil outside of my price range.
I've noticed that others have discussed motor oil as a fairly economical substitute that works effectively around this range.
Are there any types of motor oils and/or materials inside of mineral oil that i should be taking into account when selecting a brand of motor oil?
As some background, the materials I'm insulating are made of copper with a few jagged edges. There're also a few little electrolytic caps and inductors.
A:
Not too good because:
Viscosity of motor oil is higher than transformer oil - so there will be risk of having some unfilled areas (filled by air).
Motor oils can have some less or more conductive add-ons, like graphite, chemical compounds of lithium, molybdenum and so on.
Better choice is using liquid paraffin.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
rake test prepare: NoMethodError: undefined method `[]' for nil:NilClass
I always get the following error when I run rake db:test:prepare. what can cause this? rake db:create works fine.
Adam-MacBook-Pro:katy adam$ bundle exec rake db:test:prepare
rake aborted!
NoMethodError: undefined method `[]' for nil:NilClass
/Users/adam/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.4/lib/active_record/tasks/database_tasks.rb:163:in `purge'
/Users/adam/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.4/lib/active_record/railties/databases.rake:356:in `block (3 levels) in <top (required)>'
/Users/adam/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.4/lib/active_record/railties/databases.rake:362:in `block (3 levels) in <top (required)>'
/Users/adam/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `eval'
/Users/adam/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `<main>'
database.yml
<%= Rails.env %>:
adapter: mysql2
encoding: utf8
pool: <%= ENV['DB_POOL'] || 5 %>
username: <%= ENV['DB_USER'] || 'root' %>
password: <%= ENV['DB_PASSWORD'] || nil %>
timeout: <%= ENV['DB_TIMEOUT'] || 5000 %>
host: <%= ENV['DB_HOST'] || 'localhost' %>
port: <%= ENV['DB_PORT'] || 3306 %>
database: <%= ENV['DB_NAME'] || "website#{Rails.env}" %>
A:
Try specifying the RAILS_ENV when you run the rake command:
RAILS_ENV=test bundle exec rake db:test:prepare
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Changing Coarse Iron to Iron?
Note I am using the Masterwork Mod, looked through the manual didn't see anything about coarse iron. How do I change coarse Iron to normal Iron with the Masterwork Mod?
A:
Coarse Iron has the following uses in Masterwork 1.9.5:
In a crucible, use "cold hammer coarse iron" to turn the ore into coarse iron bars
In the same crucible (with additional fuel) or a magma crucible, use "refine coarse iron into iron" to turn coarse iron bars into iron bars.
It, along with the both crucibles, is being removed in Masterwork 2.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rebinding the DataContext of a Window in WPF
I have a Window in WPF for which i have defined a dataContext. I have a save button an on clicking the save button i am adding the updated datacontext to a collection and define a new instance of the datacontext object for the current window. Now how do i update the window with the new DataContext.
I tried this
this.DataContext=insClassA;//Initially it is set
//Later on some event i'm updating the NewAttributeProperty
insClassA.NewAttribute = new NewAttribute();
but the UIFields still hold the previous instance's values/
Thanks.
A:
This should take place automatically. If you set a new instance of your object to the DataContext-property of you window, all bound items should refresh automatically.
UPDATE:
Based on your edit, I assume that your object does not implement INotifyPropertyChanged and ist not a DependencyObject or the failing property is not a DependencyProperty. The problem seems to me not about the DataContext.
Your object must inform the environment, that the property has been changed. Normaly, BOs do this with the PropertyChanged-event. Search for WPF DataBinding and INotifyPropertyChanged and you will find a lot of information to this topic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
disable submit only if valid
im using jquery with asp.net mvc.
Im doing something like this so that the submit button becomes disabled when clicked.
but if there are validation errors i dont want it to be disabled.
$('form').submit(function () {
if ($('form').valid()) {
$('input[type=submit]', this).attr('disabled', 'disabled');
}
});
this makes it disabled, but even if there are validation errors.
whats wrong?
A:
EDIT: i'll try again after my first screw up :P
$('form').submit(function () {
if ($('form').valid()) {
$('input[type=submit]', this).attr('disabled', 'disabled');
}
});
Maybe there are other forms on the page, and it's validating the wrong one?
$('form').submit(function () {
if ($(this).valid()) {
$(this).find('input[type=submit]').attr('disabled', 'disabled');
}
});
oh and did you $('form').validate() to enable validation (which I would guess is called automatically by MVC if you're using MVC's validation, but I'm not 100% sure about that)?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Почему выражение возвращает False?
В моём понимании == any([]) возвращает True, когда сопоставляемая переменная равна хотя бы чему-то из словаря. Но почему-то переменная а со значением "14" (то есть и а[-2:] == "14"), сопоставляемая со списком, в итоге выдаёт False.
Почему и как добиться такой проверки, чтобы если переменная равнялась хоть чему-то из списка, она выдавала True?
a = input()
print(a[-2:] == any(["11", "14", "13", "12"]))
A:
Ответ: потому что "14" != True !
из документации:
Return True if any element of the iterable is true
Все непустые строки при приведении к типу данных bool - вернут True:
In [2]: bool("aaa")
Out[2]: True
In [3]: bool("")
Out[3]: False
Как следствие вы сравниваете a[-2:] с True.
In [10]: any(["11", "14", "13", "12"])
Out[10]: True
In [11]: a = "14"
In [12]: a == True
Out[12]: False
In [13]: "14" != True
Out[13]: True
Как проверить входит ли значение в список:
In [4]: "14" in ["11", "14", "13", "12"]
Out[4]: True
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Plot coordinates on map
I am trying to plot my coordinates using R. I have tried already to follow different post (R: Plot grouped coordinates on world map ; Plotting coordinates of multiple points at google map in R) but I am not having much success with my data.
I am trying to achieve a flat map of the world with my gps coordinate as colored dots (each area a specific color):
area lat long
Agullhas -38,31 40,96
Polar -57,59 76,51
Tasmanian -39,47 108,93
library(RgoogleMaps)
lat <- c(-38.31, -35.50) #define our map's ylim
lon <- c(40.96,37.50) #define our map's xlim
center = c(mean(lat), mean(lon)) #tell what point to center on
zoom <- 2 #zoom: 1 = furthest out (entire globe), larger numbers = closer in
terrmap <- GetMap(center=center, zoom=zoom, maptype= "satallite", destfile = "satallite.png")
problem that now I don't know how to add my points and I will like one color for each region.
Could anyone help me going forward with it?
the other option I have tried is :
library(maps)
library(mapdata)
library(maptools)
map(database= "world", ylim=c(-38.31, -35.5), xlim=c(40.96, 37.5), col="grey80", fill=TRUE, projection="gilbert", orientation= c(90,0,225))
lon <- c(-38.31, -35.5) #fake longitude vector
lat <- c(40.96, 37.5) #fake latitude vector
coord <- mapproject(lon, lat, proj="gilbert", orientation=c(90, 0, 225)) #convert points to projected lat/long
points(coord, pch=20, cex=1.2, col="red") #plot converted points
but the coordinates ends in a wrong position and I am not sure why
Hope someone can help
A:
As an alternative to RgoogleMaps, you can also use the combination ggplot2 with ggmap.
With this code:
# loading the required packages
library(ggplot2)
library(ggmap)
# creating a sample data.frame with your lat/lon points
lon <- c(-38.31,-35.5)
lat <- c(40.96, 37.5)
df <- as.data.frame(cbind(lon,lat))
# getting the map
mapgilbert <- get_map(location = c(lon = mean(df$lon), lat = mean(df$lat)), zoom = 4,
maptype = "satellite", scale = 2)
# plotting the map with some points on it
ggmap(mapgilbert) +
geom_point(data = df, aes(x = lon, y = lat, fill = "red", alpha = 0.8), size = 5, shape = 21) +
guides(fill=FALSE, alpha=FALSE, size=FALSE)
you get this result:
A:
Another option is using the leaflet package (as suggested here). Unlike Google Maps it does not require any API key.
install.packages(c("leaflet", "sp"))
library(sp)
library(leaflet)
df <- data.frame(longitude = runif(10, -97.365268, -97.356546),
latitude = runif(10, 32.706071, 32.712210))
coordinates(df) <- ~longitude+latitude
leaflet(df) %>% addMarkers() %>% addTiles()
A:
An other alternative, is the plotGoogleMaps package which allows to plot in a navigator, allowing to zoom in and out etc. You can then make a screenshot of your picture to save it (though remember google maps are legally supposed to be used for the internet).
library("plotGoogleMaps")
lat <- c(-38.31, -35.50) #define our map's ylim
lon <- c(40.96,37.50) #define our map's xlim
# make your coordinates a data frame
coords <- as.data.frame(cbind(lon=lon,lat=lat))
# make it a spatial object by defining its coordinates in a reference system
coordinates(coords) <- ~lat+lon
# you also need a reference system, the following should be a fine default
proj4string(coords) <- CRS("+init=epsg:4326")
# Note: it is a short for:
CRS("+init=epsg:4326")
> CRS arguments:
> +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
# then just plot
a <- plotGoogleMaps(coords)
# here `a <-` avoids that you get flooded by the html version of what you plot
And you get :
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it safe to construct Swing/AWT widgets NOT on the Event Dispatch Thread?
I've been integrating the Substance look and feel into my application and ran into several problems regarding it's internal EDT (Event Dispatch Thread) checking routines. Substance absolutely refuses to construct UI classes outside of the EDT. I've done plenty of Swing/AWT and I know most of the rules regarding the EDT. I use SwingWorker, SwingUtilties.invokeLater to modify components. I always though that components could be CONSTRUCTED outside of the EDT, but must be realized and manipulated on the EDT. In other words, you can construct and setup defaults in the background but the call to pack/setVisible must be EDT as well as any subsequent calls to manipulate the component.
The reason I ask is that I have a particularly "beefy" window to construct, involving many widgets, state, and resources (lots of icons). Previously, I constructed the window on the background method of a SwingWorker and made the window visible in the done method. Never had a single problem. Upon switching to Substance, the internal EDT checking bites me.
I've been able to refactor code to get around this. I can construct on the EDT which isn't a good solution since the entire application will block. I can also refactor even more and try my best to load all of the extra resources outside of the EDT.
Wrapping it up ... Is it safe to construct Swing/AWT widgets NOT on the Event Dispatch Thread?
A:
Sun has changed the rules in 2004 -- before, you were allowed to create the components outside the EDT and only had to move into the EDT once the component had been realized.
The new rule now reads:
To avoid the possibility of deadlock,
you must take extreme care that Swing
components and models are created,
modified, and queried only from the
event-dispatching thread.
this blog post of mine gives more details, including links to other related articles. note that all official Sun examples have been rewritten and are very strict about this.
historically, it probably was the increasing availability of multi-core computers as desktop machines that motivated the re-formulation of the rule -- threading issues became more and more apparent on the client stack, and by being very strict on EDT guidelines, a lot of them can be prevented from the start.
A:
No.
Simple reason is that even the EDT likes to deadlock in some rare cases and in general it's easy to deadlock the UI when using Swing (or so I've been told). I suggest you read these three articles from Kirill's (the Substance dev) blog:
New article on Swing EDT violations
Unwritten rule of working with Swing’s EDT
Stricter checks on EDT violations in Substance
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Not in scope: data constructor ‘Cons’
I'm having trouble with the following Data Type and Function:
module Lib
(intListProd) where
data IntList = Empty
| Cons Int IntList
deriving Show
intListProd :: IntList -> Int
intListProd Empty = 1
intListProd (Cons x xs) = x * intListProd xs
But if I try to use it within ghci, I get errors about 'Cons' and 'Empty' not being in the scope:
*Main Lib> intListProd (Cons 3 (Cons 2 (Cons 4 Empty)))
<interactive>:19:14: Not in scope: data constructor ‘Cons’
<interactive>:19:22: Not in scope: data constructor ‘Cons’
<interactive>:19:30: Not in scope: data constructor ‘Cons’
<interactive>:19:37: Not in scope: data constructor ‘Empty’
I'm using stack, so I use 'stack ghci' to enter the shell.
The code is not my own, I'm trying to follow the examples at the end of chapter 2 in the School of Haskell Introduction to Haskell tutorial by Brent Yorgey.
I've noticed the "Learn you a Haskell" also uses the 'Cons' constructor in the "Recursive Data Types" section. Is 'Cons' something that should be included in GHC that I don't have for some reason?? What about 'Empty'?
A:
module Lib
(intListProd) where
You're not exporting any constructor of IntList. Export them, so that they're available to other modules:
module Lib
(intListProd, IntList(..)) where
-- ^^^^^^^^^^^
|
{
"pile_set_name": "StackExchange"
}
|
Q:
php array to JQuery .live for multiple pairs of values or?
I'm starting over here...
This is generated....
<form name="ratePage">
<input id="service" type="text" value="Ground"><input id="rate" value="" type="text" size="6"><input type="submit" name="BtnAction" value="Select" onclick="SubmitValue();"><br>
<input id="service" type="text" value="3 Day Select"><input id="rate" value="" type="text" size="6"><input type="submit" name="BtnAction" value="Select" onclick="SubmitValue();"><br>
<input id="service" type="text" value="2nd Day Air"><input id="rate" value="" type="text" size="6"><input type="submit" name="BtnAction" value="Select" onclick="SubmitValue();"><br>
<input id="service" type="text" value="2nd Day Air AM"><input id="rate" value="" type="text" size="6"><input type="submit" name="BtnAction" value="Select" onclick="SubmitValue();"><br>
<input id="service" type="text" value="Next Day Air Saver"><input id="rate" value="" type="text" size="6"><input type="submit" name="BtnAction" value="Select" onclick="SubmitValue();"><br>
<input id="service" type="text" value="Next Day Air"><input id="rate" value="" type="text" size="6"><input type="submit" name="BtnAction" value="Select" onclick="SubmitValue();"><br>
<input id="service" type="text" value="Next Day Air (early AM)"><input id="rate" value="" type="text" size="6"><input type="submit" name="BtnAction" value="Select" onclick="SubmitValue();"><br></form>
From this...
<?php
foreach($services as $name=>$value){
$service = $value;
$rate = $myRate->getRate($fromzip, $tozip, $service, $length, $width, $height, $weight);
echo "<input id=\"service\" type=\"text\" value=\"$name\"><input id=\"rate\" value=\"$rate\" type=\"text\" size=\"6\"><input type=\"submit\" name=\"BtnAction\" value=\"Select\" onclick=\"SubmitValue();\"><br>\n";
}
?>
The Output looks like this...
I want to turn this... (this is in the generated forms page)
<script language="javascript">
function SubmitValue(){
opener.document.orderForm.rate.value = document.ratePage.rate.value;
opener.document.orderForm.service.value = document.ratePage.service.value;
self.close();
</script>
Into a Jquery .live function that will copy ONLY the selected values from the selected row.
What would be the best way to do this?
A:
First make each row look like:
<div>
<input type="text" value="abc" class="service">
<input class="rate" value="222" type="text" size="6">
<input type="submit" name="BtnAction" class="submit" value="Select">
</div>
Then you can use
$('.submit').live('click', function(){
var $this = $(this);
opener.document.orderForm.rate.value = $this.siblings(".rate").val();
opener.document.orderForm.service.value = $this.siblings(".service").val();
self.close();
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there such a view in sql-server?
Is there a view that during the transaction is able to show how many records have been processed? I have a transaction in which I am inserting and deleting data from tables. I would like to check the current status of the batching, i.e. how many data from a particular table have been removed or how many records have been inserted into the table at this moment?
Example tran:
BEGIN TRANSACTION x
-- Some stuff
Insert <TMP_MY_TABLE>
-- Some stuff
DELETE <MY_TABLE>
COMMIT TRANSACTION x
SELECT like this :
SELECT * FROM <some system view> WHERE TABLE_NAME = <MY_TABLE>
I am asking for help because I can not find one myself, and that does not mean that it does not exist :)
A:
I found this view :
sys.dm_db_partition_stats
For example :
SELECT OBJECT_NAME(object_id), row_count FROM sys.dm_db_partition_stats
WHERE OBJECT_NAME(object_id) = 'MY_TABLE'
row_count this is what I am looking for
Thank you for trying to help:)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I add an atomic operation to MemoryCache?
I'd like to know if I can implement a method on MemoryCache that removes an item from it and add a new one before any other thread tries to reach it. I can't seem to find anything that would let me control the lock(maybe for a good reason) so I can perform these two operations at once.
A:
If you mean "with the same key", then use the indexer:
cache[key] = value;
If you mean with different keys, then: no
|
{
"pile_set_name": "StackExchange"
}
|
Q:
batch class for opportunity records to send an email that the opportunity closing date is tommorow
global class sendemail implements Database.Batchable <sobject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
String Query;
Query = 'SELECT Name,Id From Opportunities WHERE CloseDate = createddate+1';
return Database.getquerylocator(Query);
}
global void execute(Database.BatchableContext bc, List<Opportunities> opplist) {
for(Opportunities opp :opplist){
opp.CloseDate = 'createddate+1';
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] {'[email protected]'});
email.setSubject('opportunity closed date');
email.setPlainTextBody('Dear user, Your opportunity closed date is tommorow');
emails.add(email);
}
Messaging.sendEmail(emails);
update opplist;
}
global void finish(database.BatchableContext bc){
}
}
A:
You need to declare the date variable and then use it in your query.
Also there are some other mistake in your code.
Instead of Opportunities you need to pass correct api name Opportunity in all places
You don't need to update the close date as it is already tomorrow.
You don't need to declare the Messaging.SingleEmailMessage List
global class sendemail implements Database.Batchable < sobject > {
global Database.QueryLocator start(Database.BatchableContext bc) {
String Query;
Date dt = date.today().addDays(1);
Query = 'SELECT Name,Id From Opportunity WHERE CloseDate =: dt ';
return Database.getquerylocator(Query);
}
global void execute(Database.BatchableContext bc, List < Opportunity > opplist) {
List < Messaging.SingleEmailMessage > emails = new List < Messaging.SingleEmailMessage > ();
for (Opportunity opp: opplist) {
// opp.CloseDate = 'createddate+1';
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] {
'[email protected]'
});
email.setSubject('opportunity closed date');
email.setPlainTextBody('Dear user, Your opportunity '+opp.name+' closed date is tommorow');
emails.add(email);
}
Messaging.sendEmail(emails);
// update opplist;
}
global void finish(database.BatchableContext bc) {}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to verify ecdsa-with-SHA256 signature with PHP?
I have encountered the following issue while developing a secure system:
We receive some data which we have to verify by signature. The signature algorithm is ecdsa-with-SHA256, and openssl_verify() doesn't seem to have an option for that. Already tried searching for standalone PHP libraries like phpseclib - no luck either, ecdsa-with-SHA1 is the best option they seem to offer.
What would be an appropriate solution for that issue? Maybe I've missed some library that implements such functionality?
A:
PHP's openssl_ currently supports ECDSA only with SHA1 digest (reefer to openssl_get_md_methods() output, position [14]). You'll need a workaround for this. From comments of this question (closed as off topic, by the way), but it was focused on bitcoin implementations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In satipatthana, how does mindfulness lead to nirodha?
What is the difference between "cessation" and "nirodha"? How would it be experienced during meditation?
A:
The between cessation and nirodha is "cessation" is an English word and "nirodha" is a Pali word that often does not literally mean "cessation" although often it does.
In meditation, the important "cessations" to be experienced are:
Cessation of craving.
Cessation of attachment.
Cessation of I-making & my-making.
Cessation of suffering.
Cessation of ignorance.
Cessation of ego-birthing, ego-aging & ego-dying.
In summary, all of the above "cessations" amount to the cessation of suffering (dukkha-nirodha).
Therefore, often, when the Pali teachings refer to "consciousness-nirodha"; "nama-rupa-nirodha"; "sense-contact-nirodha" and "feeling-nirodha"; what this means is consciousness, nama-rupa (mind-body), sense contact & feeling are no longer imprisoned by ignorance, craving, egoism & suffering.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I test multi-gesture capabilities of a touchpad?
I bought new laptop and I was told that my touch pad is 'Multi Gesture Touchpad'. I'd like to zoom, scroll with two fingers and perform three finger operations.
How do I test the multi gesture capabilities of my touchpad?
A:
You can enable two-finger scrolling by forcing the scrolling setting:
gconftool-2 --set --type=int /desktop/gnome/peripherals/touchpad/scroll_method 2
If this doesn't work, try with the below script:
xinput --set-prop --type=int --format=32 "SynPS/2 Synaptics TouchPad" "Synaptics Two-Finger Pressure" 10
# Below width 1 finger touch, above width simulate 2 finger touch. - value=pad-pixels
xinput --set-prop --type=int --format=32 "SynPS/2 Synaptics TouchPad" "Synaptics Two-Finger Width" 7
# vertical scrolling, horizontal scrolling - values: 0=disable 1=enable
xinput --set-prop --type=int --format=8 "SynPS/2 Synaptics TouchPad" "Synaptics Two-Finger Scrolling" 1 1
# vertical, horizontal, corner - values: 0=disable 1=enable
xinput --set-prop --type=int --format=8 "SynPS/2 Synaptics TouchPad" "Synaptics Edge Scrolling" 0 0 0
# stabilize 2 finger actions - value=pad-pixels
xinput --set-prop --type=int --format=32 "SynPS/2 Synaptics TouchPad" "Synaptics Jumpy Cursor Threshold" 120
I have added it to my startup applications. If it doesn't seem to work, try adding a sleep 10 at the top of the script.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can i set the output keyPress to the same input field?
I am trying to get the user keypress output and set it to the same input.
However in my input result I get the output twice. For example, if the user presses d I see Dd. How can I solve this?
$(document).ready(function() {
$("#test").keypress(function(e) {
let key = String.fromCharCode(e.keyCode);
let upperCaseKey = (key.toUpperCase())
$("#test").val(upperCaseKey);
$("#test").css("width", "25px")
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text class="myid" id="test" />
A:
<input type=text class="myid" id="test" />
$(".myid").on('keypress', function(evt) {
$(this).val(function (_, val) {
return val + String.fromCharCode(evt.which).toUpperCase();
});
return false;
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
storing characters in char data type C language
I can store string of few length in char data type.
But when it exceeds its capacity what can be the alternative way to store string.
I am using char data type.
void setString(char* inPoints)
{
if (strcmp(mPoints, inPoints)!= ZERO) {
if (mPoints) {
free(mPoints);
}
mPoints = (char*)malloc((strlen(inPoints) + 1) * sizeof(char));
strcpy(mPoints, inPoints);
}
}
A:
You can allocate a new, bigger array and copy the old string into it (and delete the old to prevent memory leaks), appending more characters. Or (if possible) switch to C++ string class, which makes this process easier.
A:
Using strncpy instead of strcpy is normally safer, but here you alloc eachtime the right amount of memory needed to store inPoint into mPoint, so I cant see what's the point. The max length of a string you can store in mPoint is limited by the amount of malloc-able memory.
Add: you can realloc as suggested, and likely you can add a check on the length to avoid realloc-ing if the string is shorter; so mPoint would be able to hold always strings less than the longest string met so far, or equal to:
// somewhere altogether with mPoints
size_t mPointsCurrenStorage = INITVAL;
// e.g. INITVAL is 256, and you pre-malloc-ate mPoints to 256 chars
// ... in the func
size_t cl = strlen(inPoints);
if ( cl >= mPointsCurrentStorage ) {
mPoints = realloc(mPoints, cl+1);
mPointsCurrentStorage = cl+1;
}
strcpy(mPoints, inPoints);
this way the storage grows only...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
rendering without light only texture as they are
I am new to blender and I only want to take pictures of 3d model from the side. I have everthing set up. Camera is looking exactly from the side and set to orthographic.
But either I have a light which leads to surfaces being differently illuminated as they would in reality or I don't have a light and everything is black.
All what I want to have is the texture (jpeg) on my model as they are in the jpeg.
How can I achieve this?
Thank you:)
A:
I'm not sure if you're trying to do this. Here's my solution:
Hide all lights in your scene by selecting lights and pressing H.
Set your world to white. If there's no color selection, you may check "Use Nodes" to create nodes before you change the world color.
Use Node Wrangler. It's a built-in plug-in. Ctrl+Alt+U to call User Preferences. Go to Addons and search "Node Wrangler", and tick it, then save user settings.
Go to Node Editor, and build up your materials for the object. Once finished, you want to make a solo preview of your texture, so press Ctrl+Shift+LMB on an image node of your diffuse BSDF to make it solo in preview.
(The dotted line was the original line in final, but I make a solo preview of the texture, as you can see the Material Output receives input from a Viewer, followed with Image node.)
Render, or make a viewport render, by Shift+Z.
Alternatively, You can also make screenshots in Material viewport.
Hope that helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Record sound and save using AS
How to record sound from a microphone and save it from the following code
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import flash.events.SampleDataEvent;
import flash.media.Microphone;
import flash.net.FileReference;
import mx.controls.Alert;
import flash.net.FileReference;
[Bindable] private var microphoneList:Array;
protected var microphone:Microphone;
protected var isRecording:Boolean = false;
protected function setupMicrophoneList():void
{
microphoneList = Microphone.names;
}
protected function setupMicrophone():void
{
microphone = Microphone.getMicrophone(comboMicList.selectedIndex);
}
protected function startMicRecording():void
{
Alert.show("In recording");
isRecording = true;
Alert.show("In recording1");
microphone.addEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
Alert.show("In recording22");
}
protected function stopMicRecording():void
{
isRecording = false;
microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
}
private function gotMicData(micData:SampleDataEvent):void
{
Alert.show("In mic data");
// micData.data contains a ByteArray with our sample. }
try{
var file:FileReference = new FileReference();
file.save(micData.data ,"Testsound.flv");
}
catch(e:Error)
{
Alert.show("In gotomicdataexception"+e);
}
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:ComboBox x="150" id="comboMicList" dataProvider="{microphoneList}" />
<mx:Button x="250" id="startmicrec" label="Start Rec" click="startMicRecording()"/>
<mx:Button x="350" id="stopmicrec" label="Stop Rec" click="stopMicRecording()"/>
<mx:Button x="50" id="setupmic" label="Select Mic" click="setupMicrophone()"/>
<mx:Button x="450" id="playrecsound" label="Play sound" click="playbackData()"/>
A:
Here's your updated code that will provide you ability to save file after recording it. But anyway you need to encode bytearray into format like wav or mp3:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600"
creationComplete="this_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
[Bindable] private var microphoneList:Array;
protected var microphone:Microphone;
protected var isRecording:Boolean = false;
private var soundBytes:ByteArray = new ByteArray();
protected function setupMicrophoneList():void
{
microphoneList = Microphone.names;
}
protected function setupMicrophone():void
{
microphone = Microphone.getMicrophone(comboMicList.selectedIndex);
}
protected function startMicRecording():void
{
trace("In recording");
isRecording = true;
trace("In recording1");
microphone.addEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
trace("In recording22");
}
protected function stopMicRecording():void
{
isRecording = false;
microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA, gotMicData);
saveMicData();
}
private function saveMicData():void
{
trace("In mic data");
// micData.data contains a ByteArray with our sample. }
try{
var file:FileReference = new FileReference();
file.save(/*You need encoded soundBytes here*/soundBytes ,"Testsound.wav");
}
catch(e:Error)
{
trace("In gotomicdataexception"+e);
}
}
private function gotMicData(event:SampleDataEvent):void
{
while(event.data.bytesAvailable)
{
var sample:Number = event.data.readFloat();
soundBytes.writeFloat(sample);
}
}
private function playbackData():void
{
}
protected function this_creationCompleteHandler(event:FlexEvent):void
{
setupMicrophoneList();
}
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout />
</s:layout>
<mx:ComboBox id="comboMicList" dataProvider="{microphoneList}" />
<mx:Button id="setupmic" label="Select Mic" click="setupMicrophone()"/>
<s:HGroup>
<mx:Button id="startmicrec" label="Start Rec" click="startMicRecording()"/>
<mx:Button id="stopmicrec" label="Stop Rec" click="stopMicRecording()"/>
<!--<mx:Button id="playrecsound" label="Play sound" click="playbackData()"/>-->
</s:HGroup>
</s:Application>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Substring and split in sql server
I have these data in my sql server as you can see here :
1/2
1/4
2/23
12/13
1/10
...
I need to change these to 001,001,002,012,001,..
I use this .but it doesn't work
LEFT(SheetNumber,LEN(SheetNumber)-CHARINDEX('/',SheetNumber))
My query
SELECT [Id]
,LEFT(SheetNumber,LEN(SheetNumber)-CHARINDEX('/',SheetNumber))
,[SubmitDateTime]
FROM [SPMS2].[dbo].[Lines] where SheetNumber like '%/%'
A:
You dont need to use LEN. Just use
LEFT(SheetNumber,CHARINDEX('/',SheetNumber) - 1)
To make it into 3 digits with 0 in the front, you could use something like this
Right('000' + LEFT(SheetNumber,CHARINDEX('/',SheetNumber) - 1), 3)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proper parenting of QWidgets generated from a QThread to be inserted into a QTreeWidget
I have a QTreeWidget which needs to be populated with a large sum of information. So that I can style it and set it up the way I really wanted, I decided I'd create a QWidget which was styled and dressed all pretty-like. I would then populate the TreeWidget with generic TreeWidgetItems and then use setItemWidget to stick the custom QWidgets in the tree. This works when the QWidgets are called inside the main PyQt thread, but since there is a vast sum of information, I'd like to create and populate the QWidgets in the thread, and then emit them later on to be added in the main thread once they're all filled out. However, when I do this, the QWidgets appear not to be getting their parents set properly as they all open in their own little window. Below is some sample code recreating this issue:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class ItemWidget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
btn = QPushButton(self)
class populateWidgets(QThread):
def __init__(self):
QThread.__init__(self)
def run(self):
widget = ItemWidget()
for x in range(5):
self.emit(SIGNAL("widget"), widget)
class MyMainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.tree = QTreeWidget(self)
self.tree.setColumnCount(2)
self.setCentralWidget(self.tree)
self.pop = populateWidgets()
self.connect(self.pop, SIGNAL("widget"), self.addItems)
self.pop.start()
itemWidget = QTreeWidgetItem()
itemWidget.setText(0, "This Works")
self.tree.addTopLevelItem(itemWidget)
self.tree.setItemWidget(itemWidget, 1, ItemWidget(self))
def addItems(self, widget):
itemWidget = QTreeWidgetItem()
itemWidget.setText(0, "These Do Not")
self.tree.addTopLevelItem(itemWidget)
self.tree.setItemWidget(itemWidget, 1, widget)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
ui = MyMainWindow()
ui.show()
sys.exit(app.exec_())
As you can see, doing it inside MyMainWindow is fine, but somehow things go awry once it gets processed in the thread and returns. Is this possible to do? If so, how do I properly parent the ItemWidget class inside the QTreeWidgetItem? Thanks in advance.
A:
AFAICT Qt doesn't support the creation of QWidgets in a thread other than the thread where the QApplication object was instantiated (i.e. usually the main() thread). Here are some posts on the subject with responses from Qt developers:
http://www.qtcentre.org/archive/index.php/t-27012.html
http://www.archivum.info/[email protected]/2009-07/00506/Re-(Qt-interest)-QObject-moveToThread-Widgets-cannot-be-moved-to-a-new-thread.html
http://www.archivum.info/[email protected]/2009-07/00055/Re-(Qt-interest)-QObject-moveToThread-Widgets-cannot-be-moved-to-a-new-thread.html
http://www.archivum.info/[email protected]/2009-07/00712/Re-(Qt-interest)-QObject-moveToThread-Widgets-cannot-be-moved-toa-new-thread.html
(if it were possible, the way to do it would be to call moveToThread() on the QWidgets from within the main thread to move them to the main thread -- but apparently that technique doesn't work reliably, to the extent that QtCore has a check for people trying to do that prints a warning to stdout to tell them not to do it)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
scala: type mismatch error - found T, required String
I'm learning scala, and this question may be stupid, but... why?
For example, this is ok:
def matchList(ls: List[Int]): List[Int] = ls match {
case 1 :: rest => rest
case a :: b :: rest => (a + b) :: rest
case _ => ls
}
matchList: (ls: List[Int])List[Int]
But function with type parameter does not compile:
def matchList[T](ls: List[T]): List[T] = ls match {
case 1 :: rest => rest
case a :: b :: rest => (a + b) :: rest
case _ => ls
}
<console>:10: error: type mismatch;
found : T
required: String
case a :: b :: rest => (a + b) :: rest
Why?
A:
For any type T the operation T + T doesn't make any sense. (Do all types support +? No. Think of adding two dogs or two employees.)
In your case, the string concatenation operator is getting invoked (added via any2stringadd pimp), whose return type is (obviously) String. Hence the error message.
What you need is a way to specify that type T must support an operation where you combine two values of type T to yield a new value of type T. Scalaz's Semigroup fits the bill perfectly.
The following works:
def matchList[T : Semigroup](ls: List[T]): List[T] = ls match {
case 1 :: rest => rest
case a :: b :: rest => (a |+| b) :: rest // |+| is a generic 'combining' operator
case _ => ls
}
A:
I think the problem lies in (a + b), the only universal usage of the + operator is string concatenation, so a and b must both be Strings (or automatically convertible to Strings) in order for that to be valid. Your parameterized type T isn't known to be a String, so it fails to compile.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to decide optimal settings for setMaxTotal and setDefaultMaxPerRoute?
I have a RestService running on 45 different machines in three datacenters (15 in each datacenter). I have a client library which uses RestTemplate to call these machines depending on where the call is coming from. If the call is coming from DC1, then my library will call my rest service running in DC1 and similarly for others.
My client library is running on different machines (not on same 45 machines) in three datacenters.
I am using RestTemplate with HttpComponentsClientHttpRequestFactory as shown below:
public class DataProcess {
private RestTemplate restTemplate = new RestTemplate();
private ExecutorService service = Executors.newFixedThreadPool(15);
// singleton class so only one instance
public DataProcess() {
restTemplate.setRequestFactory(clientHttpRequestFactory());
}
public DataResponse getData(DataKey key) {
// do some stuff here which will internally call our RestService
// by using DataKey object and using RestTemplate which I am making below
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000)
.setSocketTimeout(1000).setStaleConnectionCheckEnabled(false).build();
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(800);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(700);
CloseableHttpClient httpClientBuilder = HttpClientBuilder.create()
.setConnectionManager(poolingHttpClientConnectionManager).setDefaultRequestConfig(requestConfig)
.setDefaultSocketConfig(socketConfig).build();
requestFactory.setHttpClient(httpClientBuilder);
return requestFactory;
}
}
And this is the way people will call our library by passing dataKey object:
DataResponse response = DataClientFactory.getInstance().getData(dataKey);
Now my question is:
How to decide what should I choose for setMaxTotal and setDefaultMaxPerRoute in PoolingHttpClientConnectionManager object? As of now I am going with 800 for setMaxTotal and 700 setDefaultMaxPerRoute? Is this a reasonable number or should I go with something else?
My client library will be used under very heavy load in multithreading project.
A:
There are no formula or a recipe that one can apply to all scenarios. Generally with blocking i/o one should have approximately the same max per route setting as the number of worker threads contending for connections.
So, having 15 worker threads and 700 connection limit makes little sense to me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there any difference between 'ree' and 'denove'?
Is there any difference between ree and denove? I mostly see denove used, but ree seems like a logical substitute for such cases.
A:
Denove is the traditional way of saying ”again” in Esperanto. Ree is made from the prefix re-, so it’s a bit more ”fresh and slangy”, I’d say.
You could compare it with antaŭa versus eksa: Mi estis tie kun mia antaŭa koramikino vs. Mi estis tie kun mia eksa koramikino. The former sounds a bit more formal, but the difference in meaning is slight.
Hooray for synonyms, I’d say! :-) Which one to use depends on the setting. I think I’d go with the second phrase below:
Li ree restartigis sian komputilon.
Li denove restartigis sian komputilon.
Also note the Esperantigo of the great fantasy classic The Hobbit, or There and Back Again: ”La Hobito aŭ Tien kaj Reen.”
Tien kaj Denoven would be wrong, so the synonymity is not perfect in this case. :-)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grunt : JASMINE is not supported anymore
i created an angular application with yeoman, when i executed grunt command i got the following error
Running "karma:unit" (karma) task
WARN [config]: JASMINE is not supported anymore.
Please use `frameworks = ["jasmine"];` instead.
WARN [config]: JASMINE_ADAPTER is not supported anymore.
Please use `frameworks = ["jasmine"];` instead.
WARN [config]: LOG_INFO is not supported anymore.
Please use `karma.LOG_INFO` instead.
ERROR [config]: Config file must export a function!
module.exports = function(config) {
config.set({
// your config
});
};
how do i solve this error ?
A:
It's just those two predefined terms (JASMINE and JASMINE_ADAPTER)
that should not be used any more. All you have to do is open the
config file ./config/karma.conf.js and comment out those terms and add
frameworks = ["jasmine"];.
Via Yasuhiro Yoshida
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how can i get particular div text from selected li
I have created multiple ul and I want particular div value from particular li
I have tried to make a function for that but it is not working
$(".answer-list li").click(function() {
$(this).addClass('active');
BusinessLogic();
});
function BusinessLogic(){
var selText = $('.answer-list li .active div p').text();
alert(selText);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<ul class="answer-list" id="answer_list1">
<li>
<a tabindex="1" id="question1">
<span class="letter-option">A.</span>
<div>
<p>Plan risk management</p>
</div>
</a>
</li>
<li class="active">
<a tabindex="2" id="question1">
<span class="letter-option">B.</span>
<div>
<p>Identify risks</p>
</div>
</a>
</li>
<li>
<a tabindex="3" id="question1">
<span class="letter-option">C.</span>
<div>
<p>Plan risk responses</p>
</div>
</a>
</li><li>
<a tabindex="4" id="question1">
<span class="letter-option">D.</span>
<div>
<p>Perform qualitative risk analysis</p>
</div>
</a>
</li>
</ul>
and I want selected li div value but it shows me blank
can anybody help me with this?
A:
Try like this to get the innerhtml of div tag.
$(".answer-list li").click(function() {
$('li').removeClass('active');
$(this).addClass('active');
BusinessLogic();
});
function BusinessLogic(){
var selText = $('.answer-list li.active div p').text();
console.log(selText);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<ul class="answer-list" id="answer_list1">
<li>
<a tabindex="1" id="question1">
<span class="letter-option">A.</span>
<div>
<p>Plan risk management</p>
</div>
</a>
</li>
<li class="active">
<a tabindex="2" id="question1">
<span class="letter-option">B.</span>
<div>
<p>Identify risks</p>
</div>
</a>
</li>
<li>
<a tabindex="3" id="question1">
<span class="letter-option">C.</span>
<div>
<p>Plan risk responses</p>
</div>
</a>
</li><li>
<a tabindex="4" id="question1">
<span class="letter-option">D.</span>
<div>
<p>Perform qualitative risk analysis</p>
</div>
</a>
</li>
</ul>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
must be str, not bytes | 'str' has no attribute 'decode'
I have this simple code to extract from a mongo database:
import sys
import codecs
import datetime
from pymongo import MongoClient
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
mongo_db = "database"
collectionId = "coll name"
def main(argv):
client = MongoClient("mongodb://localhost:27017")
db = client[mongo_db]
collection = db[collectionId]
cursor = collection.find({})
for document in cursor:
# if "content" in document:
# sys.stdout.write(
# "|"+(document['content'] if document['content'] is not None else "")+"\n")
for key, value in document.items() :
sys.stdout.write(key.decode('utf-8'))
if __name__ == "__main__":
main(sys.argv)
running it like this, gets me
AttributeError: 'str' object has no attribute 'decode'
So... it's a str object, then? but if I remove the decode, I get
TypeError: must be str, not bytes
and, it's not like it's printing anything, so, it must be failing at the first key? but... can the first key be neither str nor bytes??? how can I print this?
EDIT testing with flush:
for key, value in document.items() :
sys.stdout.write("1")
sys.stdout.flush()
sys.stdout.write(key.decode('utf-8'))
sys.stdout.flush()
I changed the for to that, getting the error
~/Desktop$ python3 sentimongo.py
Traceback (most recent call last):
File "sentimongo.py", line 30, in <module>
main(sys.argv)
File "sentimongo.py", line 24, in main
sys.stdout.write("1")
File "/usr/lib/python3.4/codecs.py", line 374, in write
self.stream.write(data)
TypeError: must be str, not bytes
A:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
This line changes the standard output, so it does different things than you normally see. In Python 3 you don’t really need to care about converting things to utf8 since everything already is a unicode string.
If you remove that line, writing a normal string (or even printing one) should work fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I skip mercurial pre-commit hooks like in git?
I want to do something like git commit --no-verify but with mercurial. Are any ways to do it?
A:
As noted in the hg help config documentation:
... Multiple hooks can be run for the same action by appending a suffix to the action. Overriding a site-wide hook can be done by changing its value or setting it to an empty string. Hooks can be prioritized by adding a prefix of "priority." to the hook name on a new line and setting the priority. The default priority is 0.
(emphasis mine). While this refers to "system-wide hooks", it works for in-repository hooks as well:
$ sed -n '/hooks/,+1p' .hg/hgrc
[hooks]
pre-commit = ./foo.sh
$ cat foo.sh
#! /bin/sh
echo foo
exit 1
$ hg commit
foo
abort: pre-commit hook exited with status 1
Obviously my pre-commit hook is working. Now to defeat it:
$ hg --config hooks.pre-commit= commit
nothing changed
(there was nothing to commit; overriding the pre-commit hook worked).
You will, of course, need to know which specific hook(s) you want to override, since there may be more than one pre-commit hook.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
replace/remove awk/sed/vim column elements after a character
I have a text file which contains single column entries,
1745:1745
1746:1746
1747:1747
1748:1748
42:42
43:43
44:44
45:45
46:46
And I want to remove the duplication of numbers, i.e. remove all the characters starting with (including) colon, with the output format,
1745
1746
1747
1748
42
43
44
45
46
How can I do it ?
Thanks
A:
cut -d ':' -f 1 < file.txt
This seems to work, huh ?
A:
For given input below awk should work
awk -F':' '{ print $1 }' infile
A:
Could you please try following, these ones based on substitution from colon to till end with null.
Solution 1st: Using awk:
awk '{sub(/:.*/,"")} 1' Input_file
Solution 2nd: Using sed:
sed 's/:.*//g' Input_file
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show that $\mu:=\sum_{i\geq 1}p_i\mu_i$ is a probability measure
Let $(\mu_i)_{i\in\mathbb{N}}$ be a sequence of probability mesaures on $(\Omega,\mathcal{A})$ and $(p_i)_{i\in\mathbb{N}}$ a probability vector. Show that then $\mu:=\sum_{i=1}^{\infty}p_i\mu_i$ defines a probability measure.
Hello, here is my proof:
It is $\mu(\emptyset)=\sum_{i\geq 1}p_i\mu_i(\emptyset)=0$, because $\mu_i(\emptyset)=0, i\geq 1$. Similarly it is $\mu(\Omega)=\sum_{i\geq 1}p_i\mu_i(\Omega)=\sum_{i\geq 1}p_i=1$, because $\mu_i(\Omega)=1, i\geq 1$.
Let $A_i,i\geq 1$ pairwise disjoint in $\mathcal{A}$. Set $A:=\bigcup_{i\geq 1}A_i$.
$$
\mu(A)=\sum_{i\geq 1}p_i\mu_i(A)=\sum_{i\geq 1}p_i(\sum_{j\geq 1}\mu_i(A_j))=\sum_{i\geq 1}\sum_{j\geq 1}p_i\mu_i(A_j)=\sum_{j\geq 1}\sum_{i\geq 1}p_i\mu_i(A_j)=\sum_{i\geq 1}\mu(A_i).
$$
Is it okay?
Miro
A:
Your proof is correct. You should probably note that you may interchange the two sums, since the terms are non-negative.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Continuous Random Variables
Given the function:
$$
f(x) = \begin{cases} 0 & x<0, \\ a(b-x) & 0\le x\le b, \\ 0 & b<x, \end{cases}
$$
where $a, b ∈ (0, ∞)$. We also know that $\operatorname{E}(X) = 1$. I need to find out $a,b$ and the distribution function.
I made an equation system using $\operatorname{E}(X)=1$ and $F(X)=1$ from which I got $a = 2/9$ and $b = 3$, but I'm not really sure if my method is correct and I'm a bit lost on how to calculate the distribution function. Any help is greatly appreciated! :)
$$\operatorname{E}(X)=\int_0^b y f(y) \,dy,$$
This gave me $ab^3=6$.
$$F(X)=\int_0^b f(y) \, dy$$
This gave me $ab^2=2$.
A:
You need for your density function to integrate to $1.$
According to your solution you have:
$$\int_{-\infty}^\infty f(x)\,dx = \int_{-\infty}^0 0\,dx +
\int_0^3 \frac{2}{9}(3-x)\,dx + \int_3^\infty 0\,dx = \int_0^3 \frac{2}{9}(3-x)\,dx = 1,$$
which is correct. Then to get the mean, you need to find.
$$E(X) = \int_0^3 x \cdot \frac{2}{9}(3-x)\,dx$$
You have a random variable with support $(0,3)$ so the mean cannot possibly be $6.$ Try the integration again.
Your answer for the CDF is in three parts: $F(x) = 0,$ for $x \in (\infty,0);\;
F(x) = 1,$ for $x \in (3, \infty);$ and
$F(x) = \int_0^x f(t)\,dt$ for $x \in [0, 3].$ You still need to evaluate
the last integral. Make sure that you get $F(0) = 0$ and $F(3) = 1.$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using OAuth2 for securing a monolith private REST api?
Maybe this question seems opinion based, but I am facing a hard time in deciding to secure a RESTful API.
Firstly, my use-case:
My application is pretty straight forward: The front-end is written using React.js(for browser client) and that will consume the RESTful API for getting its data from the database(or something). The API is built using Spring framework.
This API is not a public API, and it has only a single client(as of now, later would be mobile apps).
Now lets come to the security problem. Obviously, I want to secure my API, I am using Spring-security as a tool for this job. During the starting days of learning, I knew only about the Basic-Authentication. But, when I kept on reading about more secure options, I learned some new fancy terms:
Token-based Authentication, using JWT
OAuth2
OpendId connect
When I read more blogs like from Auth0, Okta and a lot more, I messed up everything. This made me think twice if I should use OAuth for securing a REST API (which is not public). Also, almost all of the blogs about OAuth take examples of social logins. This made me more messed, that OAuth is for giving access of your API to the third party application. And that's it, not for my use-case.
I then asked some experts from some channels and blogs, some said the Basic-Authentication is very enough for security(using https) and I should avoid OAuth for such a small requirement. Other said opposite to that, saying Basic-Auth has security vulnerabilities.
Let's consider that OAuth is perfect for me, but in that case also, where would my Authorization server reside? Because tutorials only explain about Authorization server by keeping their code in the same layer. No separate project or something.
JWT also has some negative reviews for my user-case:
they cannot be revoked, will only expire on its own. Isn't it insecure?
they are massive in size, compared to session token or cookie
hight computational cost for verification
I really need some more advice on this, it has already taken my lot of weeks.
Thanks.
A:
The real answer depends on information not in your question. For example do you need identity verification or are you just authorizing API access?
OAuth and Open ID Connect (OIDC) today are basically the same thing for most services such as Google Login. OIDC adds an identity layer on top of authorization. If you need to verify the identity of your users, log their activity, control resources per user, etc. this is your solution.
For authorizing API endpoints, there are many solutions. The most common are secret key value and JWT. Secret key has many weaknesses so I will not touch on that here.
A very common method of authorizing API endpoints is using JWT tokens and the Authorization: Bearer TOKEN HTTP header. I will now try to answer your concerns about using JWT tokens. Here I only refer to Signed-JWT tokens.
they cannot be revoked, will only expire on its own. Isn't it
insecure?
JWT tokens can be revoked by revoking the signing certificate. This would require creating a certificate revocation server, so this is not so common. An improved approach is to create short-lived tokens. Typical expiration time is 60 minutes (3600 seconds) but you can create tokens for any time period. When the token expires, the client requests a new one, which your backend can authorize or refuse.
they are massive in size, compared to session token or cookie
What is massive? You can create a token of any size from just a few bytes (the size of the signature plus data) or include extensive information in the token. Unless your tokens are out of control in size, this will not matter to most implementations.
high computational cost for verification
Again you are using a vague term. Verifying a Signed JWT is not computational expensive unless you are on tiny devices such as IoT (which are already using SSL certificates, encryption, etc.) or you need to handle millions of transactions per minute. In other words unless you have a solid reason to worry about CPU cycles, don't worry about them in regards to improved security.
Let's consider that OAuth is perfect for me, but in that case also,
where would my Authorization server reside?
Your OAuth 2.0 authorization server can reside anywhere you want. Implementing OAuth is very easy and there are many libraries to manage the details for you. Your authorization server can be part of your backend, be a separate server, etc. You can even just outsource this completely to identity providers such as Google Login, Auth0, Okta, etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extension Method to Get the Values of Any Enum
I've been trying to create an extension method, that would work on any enum, to return its values.
Instead of doing this:
Enum.GetValues(typeof(BiasCode)).Cast<BiasCode>()
It would be nice to do this:
new BiasCode().Values()
It would even be better without new, but that's another issue.
I have a .NET fiddle that has a solution that's close (code shown below). The problem with this code is that the extension method is returning List<int>. I would like to have it return a list of the enum values itself. Returning List<int> isn't terrible; it just means I have to cast the result.
Is it even possible to do this? I tried making the extension method generic, but ran into problems. This is as close as I was able to get:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
foreach (int biasCode in new BiasCode().Values())
{
DisplayEnum((BiasCode)biasCode);
}
}
public static void DisplayEnum(BiasCode biasCode)
{
Console.WriteLine(biasCode);
}
}
public enum BiasCode
{
Unknown,
OC,
MPP
}
public static class EnumExtensions
{
public static List<int> Values(this Enum theEnum)
{
var enumValues = new List<int>();
foreach (int enumValue in Enum.GetValues(theEnum.GetType()))
{
enumValues.Add(enumValue);
}
return enumValues;
}
}
A:
You can return an instance of the appropriate enum type (created using reflection), but its static type cannot be List<EnumType>. That would require EnumType to be a generic type parameter of the method, but then the type would have to be constrained to only enum types and that is not possible in C#.
However, you can get close enough in practice (and add runtime checks to top it off) so you can write a method that works like this:
public static IEnumerable<TEnum> Values<TEnum>()
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var enumType = typeof(TEnum);
// Optional runtime check for completeness
if(!enumType.IsEnum)
{
throw new ArgumentException();
}
return Enum.GetValues(enumType).Cast<TEnum>();
}
which you can invoke with
var values = Values<BiasCode>();
I have made the method return IEnumerable<TEnum> instead of a list for the extra LINQ-y flavor, but you can trivially return a real list with .ToList() on the return value.
A:
You could declare your method like this:
public static List<T> Values<T>() where T : struct
{
var type = typeof(T);
if(!type.IsEnum) return null; // or throw exception
return Enum.GetValues(type).Cast<T>().ToList();
}
Then you can call it
Values<BiasCode>();
A:
I'm wondering if I'm missing something because all of the answers use a generic method as part of the solution. Why not just do something like this?
public static List<Enum> Values(this Enum theEnum)
{
return Enum.GetValues(theEnum.GetType()).Cast<Enum>().ToList();
}
The fiddle is here: https://dotnetfiddle.net/FRDuvD
This way this extension method will only be available to enums. Using the generics approach, the extension method seems to be available to all types:
string someString = "x";
someString.Values();
It would be better not to have Values() available to a string at compile time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android: Set alpha on button on click. Preferably xml only
I want to introduce a 'down' style on some buttons. I've created a style, and a state list.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/inactive_button_background" android:state_enabled="false"/>
<item android:drawable="@drawable/active_button_background" android:state_enabled="true"/>
<item android:drawable="@drawable/pressed_button_background" android:state_pressed="true"></item>
</selector>
The problem is that I want to be able to change just the alpha of the background when the button gets clicked (I will have variable backgrounds, so setting a sold color with alpha channel is not a solution).
And I want to do this from the declarative xml only (don't want to polute my code with layout stuff).
Problem is I don't know how to apply this alpha blending to the button from a xml drawable.
I am pretty sure there's a way though.
A:
I am bit late to answer this question but i just did this by changing the alpha value using View.onTouchListner
You can do this by implementing onTouch in this way
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
v.setAlpha(0.5f);
break;
case MotionEvent.ACTION_UP:
v.setAlpha(1f);
default :
v.setAlpha(1f)
}
return false;
}
I guess you cant change alpha value from drawable so you will have to do this in this way only.
A:
This works perfectly
yourView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.setAlpha(0.5f);
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
v.setAlpha(1f);
break;
}
}
return false;
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Store all information about the text of a richtextbox and reconstruct it- c# winforms
Is there a way to store all of the information about the text in a richtextbox (colors, sizes, fonts, etc) and reconstruct it in another richtextbox, which is not in the same form or project?
For example, I have a richtextbox which its text contains multiple fonts and colors, and some lines are centered, and I want to reconstruct it in another richtextbox.
I added that the new richtextbox is not in the same project, so i need to restore the information somewhere (for example, even in a string or a file).
A:
To copy the text and formatting from one richTextBox to another, simply use:
richtextBox2.Rtf = richtextBox1.Rtf;
The Rtf property is simply a string, so you can do with it whatever you can do with strings.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RSS Feed が遅延している
RSSフィードについてフィードバックしたいと思います。「最近の質問」 (http://ja.stackoverflow.com/feeds)がRSSリーダーごとに内容が異なります。2017/4/7 12:13 JST時点で次のように違いが見られます。
Thunderbird : 2017/4/6 8:13 が最新の質問となっており遅延している
Firefox : サイト上の新着と同じ
feeds の内容を確認すると <updated>2017-04-05T23:56:07Z</updated> と表示されました。こうやって確認しました。
$ curl -s http://ja.stackoverflow.com/feeds | gzip -dc | head -10
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
<title type="text">最近の質問 - スタック・オーバーフロー</title>
<link rel="self" href="http://ja.stackoverflow.com/feeds" type="application/atom+xml" />
<link rel="alternate" href="http://ja.stackoverflow.com/questions" type="text/html" />
<subtitle>次の URL からの最新の 30 件: ja.stackoverflow.com</subtitle>
<updated>2017-04-05T23:56:07Z</updated>
<id>http://ja.stackoverflow.com/feeds</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license>
なお、複数の環境で同じ結果なのでキャッシングなどの影響ではないと思います。私のPCと、AWS上のLinuxインスタンス どちらも同じ結果になりました。
A:
遅れてますね。
アクセス元の地域
ログイン状況 (Cookieがあるか)
が影響していそうです。
以前報告した問題でも地域による差がありました。
ざっと試した限りでは、以下のようになっています。
ログインしてアクセスすると地域によらず、最新のフィードが得られる
匿名でのアクセスでは、古いフィードが得られ、どれくらい古いかは、どこからアクセスするかによる
匿名アクセスでの遅延は相当あり、特に本家のフィード (https://stackoverflow.com/feeds) は10日近く遅れているように見える
フィードリーダーはログインセッションなど持たずにアクセスするものですから、改善するといいですね。
例として、ほぼ同時刻の https://ja.stackoverflow.com/feeds へのアクセスで以下のような違いが見られました (最初の<updated>タグを抜きだしています)。
<updated>2017-04-07T08:15:37Z</updated> # use session cookie (from Japan)
<updated>2017-04-07T04:26:06Z</updated> # from Japan
<updated>2017-04-04T20:50:23Z</updated> # from USA
<updated>2017-04-04T10:29:52Z</updated> # from Russia
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Having issues creating a 2d array of javafx shapes as it cannot have values assigned
ive been looking a while and unable to find a solution to this one. Basically on the code below the line Circle[][] board = new Circle[rows][column]; is giving me issues when i try to assign any values to these circles due to them being null. Ive been trying to add curly brackets like this Circle[][] board = new Circle(0)[rows][column]; which would fix the issue but then it says Array type expected; found javafx.scene.shape.Circle Ive added my code for this class as well as my error code. If any other code is required let me know and thanks in advance for any help.
Code:
package com.company;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class SetupBoard {
public void main(Stage stage) {
int rows = 8;
int column = 8;
Circle[][] board = new Circle[rows][column];
int rowcounter = 0;
int columncounter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
board[i][j].setRadius(0);
}
}
while (rowcounter < 3) {
if (columncounter == 9) {
columncounter = 0;
}
if (columncounter == 8) {
columncounter = 1;
}
while (columncounter < 8) {
board[rowcounter][columncounter].setRadius(20);
columncounter = columncounter + 2;
}
rowcounter++;
}
rowcounter = 5;
columncounter = 1;
while (rowcounter < 8) {
if (columncounter == 9) {
columncounter = 0;
}
if (columncounter == 8) {
columncounter = 1;
}
while (columncounter < 8) {
board[rowcounter][columncounter].setRadius(20);
columncounter = columncounter + 2;
int centrex;
int centrey;
centrex = 75 + (50 * rowcounter);
centrey = 125 + (50 * columncounter);
board[rowcounter][columncounter].setStroke(Color.BLUE);
board[rowcounter][columncounter].setFill(Color.BLUE);
board[rowcounter][columncounter].setCenterX(centrex);
board[rowcounter][columncounter].setCenterY(centrey);
}
rowcounter++;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
//System.out.print(board[i][j]);
//Group root = new Group((board[i][j]));
//Scene scene = new Scene(root, 600, 600);
//stage.setScene(scene);
//stage.show();
}
System.out.println("");
}
}
}
and the error:
> Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
... 48 more
Caused by: java.lang.NullPointerException
at com.company.SetupBoard.main(SetupBoard.java:19)
at com.company.Screens.MainWindow.BtnPress_start(MainWindow.java:25)
... 58 more*
A:
Circle[][] board = new Circle[rows][column];
Here you just initialized the array.That means you told the JVM "hey! Look, I need this space for my elements to be stored here!".
The JVM then responded by giving you a pointer to that space. Each matrix position represent a point inside that empty space.
____________________
| null | null | null |
|______|______|______|
| null | null | null |
|______|______|______|
| null | null | null |
|______|______|______|
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
board[i][j].setRadius(0);
}
}
Here you're trying to call setRadius an a null reference, which is the default valid value for an empty space.
Before doing that you need to initialize the Circle(s), in the same way
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
board[i][j] = new Circle();
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Strange Clang behaviour
Have a look at this piece of code:
#include <iostream>
#include <string>
void foo(int(*f)()) {
std::cout << f() << std::endl;
}
void foo(std::string(*f)()) {
std::string s = f();
std::cout << s << std::endl;
}
int main() {
auto bar = [] () -> std::string {
return std::string("bla");
};
foo(bar);
return 0;
}
Compiling it with
g++ -o test test.cpp -std=c++11
leads to:
bla
like it should do. Compiling it with
clang++ -o test test.cpp -std=c++11 -stdlib=libc++
leads to:
zsh: illegal hardware instruction ./test
And Compiling it with
clang++ -o test test.cpp -std=c++11 -stdlib=stdlibc++
leads also to:
zsh: illegal hardware instruction ./test
Clang/GCC Versions:
clang version 3.2 (tags/RELEASE_32/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
gcc version 4.7.2 (Gentoo 4.7.2-r1 p1.5, pie-0.5.5)
Anyone any suggestions what is going wrong?
Thanks in advance!
A:
Yes, it is a bug in Clang++. I can reproduce it with CLang 3.2 in i386-pc-linux-gnu.
And now some random analysis...
I've found that the bug is in the conversion from labmda to pointer-to-function: the compiler creates a kind of thunk with the appropriate signature that calls the lambda, but it has the instruction ud2 instead of ret.
The instruction ud2, as you all probably know, is an instruction that explicitly raises the "Invalid Opcode" exception. That is, an instruction intentionally left undefined.
Take a look at the disassemble: this is the thunk function:
main::$_0::__invoke():
pushl %ebp
movl %esp, %ebp
subl $8, %esp
movl 8(%ebp), %eax
movl %eax, (%esp)
movl %ecx, 4(%esp)
calll main::$_0::operator()() const ; this calls to the real lambda
subl $4, %esp
ud2 ; <<<-- What the...!!!
So a minimal example of the bug will be simply:
int main() {
std::string(*f)() = [] () -> std::string {
return "bla";
};
f();
return 0;
}
Curiously enough, the bug doesn't happen if the return type is a simple type, such as int. Then the generated thunk is:
main::$_0::__invoke():
pushl %ebp
movl %esp, %ebp
subl $8, %esp
movl %eax, (%esp)
calll main::$_0::operator()() const
addl $8, %esp
popl %ebp
ret
I suspect that the problem is in the forwarding of the return value. If it fits in a register, such as eax all goes well. But if it is a big struct, such as std::string it is returned in the stack, the compiler is confused and emits the ud2 in desperation.
A:
This is most likely a bug in clang 3.2. I can't reproduce the crash with clang trunk.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to process 2 of click events in order in Angular
<button class="post-save" (click)="fileUpload.upload()" (click)="editor.save()"> save </button>
When the save button is pressed,
Click Event 1 : File Upload
Click Event 2 : Post Save
When I click 'File Upload', it received the url as return value.
And 'editor.save()' is 'save the return url'.
So I want to run 'Event 2' after 'Event 1' is over.
How can I fix it?
A:
You should call one function only. I suspect fileUpload.upload() to be async, so one way to do it would be :
newFunction(){
this.fileUpload.upload().subscribe(data => {
// do what you do when the file is uploaded
this.editor.save();
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to write a regex for this expression?
url1 = http://xyz.com/abc
url2 = http://xyz.com//abc
I want to write a regex that validate both url1 and url2
A:
Why not just use urlparse instead?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Statelist drawable for different resource types
I've got resources for different screens in drawable-ldpi, drawable-ldpi, drawable-mdpi. Where should I place Statelist file? I mean, that xml could be one for all types of resources, so in what folder shoudl I place it?
A:
You can create a folder inside /res: drawable, and put your state list xml in that folder.
It can be referenced as R.drawable.your_state_list.
This way you will have only one xml which will be used for all the resolutions.
If you have other common drawables, you can place them here too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
linux split data and get expected output
"1560880011316","m1_1560880011316"
"1568622914951","m3_1568622914951"
"1561241144148","m9_1561241144148"
"1565872821276","m10_1565872821276"
"1569150947729","m40_1569150947729"
"1568629593352","m72_1568629593352"
"1557672414555","m76_1560947193769"
"1557151559940","m17_1561077860973"
From the data first column (seperated by ",") is the timestamp . i want to extract all ids (starting with m) where timestamp doesnt match the timestamp with the ids (seperated with "_") in linux
For example for the above data the result should be
m76_1560947193769
m17_1561077860973
As only the above 2 are not as expected.
A:
Since the tag is "linux" only, without any programming language specified. I assume you are expecting some Linux command line based solution: To read lines, then to split into two columns - timestamp and id, then to match timestamp against id and to output those unmatched. There should be a lot Linux commands can do above - awk, sed, grep, native shell. Here below is one based on native bash shell:
#!/bin/bash
export IFS=" ,"
while read tm id; do
[[ "${id//\"}" =~ "m[0-9]+_${tm//\"}" ]] || echo $tm,$id
done
Then run the script (e.g. check_unmatch.sh) with input text (e.g. input.txt) as ./check_unmatch.sh < input.txt (chmod in before of course).
Note:
The space inside IFS=" ," is intended to remove the heading space in your original input. The comma is of course the delimiter of columns.
The "${id//\"}" is to remove the double quote, so be the ${tm//\"}.
The regex is to check as strictly as your example describes. It can be tailored.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using jQuery to tell if file input field is empty
I have a PHP form with a file input field, and two text input fields. What I want to do is use jQuery to check if the file input field is empty, and if it's not, then show a specific div, but the following code does not work:
<input type="file" name="blog-entry-image" id="blog-entry-image" />
var fileInput = $.trim($("#blog-entry-image").val());
if (fileInput.length > 0) {
$("#new-blogentry").click(function() {
$("#sending").show();
return true;
});
}
"new-blogentry" is the submit button, and "sending" is a div with an animated gif.
A:
<input type="file" name="blog-entry-image" id="blog-entry-image" />
$(document).ready(function (){
$("#blog-entry").click(function() {
var fileInput = $.trim($("#blog-entry-image").val());
if (fileInput && fileInput !== '') {
$("#sending").show();
return true;
}
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Am I missing something with `raw_id_fields` in my Django Admin?
I am using raw_id_fields on a few foreign keys in my admin interface. When this is rendered, the magnifying-glass icon appears, but takes me to the admin list page for that model entitled "Select MODEL to change". I can then click on an item to edit it. I don't want edit the item, I want to select it and put the id in the form.
Is it possible for this to allow me to click on an item and select it? Am I missing something?
A:
That's not supposed to happen. The page after clicking the magnifying glass should be a popup titled: "Select {modelname}".
Are you not getting a popup? I can reproduce that problem if I go directly to the page in the URL, but it should be triggering some JavaScript to produce a popup.
I'd check for any JavaScript warning errors / make sure admin media is being served correctly, specifically this file: RelatedObjectLookups.js (do you see it in the source?)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Admin access on Pi 3
I have tried to edit files on my pi 3, such as pyaudio.py but cannot because system keeps telling me permission denied, why is this? How can I get admin acces even though it is my system? Anyone one please help
A:
A lot of commands need root privileges to be executed properly. You can grant them command-wise starting your commands with sudo or you can change the permission settings file-wise e.g. allowing all users to read, write and execute a file by using the command sudo chmod 777 /path/to/your/file.
However, giving all permissions to everyone circumvents the built-in permission system which is a security safeguard. You should always think about which user really needs what permissions and only grant those. For more information on what chmod does and what those numbers mean, read this post
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where can I find a free upload button image for an ajax file uploader?
I'm using the Uploadify plugin to handle file uploads but the default button image is ugly. Where can I find free button images (particularly upload buttons).
A:
Try Buttonator or IconFinder.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Implementing RxSwift with TRON
I am trying to start using RxSwift, therefore I tried to create a function that does a request and I tried to implement the rxResult() function that comes with TRON, the HTTP library I use. But the documentation on this is not very detailed. Can anyone point me in the right direction on what I am doing wrong? This is the function I have written:
static func readAllWithRx() {
let token = UserDefaults.standard.value(forKey: Constants.kTokenUserDefaultsKey) as! String
let url = URL(string: "api/url")!
let request: APIRequest<AssessmentResponse, MyAppError> = APIHelper.tron.request(url.absoluteString)
_ = request.rxResult().subscribe(onNext: { AssessmentResponse in
print("RX AssessmentResponse \(AssessmentResponse)")
}, onError: { Error in
}, onCompleted: {
}, onDisposed: {
})
}
Finally I try to call this request within my Controller using:
let read = Assessments.readAllWithRx()
A:
There’re 2 things at the beginning:
let read = Assessments.readAllWithRx() assumes the function returns something synchronously
Implementation of readAllWithRx you posted doesn’t return anything.
I’ve never used TRON, but as far as I can see, its rxResult() returns an Observable<T> where T is a type of the response. In this case, to get asynchronously AssesmentResponse, you need to subscribe to the observable (as you already did by the way).
Here's an example - an updated implementation of your readAllWithRx (won’t compiled probably, writing code in notepad):
static func readAllWithRx() -> Observable<AssessmentResponse> {
let token = UserDefaults.standard.value(forKey: Constants.kTokenUserDefaultsKey) as! String
let url = URL(string: "api/url")!
let request: APIRequest<AssessmentResponse, MyAppError> = APIHelper.tron.request(url.absoluteString)
return request.rxResult()
}
then, if you need to get AssessmentResponse somewhere in the code:
Assessments.readAllWithRx().subscribe(onNext: { result in
// your response here
print(result)
})
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redux possibibilty to dispatch an action on server side
I'm beginner with redux and create universal react redux application.
Is this any option to dispatch async action on server side like store.dispatch(actions.getOutput()) on server side.
getOutput is an asynchronous action which fetch some api on call and change the state on redux.
I Know to dispatch it on client side with redux-thunk middleware but not understanding the process on server side
let context = {},
status = 200;
const allReducers = combineReducers({
...reducers
});
const store = createStore(
allReducers,
compose(
applyMiddleware(thunkMiddleware, promise)
)
);
const preloadedStore = store.getState()
store.dispatch(actions.getStories());
const finalState = store.getState();
const ctx = ReactDomServer.renderToString(
<Provider store={store}>
<StaticRouter context={context} location={req.url}>
<App/>
</StaticRouter>
</Provider>
),
reactHelmet = ReactHelmet.renderStatic();
if(context.url){
return res.redirect(302, context.url);
}
if(context.status === 404){
status = 404;
}
let page = renderOutput(ctx, finalState, reactHelmet);
res.status(status).send(page);
A:
From the docs of redux-thunk, if you define your action like this:
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
you can then use it like this
store.dispatch(
makeASandwichWithSecretSauce('My wife')
).then(() => {
console.log('Done!');
});
Which means, on the server side you can do
store.dispatch(makeASandwichWithSecretSauce("My wife")).then(() => {
const ctx = ReactDomServer.renderToString(
<Provider store={store}>
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
</Provider>
);
const reactHelmet = ReactHelmet.renderStatic();
const page = renderOutput(ctx, finalState, reactHelmet);
res.status(status).send(page);
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
React Native Get battery status / level Using Native Modules
I am writing a react native app to get IOS and Android Battery status. I search through the net and found few libraries which can get battery level of the phone.
https://github.com/robinpowered/react-native-device-battery
https://github.com/remobile/react-native-battery-status
https://github.com/oojr/react-native-battery
Every library has issues when I try that and not much support for the developer when ask a question on git hub.
Can any one provide me better solution or library to get Battery status of IOS and Android.
Thanks in advance
A:
I wrote my own IOS and Android classes to get the Battery Status. Here are the steps if any one interested on that,
For IOS,
Open the iOS project in XCode
Create 2 new files call BatteryStatus.h and BatteryStatus.m
BatteryStatus.h file should contain following code
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface BatteryStatus : RCTEventEmitter <RCTBridgeModule>
@end
BatteryStatus.m file should
#import "BatteryStatus.h"
@implementation BatteryStatus
RCT_EXPORT_MODULE(BatteryStatus)
- (instancetype)init
{
if ((self = [super init])) {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
}
return self;
}
RCT_EXPORT_METHOD(hide) {
}
RCT_EXPORT_METHOD(updateBatteryLevel:(RCTResponseSenderBlock)callback)
{
callback(@[[self getBatteryStatus]]);
}
//manually get battery status by calling following method
-(NSDictionary*)getBatteryStatus
{
float batteryLevel = [UIDevice currentDevice].batteryLevel;
NSObject* currentLevel = nil;
currentLevel = [NSNumber numberWithFloat:(batteryLevel * 100)];
NSMutableDictionary* batteryData = [NSMutableDictionary dictionaryWithCapacity:2];
[batteryData setObject:currentLevel forKey:@"level"];
return batteryData;
}
@end
Inside your react native app, inside your js file add following code
import { NativeModules } from 'react-native';
constructor(props) {
super(props);
this.state = {
batteryLevel: null,
};
}
componentDidMount() {
NativeModules.BatteryStatus.updateBatteryLevel((info) => {
//console.log(info.level)
const level = Math.ceil(info.level);
this.setState({ batteryLevel: level});
});
}
For IOS above code is working for me to get the battery level
For Android,
Open the Android project in Android Studio
Create a group call BatteryStatus and include 2 Files named , BatteryStatusModule.java and BatteryStatusPackage.java
BatteryStatusModule.java Should contain following code
package com.yourproject.BatteryStatus;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class BatteryStatusModule extends ReactContextBaseJavaModule {
public BatteryStatusModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "BatteryStatus";
}
@ReactMethod
public void getBatteryStatus(Callback successCallback) {
Intent batteryIntent = getCurrentActivity().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if(level == -1 || scale == -1) {
level = 0;
}
//System.out.print("battery level");
//System.out.print(level);
successCallback.invoke(null ,((float)level / (float)scale) * 100.0f);
}
}
BatteryStatusPackage.java should contain following code
package com.yourproject.BatteryStatus;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BatteryStatusPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new BatteryStatusModule(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
Inside MainApplication.java include following code
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new MapsPackage(),
new BatteryStatusPackage()
);
}
Inside your react native app, inside your js file add following code
import { NativeModules } from 'react-native';
constructor(props) {
super(props);
this.state = {
batteryLevel: null
};
}
getBatteryLevel = (callback) => {
NativeModules.BatteryStatus.getBatteryStatus(callback);
}
6.Call it something like this:
componentDidMount() {
this.getBatteryLevel((batteryLevel) => {
console.log(batteryLevel);
});
}
For Android above code is working for me to get the battery level
Hope this will help some one to get battery level for IOS and ANDROID
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Webpack - Yaml -> JSON -> Extract file
I have a YAML file with a few translations. I need to transform these files into a JSON file. I've tried using yaml-import-loader and json-loader but I get an error.
Here's my setup:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractEnglish = new ExtractTextPlugin('lang/en.js');
module.exports = {
entry: [
'./src/locales/application.en.yml',
],
output: {
filename: 'english.js',
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.en\.yml$/,
use: extractEnglish.extract({
use: [
// { loader: 'json-loader' },
{
loader: 'yaml-import-loader',
options: {
output: 'json',
},
}],
}),
},
],
},
plugins: [
extractEnglish,
],
};
And the error I get:
Users/xxx/Documents/Project/node_modules/extract-text-webpack-plugin/dist/index.js:188
chunk.sortModules();
^
TypeError: chunk.sortModules is not a function
at /Users/xxx/Documents/Project/node_modules/extract-text-webpack-plugin/dist/index.js:188:19
Same error whether or not the json-loader is commented or not.
I really don't understand what is going wrong.
Versions:
"webpack": "2.6.1",
"extract-text-webpack-plugin": "^3.0.0",
"json-loader": "^0.5.7",
A:
Not sure if this will help your situation but I recently found a solution to my i18n loading problem. I do this to extract YAML into JSON files upfront as I use angular-translate and needed to load files dynamically and on-demand. I avoid extract-text-webpack-plugin and use only loaders: file-loader and yaml-loader.
First I setup the import of my .yaml files near the beginning of source (in my case a specific chain of import files for webpack to process)
import "./i18n/en.user.yaml";
I updated webpack config to translate YAML to JSON and have it available to load dynamically (everything originates from my 'src' directory, hence the context):
rules: [{
test: /.\.yaml$/,
use: [{
loader: 'file-loader',
options: {
name: '[path][name].json',
context: 'src'
}
},{
loader: 'yaml-loader'
}]
}]
This will translate my yaml file(s) and export them to my public directory, in this case at '/i18n/en.user.json'.
Now when angular-translate uploads my configured i18n settings via $http on-demand, it already has the parsed YAML and avoids having to parse it with js-yaml (or similar) on the front end.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android - Chronometer setBase() doesn't work properly
I found that if I call start() right after setBase(SystemClock.elapsedRealtime()) it will start counting from 00:00 (which is fine), see below:
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
}
});
However, if I place the setBase(SystemClock.elapsedRealtime()) out of the setOnCLickListener() like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = findViewById(R.id.main_chronometer);
startButton = findViewById(R.id.main_start_button);
resetButton = findViewById(R.id.main_reset_button);
chronometer.setBase(SystemClock.elapsedRealtime()); //no good here
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
}
});
}
It will start counting from the elapsed time since this app launches. Why?
A:
The behavior you describe is caused by the asynchronous nature of user interaction. Your two examples can be broken down as follows:
Calling setBase inside onClick
App launches
UI is configured; click listener is set on button
Time passes...
User clicks button
Chronometer baseline is set to the current time
Chronometer is started
Notice there is no time passing between steps 5 (chronometer baseline is set) and 6 (chronometer is started), which is why the chronometer correctly starts at 0 when you check its value.
Calling setBase inside onCreate and outside onClick
App launches
UI is configured; click listener is set on button
Chronometer baseline is set to the current time
Time passes...
User clicks button
Chronometer is started
In this version, time passes between steps 3 (chronometer baseline is set) and 6 (chronometer is started), which is why the chronometer does not start at 0 when you check its value.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Eclipse is telling me a cycle was detected in the building path, but that's not true!
Eclipse is telling me:
a cycle was detected in the build path of -project name-
, although the structure of the project (created by others in the team) does not have cycles.
The same project is deployed on other machines (the same!) and it doesn't give the error.
I need to work from my machine so I need to solve this.
It is giving me the error in 8 different projects.
It was giving me the error in more (10 projects) but with cleaning and building 10 times just changed to 8! (without any changes in the code).
I really need to get this working and cleaning and building over and over is not doing anything. Any tips?
(note: this is not java, this is flex so i can't change the error to warning :))
Thanks a lot!
A:
If it works on other machines but not your own, it must be a "local cache" effect.
You must have an existing library taken into account from a long time, which causes locally the error, while that same file is not present on the other workstations.
Could try and recreate the projects from scratch, on a new empty directory, and see if the problem persist?
If it does (and only then), the exact version of Eclipse and Flex plugin could help.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove AppV package using Administrator credentials
I am trying to create a script that removes a certain AppV package. The problem I am having is the AppV package is installed under the local user which does not have admin access so I get this message:
"Permission denied"
However, when I run the script as administrator and give my credentials, the AppV package does not show up. Here is the section of code I am using to list and remove the package.
# Remove AppV version of inProcess
$allAppV = Get-AppvClientPackage
If ($allAppV.Count -ge 0) {
$i = 1
#This part lists the packages
Write-Host "List AppV packages"
ForEach($Package in $allAppV) {
Write-Host `t $i - $Package.Name
$i +=
1
}
# Select which package to remove
$NumbertoRemove = Read-Host
"Which one would you like to remove? Type 0 if none"
If ($NumbertoRemove -eq 0) {
Write-Host "Not removing any App-V Client Package"
$Global:More = $False
}
else {
If ($NumbertoRemove -le $allAppV.Count) {
$NumbertoRemove -= 1
Write-Host "Removing package" $allAppV[$NumbertoRemove].Name
$PackageToRemove = $allAppV[$NumbertoRemove]
If ($PackageToRemove.IsPublishedGlobally)
{Unpublish-AppvClientPackage $allAppV[$NumbertoRemove]}
# I need to provide admin credentials for this step
Remove-AppvClientPackage $allAppV[$NumbertoRemove]
Write-Host "AppV Client Package has been removed"
This is what it looks like when I run the script as the local user. If I enter 1 it will try to remover inProcess but gets permission denied error.
If I run as administrator it looks the same except it lists no packages. I imagine because the script is running as administrator so it is listing packages installed under the admin account which their are none.
I need to either run the script as administrator but list the Appv packages of the local user or provide credentials for the remove-AppvClientPackages step. It would be preferable to prompt for credentials to remove the package. Thanks
A:
Use the Get-AppvClientPackage cmdlet with the -All switch, this will list all AppV packages on the computer regardless of the current user. You will still need to run the cmdlet with administrative credentials to uninstall the package.
$allAppV = Get-AppvClientPackage -All
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Straight lines, Combined equation.
Show that the straight lines $(A^2 - 3B^2)x^2 + 8ABxy + (B^2-3A^2)y^2=0$ form with the line $Ax+By+C=0$ is an equilateral triangle of area $C^2/[\sqrt3(A^2 +B^2)]$.
I have no idea how to start\attempt this question. Please, help.
A:
Apply factorization to decompose the line pair into:-
$$ L_1: (A + \sqrt B)x + (B - \sqrt A)y = 0$$ and $$L_2 : (A - \sqrt B)x + (B + \sqrt A)y = 0$$.
Find $m(L_1)$ and $m(L_2)$; where $m(L_1) = - \dfrac {(A + \sqrt B)}{ (B - \sqrt A)}$ and $m(L_2) = …$.
Apply the formula that can find $\theta$, the angle between $L_1$ and $L_2$ using $m(L_1)$ and $m(L_2)$. Should be able to get $\tan \theta = …. = \sqrt 3$ indicating one of the angles formed is $60^0$.
Let $L_3 : Ax + By + C = 0$. Then $m(L_3) = \dfrac {-A}{B}$.
Repeat step 3 to show the angle between $L_1$ and $L_3$ is also $60^0$. The process of proving the triangle formed is equilateral is then complete.
The next part is to prove the area of the triangle thus formed is equal to the given value.
Noting that $L_1$ and $L_2$ intersect at O(0, 0), we can use an alternate (easier) way by finding h instead; where h is the normal distance of $L_3$ from O. Actually, $h = … = | (\dfrac {C}{\sqrt (A^2 + B^2)}|$ is the altitude of the said triangle.
If h is known, the corresponding area can be found because the object is an equilateral triangle.
A:
The angle $\theta$ between the lines $ax^2+2hxy+by^2 = 0$ is given by
\begin{align*}
\tan\theta = \frac{2\sqrt{h^2-ab}}{a+b}
\end{align*}
In this case, we have
\begin{align*}
\tan\theta &= \pm\frac{2\sqrt{16A^2B^2-(A^2-3B^2)(B^2-3A^2)}}{-2(B^2+A^2)}\\
&=\pm \sqrt{3}
\end{align*}
Thus the angles between the lines is $60^\circ$. Also, the angle bisectors of the lines $ax^2+2hxy+by^2 = 0$ are given by
\begin{align*}
\frac{x^2-y^2}{a-b} = \frac{xy}{h}
\end{align*}
Here the angle bisectors are given by
\begin{align*}
\frac{x^2-y^2}{A^2-B^2} = \frac{xy}{AB}
\end{align*}
This can be written as
\begin{align*}
(Ax+By)(Bx-Ay) = 0
\end{align*}
Note that $Ax+By=0$ is parallel to $Ax+By+C=0$ and $Bx-Ay=0$ is perpendicular to it. Thus the angle bisector is perpendicular to the third side and the triangle is isosceles. Since the vertex angle is $60^\circ$, it follows that the triangle is equilateral.
We just need to find the altitude of the triangle to compute the area. This is equal to the perpendicular distance from the origin on $Ax+By+C = 0$ and equals
\begin{align*}
\frac{C}{\sqrt{A^2+B^2}}
\end{align*}
Since the area is $\frac{h^2}{\sqrt{3}}$, it follows that the area is
\begin{align*}
\frac{C^2}{\sqrt{3}(A^2+B^2)}
\end{align*}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Modeling impedance matching network
Background
I'm looking at the RF (LNA_IN) pin of ESP32 as described in esp32_hardware_design_guidelines.
According to this document, the output impedance of the RF pins of ESP32 are (30+j10) or (35+j10) Ω (depends on package), while the antenna impedance is expected to be 50Ω.
It suggests the following π-type matching network:
Now I would like to model (simulate) this circuit to test the impedance matching.
Question 1
To simulate the source output impedance I've added a 30Ω resistor in series to the source. But what would be the best way to model the imaginary part j10?
Question 2
To simulate the antenna impedance I've added a 50Ω resistor. Let's say this is a 50Ω MIFA pcb trace antenna like this one. Does such antenna have an imaginary impedance part and how do I model it?
So I tried this:
simulate this circuit – Schematic created using CircuitLab
Simulating DB(MAG( (V(Out) * I(R1.nA)) / (I(I1.nA) * V(In)) )) on frequency domain:
Question 3
At first glance it more-or-less makes sense (-0.3dB on 2.4Ghz).
What puzzles me is that the result of the simulation is independent of the source impedance value. For example, here I tried to sweep R2 from 0Ω to 100Ω. The graph below looks the same for every value of R2. What am I missing here?
Here is another implementation for the impedance matching circuit I found in another design, probably a "tapped capacitor" matching:
simulate this circuit
Here, a nice 0dB peak on 2.4Ghz, but when sweeping the value of R2 the result remains the same, independent from R2 resistance. So Question 3 applies here too:
Question 4
In general, what would be the considerations for selecting either the π-type or the "tapped capacitor" matching network? The simulation graphs look quite different, I wonder what works best from practical aspects.
A:
(30+j10) is indicating that the pin has some inductance associated with it.
J10 is the inductive reactance at a given frequency. Since no frequency is specified, lets assume it is the operating frequency of 2.4 GHz which gives an inductance of 663 pH.
Your simulation is plotting the power ratio of out/in. This does not include R2 and so is independent of R2. If you move the node labeled In to I1 then you will see an effect of R2.
At these frequencies the parasitic elements of capacitors and inductors are significant, so it would be a good idea to find out what they are and include them in the simulation, or find a spice model for them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Semop: When decreasing a set of semaphores are all decremented at once or does it block on first failure?
So if I have a semaphore set semid with num_of_sems semaphores and a sembuf *deleter_searchers_down
struct sembuf *deleter_searchers_down
= malloc(sizeof (*deleter_searchers_down) * num_of_sems);
for (i = 0; i < num_of_sems; ++i) {
(deleter_searchers_down + i)->sem_op = -1;
(deleter_searchers_down + i)->sem_num = i;
(deleter_searchers_down + i)->sem_flg = SEM_UNDO;
}
semop(semid, deleter_searchers_down, num_of_sems);
The call to semop will attempt to lower all semaphores in the set at once or will it block once it attempts to lower the first semaphore that is 0 and continue after some other process ups that particular semaphore?
A:
No updates happen until all updates can proceed as a unit.
The POSIX specification could be clearer about this point, although it does say that semop is atomic.
On Linux, semop(3) in glibc is a simple wrapper around semop(2). The semop(2) manpage in turn says
The set of operations contained in sops is performed in array order, and atomically, that is, the operations are performed either as a complete unit, or not at all.
The HP-UX semop(2) manpage is even clearer:
Semaphore
array operations are atomic in that none of the semaphore operations
are performed until blocking conditions on all of the semaphores in
the array have been removed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is my 6-year-old son yelling or being very loud when talking?
I have a 6-year-old son. Whenever he talks, he yells. He has had several hearing tests and passes them with flying colors. I do not understand why he tends to yell. Is his behavior normal?
A:
Drawing from experience with my 4 yo and from re-telling from my own childhood by my own mother, it may be that your 6 yo is simply afraid of not being heard?
I know that both my 4yo and my 7yo crank up the volume if I don't answer quickly, in spite of all my best efforts to do so or to teach them some sort of self-control and patience.
Additionally, it may be simply a reaction to his environment or a reproduction of what he sees around him.
You have to put yourself in his context:
he's small,
he's aware he's a child and grown-ups have precedence,
he's oftentimes in noisy surroundings (school playground and class, activities, etc...) where raising his voice gets him heard,
it's what grown-ups do when they want the kids to pay attention.
In what contexts is he yelling?
When talking to you?
To siblings/friends?
To anyone else, e.g. the baker, the postman. the cashier?
To himself during "quiet play"?
I'd expect he does mostly in the first 2 contexts, for either or both of the reasons stated above. If it's in all scenarios, all the time... then I don't know.
Also, though I suppose you've done so already, have you tried:
asking him why he raises his voice,
and asking him to compare his volume to that of the rest of the room?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
bootstrap.php file in CodeIgniter PHP framework?
I am new in php. I am learning Code Igniter (a PHP framework). Can anybody let me know is there any bootstrap.php file in codeIgniter ? And if yes then what it does?
I googled but no luck for bootstrap.php file for CodeIgniter, however i got the bootstrap.php file for Zend and one other framework.
Many Thanks.
A:
application/config
From the question, I'm assuming you would like to know where this file is to add something to it.
The bootstrap file in CakePHP is for additional application settings and setup logic - the equivalent file in Codigniter is probably the application/config/config.php file.
The bootstrap file in Zend contains a class used for initializing the whole application , which by default reads a config.ini file. Depending on specifically what it is you're looking for in "bootstrap.php file in CodeIgniter" - again, the application config files are the CI equivalent of this file's logic/purpose.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to push data from non-AngularJS to AngularJS
I have some data that I am retrieving outside of AngularJS scope. I want to use this data to update the model inside Angular so that it reflects in the views as well, and thereafter work like how Angular should work. How do I push this data in?
A:
Look into Scope.$apply(). From that page:
$apply() is used to execute an expression in angular from outside of
the angular framework.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Eclipse and EGit: how to commit build directories
I'm using Eclipse 3.7 (Indigo) with CDT and EGit 2.0.0. I want to commit build directories (Debug and Release) because they contain makefile, so if I want to compile my project in a host without Eclipse, I can clone the repository, cd to the Release directory and call make all.
My .gitignore is this:
*.o
*.d
Debug/MyApplication
Release/MyApplication
If I call git status from a console, it tells that Debug and Release directories are untracked, so I can call git add ..
From Eclipse, this is impossible: it simply ignore Debug and Release directories.
So... how to force Eclipse to stage these directories? I don't want to call git from command line everytime makefile changes.
A:
Update to EGit 2.1 with the following update site (or use the nightly update site):
http://download.eclipse.org/egit/updates
EGit used to ignore derived resources (e.g. Eclipse build output folders) before 2.1.
In 2.1, this was changed so that it is consistent with Git, see bug 359052. It now only ignores files that are explicitly excluded (e.g. by .gitignore).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Row index's of row belongs to a DataTable along with Sorting
I would like to add one more query to this.. How Can Convert DataRow to DataRowView in c#
DataRowView drv= dt.DefaultView[dt.Rows.IndexOf(dr)];
This is the code which is mentioned there..
Assume a scenario, that a column has sorted and if i try to get the row view based on the row index, it will mismatch..
How could overcome this?
A:
We could use the FindRows method to get the matched rows..
DataRowView drv = dt.DefaultView.FindRows(dr[Regex.Match(dt.DefaultView.Sort, @"\[([^)]*)\]").Groups[1].Value])[0];
In my case, i could take the first value of RowView collection. This is a kind of filtering the dataview with the respective value... and it solves my problem...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Upload image with post -ios
i use this method to save user informations in data base. Can someone help me to upload image too in the same function ?
- (void)Inscription:(NSArray *)value completion:(void (^)( NSString * retour))block{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSArray *Param_header = @[@"username", @"password", @"email",@"first_name", @"last_name"];
// NSArray *Param_value = @[@"ali", @"aliiiiiiii", @"[email protected]",@"ali",@"zzzzz"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:// /Messenger/services/messenger_register"]]];
NSString *aa=[self buildParameterWithPostType:@"User" andParameterHeaders:Param_header ansParameterValues:value];
[request setHTTPBody:[aa dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(@"Server Error : %@", error);
} else {
NSError *error = Nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
block([NSString stringWithFormat:@"%@", [jsonObjects objectForKey:@"message"]]);
}
}
];
}
A:
You can use third-party frameworks like AFN to upload image。
Here is sample code:
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"Jack";
[mgr POST:@"http:// /Messenger/services/messenger_register" parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *file = [[NSBundle mainBundle] pathForResource:@"image.png" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:file];
[formData appendPartWithFileData:data name:@"file" fileName:@"image.png" mimeType:@"mage/png"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"upload success!----%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"upload failed!----%@", error);
}];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reset Password in ASP.NET MVC
I am implementing my own reset password in ASP.NET. In reset password, first I create a random string and mail it to user email.For the link in email like http://xyz.com/account/forgot?random=xxxx&userid=xx.I created a httpget type action forgot which show return a view with input tags for passwords if randomid and userid are validated.
But in httppost type of forgot, I have confusion about the parameters.
I have forgotModel having 2 properties password and confirmpassword.If I just pass forgotmodel to httppost action, then I cannot query user from database.I think I should pass randomId as parameter.But, I am getting how to grab randomID from url of httpget action (If I do so, is it safe?)?
Please guide me, I got stuck..
Thanks in advance
A:
Are you using like Html.BeginForm("action","controller"), If so then you will loose querystring parameters. Since HttpGet and HttpPost methods of ForGotPassword(..) have same action name, You can just use Html.BeginForm().
So, the form will post data to the page url and you will get querystring along with it.
in your http post method you can define like,
[HttpPost]
public ActionResult ForGot(ForgotModel model, string random,strung userid)
{
:
:
}
If you do not want to follow the above approach, then in httpget method write to ViewBag/ViewData and put them as hidden field in view. Then you can receive them as input to Method.
[HttpGet]
public ActionResult ForGot(string random,strung userid)
{
ViewBag.Random =random;
Viewbag.Userid =userid;
:
:
}
[HttpPost]
public ActionResult ForGot(ForgotModel model, string random,strung userid)
{
:
:
}
and , in view
@Html.BeginForm("ForGot","Account"){
:
@Html.Hidden(ViewBag.Random)
@Html.Hidden(ViewBag.Userid)
:
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Data does not get inserted into the table, even though there is no exception
I am trying push the data to a database, using JDBC connection. Here is the schema http://s000.tinyupload.com/?file_id=06524701188448795628. JDBC connection seems fine as I am getting data from another table properly. And I am getting no exception.
Here is the String
String sql = "insert into online_orders_hdr (OOH_ONLINE_REFERENCE_NO, OOH_SERVICE_USER_ID, OOH_ORDER_STATUS," +
"OOH_TOTAL_QUANTITY, OOH_TOTAL_AMOUNT, OOH_PAYMENT_MODE, OOH_SHIPPING_ID, OOH_SHIPPING_NAME, OOH_SHIPPING_ADDRESS1, " +
"OOH_SHIPPING_ADDRESS2, OOH_SHIPPING_PLACE, OOH_SHIPPING_STATE, OOH_SHIPPING_COUNTRY, OOH_SHIPPING_PINCODE, OOH_SHIPPING_MOBILE, "+
"OOH_SHIPPING_PHONE, OOH_SHIPPING_EMAIL, OOH_CUSTOMER_ID, OOH_CUSTOMER_NAME, OOH_CUSTOMER_ADDRESS_LINE1, OOH_CUSTOMER_ADDRESS_LINE2,"+
"OOH_CUSTOMER_CITY, OOH_CUSTOMER_STATE, OOH_CUSTOMER_PINCODE, OOH_CUSTOMER_COUNTRY, OOH_CUSTOMER_MOBILE, OOH_CUSTOMER_EMAIL, "+
"OOH_POS_PUSH_STATUS, OOH_CREATED_AT, OOH_UPDATED_AT, OOH_POS_TIMESTAMP, OOH_ONLINE_PUSH_STATUS, OOH_VENDOR) values "+
"(" + OOH_ONLINE_REFERENCE_NO +","+ OOH_SERVICE_USER_ID +","+ OOH_ORDER_STATUS +","+ OOH_TOTAL_QUANTITY +","+ OOH_TOTAL_AMOUNT +","+
OOH_PAYMENT_MODE +","+ OOH_SHIPPING_ID +","+ OOH_SHIPPING_NAME +","+ OOH_SHIPPING_ADDRESS1 +","+ OOH_SHIPPING_ADDRESS2 +","+ OOH_SHIPPING_PLACE +","+
OOH_SHIPPING_STATE +","+ OOH_SHIPPING_COUNTRY +","+ OOH_SHIPPING_PINCODE +","+ OOH_SHIPPING_MOBILE +","+ OOH_SHIPPING_PHONE +","+ OOH_SHIPPING_EMAIL +","+
OOH_CUSTOMER_ID+","+ OOH_CUSTOMER_NAME +","+ OOH_CUSTOMER_ADDRESS_LINE1 +","+ OOH_CUSTOMER_ADDRESS_LINE2 +","+ OOH_CUSTOMER_CITY +","+ OOH_CUSTOMER_STATE +","+
OOH_CUSTOMER_PINCODE+","+ OOH_CUSTOMER_COUNTRY +","+ OOH_CUSTOMER_MOBILE +","+ OOH_CUSTOMER_EMAIL +","+ OOH_POS_PUSH_STATUS +","+ OOH_CREATED_AT +","+ OOH_UPDATED_AT+","+
OOH_POS_TIMESTAMP+","+ OOH_ONLINE_PUSH_STATUS +","+ OOH_VENDOR + " )";
Here is the SOP of the string
insert into online_orders_hdr (OOH_ONLINE_REFERENCE_NO, OOH_SERVICE_USER_ID, OOH_ORDER_STATUS,OOH_TOTAL_QUANTITY, OOH_TOTAL_AMOUNT, OOH_PAYMENT_MODE, OOH_SHIPPING_ID, OOH_SHIPPING_NAME, OOH_SHIPPING_ADDRESS1, OOH_SHIPPING_ADDRESS2, OOH_SHIPPING_PLACE, OOH_SHIPPING_STATE, OOH_SHIPPING_COUNTRY, OOH_SHIPPING_PINCODE, OOH_SHIPPING_MOBILE, OOH_SHIPPING_PHONE, OOH_SHIPPING_EMAIL, OOH_CUSTOMER_ID, OOH_CUSTOMER_NAME, OOH_CUSTOMER_ADDRESS_LINE1, OOH_CUSTOMER_ADDRESS_LINE2,OOH_CUSTOMER_CITY, OOH_CUSTOMER_STATE, OOH_CUSTOMER_PINCODE, OOH_CUSTOMER_COUNTRY, OOH_CUSTOMER_MOBILE, OOH_CUSTOMER_EMAIL, OOH_POS_PUSH_STATUS, OOH_CREATED_AT, OOH_UPDATED_AT, OOH_POS_TIMESTAMP, OOH_ONLINE_PUSH_STATUS, OOH_VENDOR) values (1262571076,123,pending,1,250.0,COD,11111,22222,sarathy nagar, Velachery,,Chennai,Tamil Nadu,India,600042,7639817688,null,[email protected],33333,Vamsi g,sarathy nagar, Velachery,,Chennai,Tamil Nadu,600042,India,7639817688,[email protected],pending,2015-08-21 06:12:47,2015-08-21 06:13:11,2000-01-01 12:00:00,0,SHOPIFY )
I am using statement.executeUpdate(sql) for execution. // sql String I mentioned above
Here is the logger output
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_ONLINE_REFERENCE_NO -- 1262571076
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SERVICE_USER_ID -- 123
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_ORDER_STATUS -- pending
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_TOTAL_QUANTITY -- 1
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_TOTAL_AMOUNT -- 250.0
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_PAYMENT_MODE -- COD
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_ID -- 11111
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_NAME -- 22222
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_ADDRESS1 -- sarathy nagar, Velachery
9 Sep, 2015 5:26:53 PM Hello getOrders
WARNING: The shipping address2 can fail
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_ADDRESS2--
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_PLACE -- Chennai
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_STATE -- Tamil Nadu
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_COUNTRY -- India
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_PINCODE -- 600042
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_MOBILE -- 7639817688
9 Sep, 2015 5:26:53 PM Hello getOrders
WARNING: This can fail
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_PHONE -- null
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_SHIPPING_EMAIL -- [email protected]
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_ID -- 33333
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_NAME --Vamsi g
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_ADDRESS_LINE1 -- sarathy nagar, Velachery
9 Sep, 2015 5:26:53 PM Hello getOrders
WARNING: This may fail
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_ADDRESS_LINE2 --
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_CITY -- Chennai
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_STATE -- Tamil Nadu
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_PINCODE -- 600042
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_COUNTRY -- India
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_MOBILE -- 7639817688
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_CUSTOMER_EMAIL -- [email protected]
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_POS_PUSH_STATUS -- pending
9 Sep, 2015 5:26:53 PM Hello getOrders
SEVERE: OOH_CREATED_AT -- 2015-08-21 06:12:47
9 Sep, 2015 5:26:53 PM Hello getOrders
SEVERE: OOH_UPDATED_AT -- 2015-08-21 06:13:11
9 Sep, 2015 5:26:53 PM Hello getOrders
SEVERE: OOH_POS_TIMESTAMP -- 2000-01-01 12:00:00
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_ONLINE_PUSH_STATUS -- 0
9 Sep, 2015 5:26:53 PM Hello getOrders
INFO: OOH_VENDOR -- SHOPIFY
Any help will be appreciated.
A:
Your code is vulnerable to SQL injection. Please use prepared statements instead of string concatenation:
// create the string with the insert statement
String sqlInsertString = "insert into online_orders_hdr ( " +
" OOH_ONLINE_REFERENCE_NO, OOH_SERVICE_USER_ID, OOH_ORDER_STATUS, " +
" OOH_TOTAL_QUANTITY, OOH_TOTAL_AMOUNT, OOH_PAYMENT_MODE, " +
" OOH_SHIPPING_ID, OOH_SHIPPING_NAME, OOH_SHIPPING_ADDRESS1, " +
" OOH_SHIPPING_ADDRESS2, OOH_SHIPPING_PLACE, OOH_SHIPPING_STATE, " +
" OOH_SHIPPING_COUNTRY, OOH_SHIPPING_PINCODE, OOH_SHIPPING_MOBILE, " +
" OOH_SHIPPING_PHONE, OOH_SHIPPING_EMAIL, OOH_CUSTOMER_ID, " +
" OOH_CUSTOMER_NAME, OOH_CUSTOMER_ADDRESS_LINE1, " +
" OOH_CUSTOMER_ADDRESS_LINE2, OOH_CUSTOMER_CITY, OOH_CUSTOMER_STATE, " +
" OOH_CUSTOMER_PINCODE, OOH_CUSTOMER_COUNTRY, OOH_CUSTOMER_MOBILE, " +
" OOH_CUSTOMER_EMAIL, OOH_POS_PUSH_STATUS, OOH_CREATED_AT, " +
" OOH_UPDATED_AT, OOH_POS_TIMESTAMP, OOH_ONLINE_PUSH_STATUS, " +
" OOH_VENDOR) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// prepare the statement
PreparedStatement insert = connection.prepareStatement(sqlInsertString);
// populate the statement variables
int i = 0;
insert.setString(++i, OOH_ONLINE_REFERENCE_NO);
insert.setString(++i, OOH_SERVICE_USER_ID);
insert.setString(++i, OOH_ORDER_STATUS);
insert.setString(++i, OOH_TOTAL_QUANTITY);
insert.setString(++i, OOH_TOTAL_AMOUNT);
insert.setString(++i, OOH_PAYMENT_MODE);
insert.setString(++i, OOH_SHIPPING_ID);
insert.setString(++i, OOH_SHIPPING_NAME);
insert.setString(++i, OOH_SHIPPING_ADDRESS1);
insert.setString(++i, OOH_SHIPPING_ADDRESS2);
insert.setString(++i, OOH_SHIPPING_PLACE);
insert.setString(++i, OOH_SHIPPING_STATE);
insert.setString(++i, OOH_SHIPPING_COUNTRY);
insert.setString(++i, OOH_SHIPPING_PINCODE);
insert.setString(++i, OOH_SHIPPING_MOBILE);
insert.setString(++i, OOH_SHIPPING_PHONE);
insert.setString(++i, OOH_SHIPPING_EMAIL);
insert.setString(++i, OOH_CUSTOMER_ID);
insert.setString(++i, OOH_CUSTOMER_NAME);
insert.setString(++i, OOH_CUSTOMER_ADDRESS_LINE1);
insert.setString(++i, OOH_CUSTOMER_ADDRESS_LINE2);
insert.setString(++i, OOH_CUSTOMER_CITY);
insert.setString(++i, OOH_CUSTOMER_STATE);
insert.setString(++i, OOH_CUSTOMER_PINCODE);
insert.setString(++i, OOH_CUSTOMER_COUNTRY);
insert.setString(++i, OOH_CUSTOMER_MOBILE);
insert.setString(++i, OOH_CUSTOMER_EMAIL);
insert.setString(++i, OOH_POS_PUSH_STATUS);
insert.setString(++i, OOH_CREATED_AT);
insert.setString(++i, OOH_UPDATED_AT);
insert.setString(++i, OOH_POS_TIMESTAMP);
insert.setString(++i, OOH_ONLINE_PUSH_STATUS);
insert.setString(++i, OOH_VENDOR);
// execute the insert statement
insert.executeUpdate();
connection.commit();
Of course you have to use the appropriate set...-methods on the PreparedStatement that match the parameter's type.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.htaccess rewrite for removing 2 url segments
I have these URLs that need to be 'rewritten' using .htaccess... The first and last segment need to be removed, so
/articles/marketing-stuff/seo-management/1418/ should
become /marketing-stuff/seo-management/
/articles/command-line/linux-post/2131/ needs to
become /command-line/linux-post/
I have these rewrite rules but they're not working:
RewriteCond %{REQUEST_URI} /articles/marketing-stuff/(.*)/(\d+)/?
RewriteRule ^/articles/marketing-stuff/(.*)/(\d+)/?$ /marketing-stuff/$1/
RewriteCond %{REQUEST_URI} /articles/command-line/(.*)/(\d+)/?
RewriteRule ^/articles/command-line/(.*)/(\d+)/?$ /command-line/$1/
What am I missing?
A:
You can use:
RewriteEngine on
RewriteRule ^articles/(marketing-stuff|command-line)/(.*)/(\d+)/?$ /$1/$2/ [NC,L]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why have humans evolved much more quickly than other animals?
Humans have, in a relatively short amount of time, evolved from apes on the African plains to upright brainiacs with nukes, computers, and space travel.
Meanwhile, a lion is still a lion and a beetle is still a beetle.
Is there a specific reason for this? Do we have a particular part of brain that no other animal has?
A:
This question appears to address at least two distinct concepts:
the "speed" of evolution
whether there is some "end goal" that evolution seeks
I will provide an explanation of each separately below:
The Speed of Evolution
The speed at which a species evolves—that is, the speed at which it acquires new heritable characteristics—can be affected by numerous factors. Among the most obvious which come to mind are:
existing population size
reproductive cycle rate
number of offspring
offspring survival rate
environmental demands
That said, have humans evolved faster than other species?
On the whole, I do not feel that I could say without a doubt that humans have evolved significantly faster than other organisms. Considering the above factors (we have a slow reproductive cycle, few offspring, etc.), it seems unlikely but this is where a zoologist would know better. The answer provided by bobthejoe may provide insight as well.
I would just raise a word of caution before leaping to the conclusion that we have evolved rapidly without looking into it, because while we often study human evolution quite extensively in biology classes and thus are more aware of changes like upright walking and opposable thumbs and increased brain size, that doesn't mean other animals didn't evolve that much as well (we just don't learn about them in as much detail). Being a psychologist and not a zoologist, I do not have the knowledge to say with any surety that other species did not evolve in their own ways to the same magnitude as we have in the last 3-4 million years, so perhaps someone else can help you there.
But you ask whether we have a particular part of our brain that no other animal has; the answer to this is no, but the parts of our brains which we do share with animals are often much larger than as seen in those other species.
The "Goal" of evolution
I would like to point out here that human technology has nothing to do with evolution. Not only have all of our notable technological achievements occurred in the last couple hundreds years when human evolution was at its slowest (early human evolution as we know it today dates back at least 5-7 million years, and it was during this several million year period when all the genetic evolution you speak of happened), I would argue that human spaceships and computers are no more sophisticated to us than a mushroom garden and ventilation system are to a termite. I could be wrong here but it seems as if you are under the impression that evolution is striving towards something... That humans are somehow intrinsically better than lions or sharks or beetles. On the contrary, each of these creatures is not significantly more or less adapted to their environments as we are to our own, and in many ways these creatures possess features which are beyond our own.
I shall leave you with one of my favorite quotes:
"We need a wiser and perhaps a more mystical concept of animals. We
patronize them for their incompleteness, for their tragic fate having
taken form so far below ourselves. And therein we err, and greatly
err. For the animal shall not be measured by man. In a world older and
more complete than ours, they move finished and complete, gifted with
extensions of the senses we have lost or never attained, living by
voices we shall never hear. They are not brethren, they are not
underlings. They are other nations caught with ourselves in the net of
life and time, fellow prisoners of the splendor and travail of the
earth."
–Henry Beston, in The Outermost House
I don't have a dog in this fight, and I could very well be falsely assuming that you think this particular way when you in fact don't (you only wrote 4 lines after all, it's hard to glean much from that), but I wanted to make sure that these concepts were clear either way, particularly for any future visitors who might get the wrong impression. :)
A:
We have the Human Accelerated Regions (HARs) which are some of the most rapidly evolving RNA genes elements. While heavily conserved in vertebrates, they go haywire in humans and are linked with neurodevelopment.
Thanks to @Nico, the following paper compares the human genome with that of the chimp and identifies genetic regions that show accelerated evolution. The most extreme, HAR1 is expressed mainly in Cajal-Retzius neuron cells which hints at its important role in human development.
Pollard KS, Salama SR, Lambert N, Lambot M-A, Coppens S, Pedersen JS, Katzman S, King B, Onodera C, Siepel A, et al.. 2006. An RNA gene expressed during cortical development evolved rapidly in humans. Nature 443: 167–72.
A:
It seems to me that humans have, in a relatively short amount of time evolved from apes on the African plains to upright brainiacs with nukes, computers, and space travel.
The question covers changes of two sorts: biological evolution and cultural evolution. The other answers speak to biological evolution, but I want to point out that much of the most striking changes ("nukes, computers...") are due to the evolution of our culture.
By 40,000 years ago most of our biological evolution to the present had happened (perhaps the most notable exception being changes related to our coevolution with disease organisms). Yet although we had achieved upright brainiac-hood by the apparent evidence, we were not strikingly different from other large animals.
We had sharpened rocks and sticks, and made better use of the surroundings, particularly in non-food categories, than other animals. We had been successful enough to spread throughout much of the old world. Nevertheless, the overall contrast with other animals seems rather muted when viewed by the differences with the modern world.
Most of the visible changes since then are due to evolution happening outside our genes and bodies in what can be called culture. Other animals have culture but our nature gives us many times the cultural capability. We build upon the culture we find ourselves in and make it more effective. The cultural presevation and advances come not just from aping ('monkey see, monkey do'), but from language, and from mechanisms of cultural distribution and preservation, most notably from the invention of written language. These things have driven the cultural evolution of the largest visible changes, those of the last few millenia.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
permanent terminal with root
Is it bad to have at all times (one) terminal logged in as root? If so, why?
(I leave the window with root terminal usually opened because it's much more comfortable than writing sudo before everything what needs root.)
Just to clarify that this isn't a duplicate question as suggested by system, I'm not talking about running the whole account as root, just one terminal window.
Thank you.
P.S.: sorry for the non-descriptive heading, I for love nor money couldn't think off sth that made more sense.
P.P.S.: This does not mean I'm performing the usual tasks (copying, running normal programs...) as root.
Ok, the main question came up later after posting this - what is the technical difference between executing command as $ sudo command and executing it as # command ?
To clarify:
I wanted to write into file /sys/devices/platform/asus-nb-wmi/leds/asus::kbd_backlight/brightness directly. It containes only a number with level of KB backlight.
This failes:
edison23@edison23-N56VM:/sys/devices/platform/asus-nb-wmi/leds/asus::kbd_backlight$ sudo echo 3 > brightness
bash: brightness: Permission denied
This succeeds
root@edison23-N56VM:/sys/devices/platform/asus-nb-wmi/leds/asus::kbd_backlight# echo 3 > brightness
Why?
Thanks
A:
Is it bad to have at all times (one) terminal logged in as root? If so, why?
Yes. Well. The idea of logging out your root terminal is due to the fact that Linux is a multi-user system. So other users could walk to your terminal and issue commands you do not want them to issue. With the introduction of desktops (that are often single user) this is less of an issue.
The 2nd issue is that some files depend on the user being the owner of files. If you touch those as root they will be saved for the user root and you can lock yourself out of the desktop. We have several questions about that on Ask Ubuntu.
But besides that: Ubuntu does not use root. We use "sudo" and (by default) you have to supply the "sudo" password every 15 minutes. So there is no need for "root". No need at all. Learn to live with the way Ubuntu does it. It has proven it works over the past decade or so.
But... It is your system. It is your data. If you believe you need "root" go for it. Most of us will not. When you mess up it is on your head (but that is also doable using "sudo" ;) ).
Make regular backups. Check that you can restore backups. And you should always be able to restore your system.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
probability P(A and B)
I have difficult to understand the following rule. Can anyone use a simple example to explain the rule to me? Thanks.
If A and B are any two events, then $P(A \cap B) = P(B)\cdot P(A| B)=P(A)\cdot P(B|A)$, where P(B|A) is the probability of B happening under the condition of event A.
A:
The Kolmogorov definition of conditional probability is
$$ P(B|A) = \frac{P(B \cap A)}{P(A)}
$$
so rearranging gives $P(B|A) P(A) = P(B \cap A)$.
A:
Conditional probabilities are especially useful when it comes to things that involve having to pick things without replacement.
Consider a game of blackjack and you want to calculate the probability that you're dealt two aces. (We can assume for simplicity that we are only dealing with a single deck of 52 cards and that the first two cards in the deck are dealt to us). If we let $A$ be the event that the first card is an ace and let $B$ be the event that the second card is an ace, then it is clear that we want to find $P(A \text{ and } B)$.
Using the definition of conditional probability, we find,
$$P(A \text{ and } B) = P(A)P(B|A) = P(\text{first card is an ace})P(\text{second card is an ace given the first card is an ace)} $$$$= \frac{4}{52}\cdot \frac{3}{51} = \frac{1}{221}.$$
We have that $P(A)$ is $\frac{4}{52}$ since there are 4 aces in a 52 card deck and $P(B|A) = \frac{3}{51}$ because after the first ace is drawn, there are 3 aces amongst the 51 cards remaining.
A:
If $\mathbb{P}[A]=0$ then clearly we would like $\mathbb{P}[A \cap B]=0$ and this is the case.
Now if $\mathbb{P}[A]\neq0$ then this is equivalent to
$$
\mathbb{P}[B|A] = \frac{\mathbb{P}[A \cap B]}{\mathbb{P}[A]}
$$
The right-hand side is a definition of $\mathbb{P}[B|A]$, that is, the probability of $B$ knowing $A$. It makes sense because it basically restricts the sample space to $A$.
Simple example: We throw a dice twice.
There are $36$ possible equiprobable outcomes, say $(a,b)$ with $1\leq a,b\leq 6$.
What is the probability of obtaining at least one $6$ knowing that the sum of the two throws is $8$ ?
Answer: There are $5$ outcomes for which the sum of the two throws is $8$. They are
$$
(2,6),(3,5),(4,4),(5,3),(6,2)
$$
Of those $5$ outcomes, there are $2$ for which there is a $6$ : $(2,6)$ and $(6,2)$. Hence, reasonably, the probability should be $2/5$.
This example motivates the above definition.
Indeed, if you call $B$ the event "obtaining at least one $6$" and $A$ the event "the sum of the two throws is $8$" then we see that
$$
A \cap B = \{(2,6),(6,2)\}
$$
and our answer $2/5$ can be written in the form
$$
\frac{2}{5} = \frac{2/36}{5/36} = \frac{\mathbb{P}[A\cap B]}{\mathbb{P}[A]}
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Efficient daemon in Vala
i'd like to make a daemon in Vala which only executes a task every X seconds.
I was wondering which would be the best way:
Thread.usleep() or Posix.sleep()
GLib.MainLoop + GLib.Timeout
other?
I don't want it to eat too many resources when it's doing nothing..
A:
If you spend your time sleeping in a system call, there's won't be any appreciable difference from a performance perspective. That said, it probably makes sense to use the MainLoop approach for two reasons:
You're going to need to setup signal handlers so that your daemon can die instantaneously when it is given SIGTERM. If you call quit on your main loop by binding SIGTERM via Posix.signal, that's probably going to be a more readable piece of code than checking that the sleep was successful.
If you ever decide to add complexity, the MainLoop will make it more straight forward.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Single-word noun for something changing width
I'm looking for a noun to describe the situation where something is changing width. Have a look at this hypothetical window frame:
Window Frame with Two Panes of Uneven Height
The bottom part of the frame changes width across the window. What might I call the category of windows where this occurs?
I have thought about "widening," but am not overly fond of it, since it might go from wide to narrow, or you could even have a situation with more panes, where it is wide-narrow-wide. Any ideas?
A:
Window frames could be of uniform cross-section or rarely, with a change in width half-way.
Such an abrupt change in width is usually called a "step" and a member with its section having one or more such "steps" may be called a "stepped section".
For a visualization, consider the case of a "stepped beam" (Chegg via Google).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to create watermark in PDF
I have a program where I am generating a money receipt for some organization. I need to add a waterark in the document as for some sort of security. I am adding my code below. My PDF has been generating OK but how to add the watermark?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.example;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
*
* @author Chandan
*/
public class MoneryRecipt {
// Document m_PdfDocument;
public static void main(String[] args) throws DocumentException, FileNotFoundException
{
Document m_PdfDocument = new Document(PageSize.LETTER, 5, 5, 5, 5);
try
{
DocWriter m_DocWriter;
// PdfWriter m_PdfWriter = null;
PdfWriter writer = PdfWriter.getInstance(m_PdfDocument, new FileOutputStream("E:/aa.pdf"));
Image logo=Image.getInstance("F:/gmc_report.jpg");
m_PdfDocument.open();
Image background = Image.getInstance(logo);
background.setAbsolutePosition(200, 400);
// Phrase watermarkdd = new Phrase("Chandan Sarma", new Font(FontFactory.getFont(FontFactory.HELVETICA, 20,Font.NORMAL,new Color(240,240,240))));
PdfContentByte canvas = writer.getDirectContentUnder();
PdfContentByte addWaterMark;
addWaterMark=writer.getDirectContentUnder();
addWaterMark.addImage(logo);
PdfPTable maintable = new PdfPTable(2);
PdfPCell spece = new PdfPCell();
spece.setBorder(0);
spece.setColspan(2);
spece.setFixedHeight(20f);
spece.setSpaceCharRatio(20f);
maintable.addCell(spece);
Image logo=Image.getInstance("D:/logo_gmcmanin.png");
Paragraph ph = new Paragraph();
ph.add(new Chunk(logo, 0, 0));
ph.add(new Chunk("\n\nGuwahati Municipal Corporation", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLDITALIC)));
ph.add(new Chunk("\n\nMoney recipt", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLD)));
PdfPCell heading = new PdfPCell(ph);
// heading.setBorder(1);
heading.setColspan(2);
heading.setHorizontalAlignment(Element.ALIGN_CENTER);
heading.setVerticalAlignment(Element.ALIGN_CENTER);
maintable.addCell(heading);
Paragraph ph2 = new Paragraph();
ph2.add(new Chunk("\nPayment Receipt / Acknowledgment for Property Tax Bill of the ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLDITALIC)));
ph2.add(new Chunk("\n\nFinancial Year 2014-15", FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLD)));
PdfPCell reciptHeading = new PdfPCell(ph2);
// heading.setBorder(1);
reciptHeading.setColspan(2);
reciptHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
reciptHeading.setVerticalAlignment(Element.ALIGN_CENTER);
maintable.addCell(reciptHeading);
Paragraph ph3 = new Paragraph();
ph3.add(new Chunk("Receipt No ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
ph3.add(new Chunk(" 2014-15", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
PdfPCell reciptCell=new PdfPCell(ph3);
//reciptCell.setBorder(0);
//reciptCell.setBorderWidthLeft(1);
reciptCell.setBorderWidthBottom(0);
reciptCell.setBorderWidthTop(0);
reciptCell.setBorderWidthRight(0);
reciptCell.setColspan(1);
reciptCell.setHorizontalAlignment(Element.ALIGN_CENTER);
reciptCell.setVerticalAlignment(Element.ALIGN_CENTER);
maintable.addCell(reciptCell);
Paragraph ph4 = new Paragraph();
ph4.add(new Chunk("Date ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
ph4.add(new Chunk("2014-15", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
PdfPCell dateCell=new PdfPCell(ph4);
dateCell.setFixedHeight(20);
//dateCell.setBorder(0);
dateCell.setBorderWidthLeft(0);
dateCell.setColspan(1);
dateCell.setBorderWidthTop(0);
dateCell.setBorderWidthBottom(0);
dateCell.setHorizontalAlignment(Element.ALIGN_CENTER);
dateCell.setVerticalAlignment(Element.ALIGN_CENTER);
maintable.addCell(dateCell);
PdfPCell details = new PdfPCell();
//details.setBorder(0);
details.setColspan(2);
PdfPTable detailsTable = new PdfPTable(2);
detailsTable.setWidthPercentage(65);
PdfPCell ownerCell=new PdfPCell(new Phrase("Owner’s Name ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
ownerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
detailsTable.addCell(ownerCell);
PdfPCell ownernameCell=new PdfPCell(new Phrase("Chandan Sarma ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
ownernameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
detailsTable.addCell(ownernameCell);
PdfPCell assementIdOldCell=new PdfPCell(new Phrase("Assessment id (old) ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
assementIdOldCell.setHorizontalAlignment(Element.ALIGN_LEFT);
detailsTable.addCell(assementIdOldCell);
PdfPCell assementIdValueCell=new PdfPCell(new Phrase("27-05-7859 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
assementIdValueCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
detailsTable.addCell(assementIdValueCell);
PdfPCell assementIdNewCell=new PdfPCell(new Phrase("Assessment id (New) ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
assementIdOldCell.setHorizontalAlignment(Element.ALIGN_LEFT);
detailsTable.addCell(assementIdOldCell);
PdfPCell assementIdNewValueCell=new PdfPCell(new Phrase("225642 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL)));
assementIdNewValueCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
detailsTable.addCell(assementIdNewValueCell);
details.setBorderWidthTop(0);
details.setBorderWidthBottom(0);
details.addElement(detailsTable);
maintable.addCell(details);
Paragraph ph6=new Paragraph();
ph6.add(new Chunk("HOUSEHOLD WASTE COLLECTION ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.BOLDITALIC,Color.RED)));
ph6.add(new Chunk("\n\nWard-wise contact number of NGOs for collecting household waste from your doorstep:- ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph6.add(new Chunk("\n\nWard No. 1- 9957047867 Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph6.add(new Chunk("\n\nWard No. 1- 9957047867 Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph6.add(new Chunk("\n\nWard No. 1- 9957047867 Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph6.add(new Chunk("\n\nWard No. 1- 9957047867 Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph6.add(new Chunk("\n\nWard No. 1- 9957047867 Ward No. 17- 9864623744", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
PdfPCell wasteCollectionHeader=new PdfPCell(ph6);
wasteCollectionHeader.setColspan(1);
wasteCollectionHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
maintable.addCell(wasteCollectionHeader);
Paragraph ph7=new Paragraph();
ph7.add(new Chunk("PROPERTY TAX RELATED GRIEVANCE REDRESSAL MECHANISM ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.BOLDITALIC,Color.RED)));
ph7.add(new Chunk("\n\nFor billing or any service grievance, please approach (during office hours) ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph7.add(new Chunk("\n\n •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph7.add(new Chunk("\n\n •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph7.add(new Chunk("\n\n •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph7.add(new Chunk("\n\n •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
ph7.add(new Chunk("\n\n •Deputy Commissioner, East Zone, GMC, Bhaya Mama Path, RG Baruah Road, Mobile No: 07399092259 ", FontFactory.getFont(FontFactory.TIMES_ROMAN, 6)));
PdfPCell propertyTexRelatedHeader=new PdfPCell(ph7);
propertyTexRelatedHeader.setColspan(1);
propertyTexRelatedHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
maintable.addCell(propertyTexRelatedHeader);
m_PdfDocument.add(maintable);
m_PdfDocument.newPage();
m_PdfDocument.setPageSize(m_PdfDocument.getPageSize());
m_PdfDocument.close();
}
catch(Exception e)
{
System.out.println("Exception is"+e.toString());
}
}
}
A:
I have solve it by using the following code which have generated the water mark
class PDFBackground extends PdfPageEventHelper {
@Override
public void onEndPage(PdfWriter writer, Document document) {
try {
Image background = Image.getInstance("F:/gmc_report.jpg");
background.setAbsolutePosition(250, 500);
// This scales the image to the page,
// use the image's width & height if you don't want to scale.
float width = document.getPageSize().getWidth();
float height = document.getPageSize().getHeight();
writer.getDirectContentUnder().addImage(background, false);
} catch (DocumentException ex) {
Logger.getLogger(MoneryRecipt.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(MoneryRecipt.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MoneryRecipt.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and write the image in your pdf by
PdfWriter writer = PdfWriter.getInstance(m_PdfDocument, new FileOutputStream("E:/aa.pdf"));
writer.setPageEvent(new PDFBackground());
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cakephp Uploaded on a subdirectory is giving issues
I just completed a cakephp project with cake 2.x locally , every thing works perfectly.
Now, I moved it online and uploaded to a sub directory, http://doubleedgetechnologies.com.ng/unlimitedgrace/
but below is the error I am getting, I know is .htaccess issue, I have struggled with it for over 3 hours all to no avail.
Please help me out.
Thanks
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, [email protected] and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
A:
I have moved it to another server, and it works perfectly there.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to write a query to control a datasheet subform's combobox based on a linked table?
I would like my users to select from a pre-defined project list combobox in a subform. The easy way would be to use lookup fields, but I've been told to avoid those like poison. To provide context, I have two linked tables, one for User Entry, and one that stores projects.
User Entry Table
PK ProjectFK Projected Hours Actual Hours
1 1 15 13
2 3 12 14
3 4 13 13
Project List Table
PK ProjectName
1 Caterpillar
2 Omaha
3 Dilly
4 Holdout
On a separate main form, the User Entry Table serves as a datasheet subform where users select which projects they're working on, and how many hours they spend on them. Rather than having users select the project by foreign key, I was hoping the users could select the project by Project Name located in the linked table.
I'm having trouble experimenting/visualizing this process. Does it involve a query, and if so, how should I go about it?
Thank you for your help!
A:
I might have figured it out - I created a query based off the Project List Table, incorporating every field. Afterward in my User Entry Subform, I created a combobox control with the User Entry's foreign key as its control source, and the query as its row source. Linking the correct control source was what was throwing me off.
Hope this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mysql: how to Calculating the difference between two avg?
I have a table:
+------------+--------------+-------+------------+
| Name | Nation | Score | Game_date |
+------------+--------------+-------+------------+
| Ginobili | Argentina | 48 | 2005-01-21 |
| Irving | Australia | 44 | 2014-04-06 |
| Kirilenko | Soviet Union | 31 | 2006-11-11 |
| Kobe | USA | 81 | 2006-01-22 |
| LeBron | USA | 52 | 2014-12-06 |
| Mutombo | Congo | 39 | 1992-02-03 |
| Nowitzki | Germany | 48 | 2011-05-18 |
| PauGasol | Spain | 46 | 2015-01-11 |
| SteveNash | Canada | 42 | 2006-12-08 |
| TonyParker | France | 55 | 2008-11-06 |
| YaoMing | China | 41 | 2009-02-23 |
| YiJianlina | China | 31 | 2010-03-27 |
+------------+--------------+-------+------------+
I want to calculate the avg(score) of USA - avg(score) of China.
I have tried
select avg(score) from nba where nation = "USA" -
avg(score) from nba where nation = "China";
But it is wrong!
A:
You can use AVG and CASE WHEN:
SELECT AVG(CASE WHEN nation = 'USA' THEN score END) -
AVG(CASE WHEN nation = 'China' THEN score END) AS result
FROM nba
WHERE nation IN ('USA', 'China');
Another option is to use UNION:
SELECT SUM(sub.r) AS result
FROM ( SELECT avg(score) AS r
from nba
where nation = 'USA'
UNION ALL
SELECT -avg(score)
from nba
where nation = 'China') AS sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Printing to a Local Shared Printer When the Network is down
I have some legacy application logic that sends files to an attached printer using a DOS copy command:
copy fileToPrint \myLocalComputerName\printerShareName
The problem is that even though the application is running on the computer that's physically attached to the printer since it's using a network "share" it requires the network be available. If the network isn't available DOS throws a network unavailable error.
How can I code this so I don't have the network dependency? (preferably without re-architecting the entire file based print logic)
A:
Found the following article which uses a loopback network adapter to access the local share when the network is unavailable.
http://geekswithblogs.net/dtotzke/articles/26204.aspx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Programming language with arbitrary but fixed precision integers?
Are there any programming languages out there that support n-bit integer types for arbitrary n as primitives? That is, is there a language where I could write something to the effect of
int[137 bits] n = 0;
Note that this isn't the same as asking if there's a language with arbitrary-precision integers in them. I'm looking specifically for something where I can have fixed-precision integers for any particular fixed precision I'd like.
A:
Verilog would express that as reg [136:0] n. Hardware description languages (HDL) all give you similar capabilities. You can use Verilog as a scripting language as well, but that's not really its design center and won't give you the performance you could get with a BigInt style integer in a regular programming language.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If match error when a value does not match
I currently have this:
=IF(MATCH("Example",D:D,0),"Not Available","Available"). The problem is that if the value isn't in the column, it gives the #N/A error. How do I make that go away? I have read several similar problems that might have had the solution but couldn't make sense of it.
A:
Although I've commented it out, here's the formal answer to the question.
The reason why your function is throwing up an #N/A error value is because
the logical part of your IF statement cannont handle values other than Bolean (true or false).
When MATCH returns an ERROR, the logical part of IF statement was not satisfied
thus returning #N/A error.
To correct this, we add ISERROR on your IF statement like this:
=IF(ISERROR(MATCH("Example",D:D,0)),"Not Available","Available")
ISERROR evaluates if the function or statement returns an ERROR.
It returns TRUE if it is an ERROR and FALSE otherwise.
Adding that to your code let's your IF statement evaluates the result of MATCH function when it returns an ERROR.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How should a view controller abort loading / dismiss itself?
I have a view controller which contains a table view, and which is wrapped within a navigation controller, i.e. in the app delegate these two are created and set as:
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.myViewController];
self.window.rootViewController = navController;
If the user clicks on a row within a table then another view controller is created and pushed to the navigation controller's stack:
[self.navigationController pushViewController:webPageController animated:YES];
The webPageController loads and reads local files. If a file is missing I want to abort the loading of the webPageController and the displaying of its view and have the table view displayed.
How should I achieve this?
If the webPageController detects a problem I've tried experimenting with it calling various things such as:
[self.navigationController popViewControllerAnimated:YES];
or
[self.navigationController.navigationBar popNavigationItemAnimated:YES];
To pop itself off the navigation stack, however these aren't working, is it wrong for a navigation controller to attempt to pop itself like this? What is the canonical way of implementing this?
Thanks
A:
That should be fine. Where are you calling popViewControllerAnimated:? If you're calling before viewDidAppear, you'll likely run into problems. ViewControllers need to finish the appearing and disappearing before they can make any kind of pop or push to their stack. If you do it before, you get really weird results. The most common symptom of this is it doesn't work. Often buttons inside it will get messed up as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ember-simple-auth prevent session invalidation on 401 reponse
I am using
Ember: 2.11.0, ember-simple-auth: 1.2.0
I use the ember-simple-auth to authenticate my application via oauth2 to my REST API.
The standard behaviour of ember-simple-auth is to invalidate the users session if the server responds with a 401 status code.
I want to handle this different and try to override this:
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DS.RESTAdapter.extend(DataAdapterMixin, {
host: 'http://localhost:3000',
authorizer: 'authorizer:oauth2',
/*
* The DataAdapterMixin invalidetes the session automatically if the server
* returns the status 401. We don't want this behaviour, so we override
* the handleResponse method.
*/
handleResponse(status) {
console.log(status);
return this._super(...arguments);
}
});
In my RestAdapter I Use the DataAdapterMixin which triggers the invalidation within the handleResponse method.
So I tried to override this method in my adapter. My method is called but after my method finished, the mixins method is called by ember, as you can see here:
The Comments for the Ember superWrapper method state, that it is made to handle calls to methods of the super class and redirect them to it, but somehow it seems to redirect it to the mixin.
I have no idea why this happens. This could probably be fixed by editing the DataAdapterMixin directly, but think that wouldn't be a good idea in terms of compatibility with future versions of ember-simple-auth
I would really appreciate if someone could point me into the right direction to make the override work.
A:
When you extend adapter from mixin, this._super(...arguments); will call method of the mixin (if it has such method). That's why your override doesn't work. You have following options:
Look into ember-data source and copy handleResponse code from DS.RESTAdapter (start from here). No this._super call - no influence from mixin. This can be not so easy as it sounds and may be not compatible with future versions of ember data
Create your own DataAdapterMixin by copying code from ember-simple-auth and removing/modifying it's handleResponse method. This can be not compatible with future versions of ember-simpe-auth.
Modify arguments before calling this._super(...arguments), so status will be 400 instead of 401:
handleResponse: function (status) {
/**
* Modify status
*/
if (status === 401) {
status = 400;
}
/**
* Replace status in arguments.
*/
var args = Array.prototype.slice.call(arguments, 0);
args.splice(0, 1, status);
/**
* Call parent's method
*/
return this._super(...args);
}
This method is compatible with future versions - even if new argument will be added (at the moment arguments are status, headers, payload), this code will work. It will stop to work if status will not be the first argument anymore (I don't think this will happen in near future).
But I want also to say that something is probably not right with your backend: 401 means "unathorized" and ember-simple-auth does what should be done in this case - invalidates session. If you need special status for some cases, I'd suggest to use 418 (I'm a teapot).
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.