text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Dealing with single quotes in excel vba sql queries I am using excel sql queries to fetch data from the backend according to the selection i make in a dropdown box.However my sql queries are not working in cases where there is a single quote(') in the dropdown box value. For example-- Men's Wear . Please suggest me a way to deal with this problem
SQL = "select Segment,Weeks,Value from [Category performance data$] where Departments='" & Sheet3.Range("Dept_name").Value & _
"' and Metric ='Total Spend' group by Segment,Weeks,Value"
Call execQry
A: Departments='" & replace(Sheet3.Range("Dept_name").Value, "'", "''") & _ "' and Metric
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13134070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Encrypting data at rest protect me against what type of attack? Encrypt data at rest is one of the major 101 of security for a lot of compliance (if not all of them). I am however not sure I understand against which attack this protect me.
Let say I am in AWS cloud. I encrypt my S3 data at rest using KMS provided service.
The protection I get is, if someone get access to AWS network and were able to access the data, it would get encrypted data. So basically, I am encrypting my data in case AWS is getting hacked. Now as unlikely it is, I understand the value.
Is there another kind of attack possible that encrypting data protecting me against?
A: Somebody could get access to a resource via a misconfigured IAM role for example. This is especially relevant for S3, where public access might sometimes be configured inadvertently. If you have encryption via KMS, access to the key would also have to be granted, which provides an additional layer of security, and something you can monitor and alert on easily. This also applies to your own components, some of which will be granted access to the KMS key, but others (like a frontend server) might not, because they don't need it, and you want to implement the least privilege principle to limit the impact of a potential breach. Of course you will not only rely on key access to implement access control to your resources, but it provides a single point where rules and actual access can easily be enforced and audited.
Also think about backups and disposed media. Maybe more usual to consider this when you host stuff yourself, but it is still relevant for public clouds. You probably trust AWS to manage backups and disposed media securely, but while they're pretty good at it, they might not be perfect, and you have zero control. If you store your data encrypted, there is no way for it to be recovered from a dumpster.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72790958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Angular 2+ routage basic Complete a simple Angular component named MenuDisplayComponent having menu-display-component as selector.
Complete the declaration of the appRoutes variable.
The component must contain two elements. They symbolize a menu of the application:
When we click on the element with id="menu1" the component associated with the /menu1 route should be loaded.
When the element with id="menu2" is clicked the component associated with the /menu2 route must be loaded.
Initially, neither component is loaded.
You must create the corresponding routes in appRoutes. Menu1Component corresponds to the menu1 path, Menu2Component corresponds to the menu2 path.
You only need to update MenuDisplayComponent (+ its template) and appRoutes.
import { Component, Input, NgModule } from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
@Component({
selector:'menu1-component',
template: `
<div id="menuComp">You are at menu 1.</div>
`
})
export class Menu1Component {
}
@Component({
selector:'menu2-component2',
template: `
<div id="menuComp">You are at menu 2.</div>
`
})
export class Menu2Component {
}
@Component({
selector:'menu-display-component',
template: `
<div id="menuComp">You are at menu 2.</div>
<a id="menu1" routerLink="/menu1"></a>
<a id="menu2" routerLink="/menu2"></a>
`
})
export class MenuDisplayComponent {
}
export const appRoutes:Routes = [
{path:"menu1",component:Menu1Component},
{path:"menu2",component:Menu2Component}
];
// #region Preview
@Component({
template: `
<menu-display-component></menu-display-component>
`
})
export class PreviewComponent { }
// #endregion Preview
// #region Module declaration - Do not Change
@NgModule({
imports: [RouterModule.forRoot(appRoutes, {useHash: true})],
exports: [RouterModule]
})
export class AppRoutingModule {
}
@NgModule({
imports: [
RouterModule,
AppRoutingModule
],
declarations: [PreviewComponent, Menu1Component, Menu2Component, MenuDisplayComponent],
entryComponents: [PreviewComponent],
providers: [{provide: APP_BASE_HREF, useValue : '/'}]
})
export class PreviewModule { }
// #endregion Module declaration
A: One way you can do this is using children routes. This will help you load components inside of another component. You will need to add the router outlet tag inside the parent component for this to work. Let me know if that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70034326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to add custom view on DefaultTimeBar in ExoPlayer Need to add custom views on the DefaultTimeBar in Exoplayer at particular timestamps to indicate that there is something which is coming up during the video play similar to what we have in terms of video ads.
Please find the attached image to understand the exact requirement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71264170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Split a pair of strings in bracket using python I want to split the following data into two columns, latitude and longitude and put them in a dataframe.
0 (45.349586099999996, -75.81031967988278)
1 (-37.77922725, 175.2010323246593)
2 (-42.9945669, 170.7100413)
3 (-39.2711067, 174.154795)
4 (51.2800275, 1.0802533)
5 (-41.30222105, 172.89453190955697)
6 (-35.3712702, 173.7405337)
7 (-45.7255555, 168.2936808)
8 (-40.3284102, 175.8190684)
9 (-45.1299859, 169.5248818)
10 (-37.9503756, 176.93828736155422)
Can anyone help me please?
A: Another way:
data='''a b
0 (45.349586099999996, -75.81031967988278)
1 (-37.77922725, 175.2010323246593)
2 (-42.9945669, 170.7100413)
3 (-39.2711067, 174.154795)
4 (51.2800275, 1.0802533)
5 (-41.30222105, 172.89453190955697)
6 (-35.3712702, 173.7405337)
7 (-45.7255555, 168.2936808)
8 (-40.3284102, 175.8190684)
9 (-45.1299859, 169.5248818)
10 (-37.9503756, 176.93828736155422)'''
df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python')
df[['lat', 'lon']] = df.b.str[1:-1].str.split(',', expand=True)
a b lat lon
0 0 (45.349586099999996, -75.81031967988278) 45.349586099999996 -75.81031967988278
1 1 (-37.77922725, 175.2010323246593) -37.77922725 175.2010323246593
2 2 (-42.9945669, 170.7100413) -42.9945669 170.7100413
3 3 (-39.2711067, 174.154795) -39.2711067 174.154795
4 4 (51.2800275, 1.0802533) 51.2800275 1.0802533
5 5 (-41.30222105, 172.89453190955697) -41.30222105 172.89453190955697
6 6 (-35.3712702, 173.7405337) -35.3712702 173.7405337
7 7 (-45.7255555, 168.2936808) -45.7255555 168.2936808
8 8 (-40.3284102, 175.8190684) -40.3284102 175.8190684
9 9 (-45.1299859, 169.5248818) -45.1299859 169.5248818
10 10 (-37.9503756, 176.93828736155422) -37.9503756 176.93828736155422
A: Data
Position
0 (45.349586099999996,-75.81031967988278)
1 (-37.77922725,175.2010323246593)
2 (-42.9945669,170.7100413)
3 (-39.2711067,174.154795)
4 (51.2800275,1.0802533)
5 (-41.30222105,172.89453190955697)
6 (-35.3712702,173.7405337)
7 (-45.7255555,168.2936808)
8 (-40.3284102,175.8190684)
9 (-45.1299859,169.5248818)
10 (-37.9503756,176.93828736155422)
Solution
#Strip of the brackets if column is string and not tuple.
#str.split column to make it a list
#stack it to dataframe it
pd.DataFrame(np.vstack(df['Position'].str.strip('\(\)').str.split(',')), columns=['Lat','Long'])
Lat Long
0 45.349586099999996 -75.81031967988278
1 -37.77922725 175.2010323246593
2 -42.9945669 170.7100413
3 -39.2711067 174.154795
4 51.2800275 1.0802533
5 -41.30222105 172.89453190955697
6 -35.3712702 173.7405337
7 -45.7255555 168.2936808
8 -40.3284102 175.8190684
9 -45.1299859 169.5248818
10 -37.9503756 176.93828736155422
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67813808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing Multidimensional array with variable size Passing dimensions of the array to function but still getting an error!
Code (You can directly scroll down to the error it gives and see only those lines in code)
class Solution {
public:
int mod = 1e9 + 7;
int checkRecord(int n) {
int dp[n + 1][2][3];
memset(dp, -1, sizeof(dp));
return helper(0, 1, 2, n + 1, 2, 3, dp);
}
int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {
if(idx == N) return;
if(dp[idx][A][startL] != -1) {
return dp[idx][A][startL];
}
dp[idx][A][startL] = helper(idx + 1, A, 2, N, M, K, dp) % mod;
if(startL > 0) {
dp[idx][A][startL] += helper(idx + 1, A, startL - 1, N, M, K, dp) % mod;
}
return dp[idx][A][startL];
}
};
Error
error: cannot initialize a parameter of type 'int (*)[*][*]' with an lvalue of type 'int [n + 1][2][3]'
return helper(0, 1, 2, n + 1, 2, 3, dp);
^~
note: passing argument to parameter 'dp' here
int helper(int idx, int A, int startL, int N, int M, int K, int dp[][M][K]) {
^
A:
int checkRecord(int n) {
int dp[n + 1][2][3];
The size of an array variable must be compile time constant in C++. n + 1 is not compile time constant and as such the program is ill-formed.
If you want to create an array with runtime size, then you must create an array with dynamic storage duration. simplest way to do that is to use std::vector.
int helper(int idx, int A, int startL, int N, int M, int K, int dp[N][M][K]) {
Same applies to parameters which are also variables. Though there is slight difference since the array parameter will be adjusted to be a pointer to the first element of the array and the outermost dimension of the array i.e. N is ignored. The type of dp would be int(*)[M][K] if M and K were compile time constant.
Yeah, but 3d vector is too much to type vector<vector<..
In order to write long class template instances, you should pace yourself so that you don't get exhausted before the end. In case you are overcome by fatigue, take a short break to recover and continue later. I believe that you can do it.
That said, the inner dimensions of your array seem to be constant, so you don't need to use vectors inside vectors.
if(idx == N) return;
This is an ill-formed return statement in a non-void function.
A: Seems like you are trying to solve a competitive programming problem. So my answer is going to focus on that. I think others pointed out why it is not valid C++.
In C++, I don't see any easy way to achieve what you want.
In practice, when it comes to competitive programming problems, you may just define a big global array(As problems have fixed input sizes usually. In this case, there would be the max number of N, M, and K) and you don't have to struggle with passing it. Reuse the array for each case, but make sure you initialize it every time. Yeah, this is not a good practice in general but pretty handy for competitive programming.
If you think about 3D vectors are overkill, you may consider this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69017187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use setMenuVisibility in fragment? I have a sliding tabbed layout with seven fragments. I am saving my events in another activity and retrieving data from database in fragment and creating views.
Now when I save the data in add event activity and finish that activity and return to fragment, the events are not getting created. I am using setMenuVisibility funcion to show this events. But when I did debug the setMenuVisibility never run when I return from activity.
What's wrong here? How can I show events on fragments when I return from activity?
Fragment code:
public class Mon extends Fragment {
private FrameLayout fab;
private EventTableHelper mDb;
private Intent i;
private ViewGroup dayplanView;
private int minutesFrom,minutesTo;
private List<EventData> events;
private List<View> list;
private EventData e;
private LayoutInflater inflater;
public boolean editMode;
private RelativeLayout container;
RelativeLayout parent;
View eventView;
private boolean mCheckFragment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mon, container, false);
list = new ArrayList<View>();
dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout);
showEvents();
mCheckFragment = true;
return view;
}
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,final int id) {
eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
list.add(eventView);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
if(location.equals(""))
{
tvTitle.setText("Event : " + title);
}
else
{
tvTitle.setText("Event : " + title + " (At : " + location +")");
}
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(getActivity(), AddEventActivity.class);
editMode = true;
i.putExtra("EditMode", editMode);
i.putExtra("id", id);
startActivityForResult(i, 1);
}
});
}
@Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible) {
if(mCheckFragment) {
removeView();
showEvents();
Toast.makeText(getActivity(), "Monday", Toast.LENGTH_SHORT).show();
}
// ...
}
}
public void showEvents()
{
mDb = new EventTableHelper(getActivity());
events = mDb.getAllEvents("Mon");
for (EventData eventData : events) {
int id = eventData.getId();
String datefrom = eventData.getFromDate();
if (datefrom != null) {
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
String title = eventData.getTitle();
String location = eventData.getLocation();
String dateTo = eventData.getToDate();
if (dateTo != null) {
//times = dateTo.substring(11,16).split(":");
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id);
id++;
}
}
public void removeView()
{
for(int i=0; i<list.size(); i++)
{
View view = (View)list.get(i);
dayplanView.removeView(view);
}
}
private int dpToPixels(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
}
Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35357309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HTML5 video not playing on IE9 Im trying to use HTML5 video on IE9 but doesn't play.
When i play it locally evrything works fine, but when i upload to the server doesn't work.
This is the URL: http://inoq.com/lxgo2/monumentos.html
It works fine in all other browsers(Chrome, Safari, Opera, Firefox..) just not IE9.
I already added the mime types too .htaccess file:
AddType video/ogg ogv
AddType video/mp4 mp4 m4v
AddType video/webm webm
This image shows the network logs on IE9:
Network logs IE9 http://inoq.com/lxgo2/network-log.jpg
Any idea on what can be the problem?
Thanks
Bruno
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12437578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 0x4 Decompression error in Python Confluent Kafka I've been having trouble getting python-confluent-kafka to work on my windows server.
When creating a simple consumer on my local machine, everything works fine.
However, once on the windows server, I will receive the messages but get the following error:
b'Decompression (codec 0x4) of message at 24023756 of 9550 bytes failed: Local: Not implemented'
I copied the exact conda environment I have on my local machine to the server.
A: Turns out it had to do with the .dll's not being found due to the Path/Environment Variables not being configured properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73298124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding new unique grouping ID based on group_by variable I have a dataset with drugs being administered overtime. I want to create groups for each block of the drug being administered. I figured out a simple method to do this with a for-loop that I can apply to each patients set of drugs.
BUT I am curious if there is simple way to do this within the realm of tidyverse?
Not that it matters, but more so I am curious if there is a simple method already created for this problem.
Set-up
have <- tibble(
patinet = c(1),
date = seq(today(), today()+11,1),
drug = c(rep("a",3), rep("b",3), rep("c",3), rep("a",3))
)
## Want
want <- tibble(
patinet = c(1),
date = seq(today(), today()+11,1),
drug = c(rep("a",3), rep("b",3), rep("c",3), rep("a",3)),
grp = sort(rep(1:4,3))
)
> have
# A tibble: 12 Γ 3
patinet date drug
<dbl> <date> <chr>
1 1 2022-03-16 a
2 1 2022-03-17 a
3 1 2022-03-18 a
4 1 2022-03-19 b
5 1 2022-03-20 b
6 1 2022-03-21 b
7 1 2022-03-22 c
8 1 2022-03-23 c
9 1 2022-03-24 c
10 1 2022-03-25 a
11 1 2022-03-26 a
12 1 2022-03-27 a
> want
# A tibble: 12 Γ 4
patinet date drug grp
<dbl> <date> <chr> <int>
1 1 2022-03-16 a 1
2 1 2022-03-17 a 1
3 1 2022-03-18 a 1
4 1 2022-03-19 b 2
5 1 2022-03-20 b 2
6 1 2022-03-21 b 2
7 1 2022-03-22 c 3
8 1 2022-03-23 c 3
9 1 2022-03-24 c 3
10 1 2022-03-25 a 4
11 1 2022-03-26 a 4
12 1 2022-03-27 a 4
A: You can use data.table::rleid
have %>% mutate(group = data.table::rleid(drug))
# A tibble: 12 x 4
patinet date drug group
<dbl> <date> <chr> <int>
1 1 2022-03-16 a 1
2 1 2022-03-17 a 1
3 1 2022-03-18 a 1
4 1 2022-03-19 b 2
5 1 2022-03-20 b 2
6 1 2022-03-21 b 2
7 1 2022-03-22 c 3
8 1 2022-03-23 c 3
9 1 2022-03-24 c 3
10 1 2022-03-25 a 4
11 1 2022-03-26 a 4
12 1 2022-03-27 a 4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71497278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apply function to URL and write in new column in CSV I'm a newbie and surprised there's already not a clear answer similar to what I'm asking, apologies if this is a duplicate.
I have a list of URLs in a CSV file I'm trying to shorten, I want to loop through my CSV file and then write a new column with the shortened URL right next to the original URL.
from pyshorteners import Shortener
import csv
def generate_short(url):
x = shortener.short(url)
return x
with open('Links_Test.csv') as csvfile:
my_date = csv.reader(csvfile, dialect = 'excel')
for row in my_data:
x = shortener.short(row)
print(X)
EDIT:
I keep getting the error "ValueError: Please enter a valid url" and don't know how to proceed from here.....I'm sure I'm the problem.
Here's what my input data looks like:
URL
http://www.google.com
http://www.facebook.com
http://www.twitter.com
http://www.linkedin.com
and here's what I want my output to look like:
URL Short_URL
http://www.google.com http://goo.gle
http://www.facebook.com http://goo.g3c
http://www.twitter.com http://goo.g3a
http://www.linkedin.com http://goo.g2q
Thank you for your help. I was very surprised there's not already a clear answer posted (at least I couldn't find it) so I'm sorry if this is a duplicate.
A: Apply the function on row[0] or row['URL']
Also you have to apply it on my_data.iterrows()and not on my_data
from pyshorteners import Shortener
import pandas as pd
def generate_short(url):
x = shortener.short(url)
return x
my_date = pd.read_csv( 'Link-Tests.csv', sep = "\t") #seperator argument is optional. It can be a semi colon, a tab. Check your CSV file for knowing what the separator is.
for index,row in my_data.iterrows():
x = shortener.short(row[0])
print(X)
If you can always store the shortened URL into a separate list, convert it into a DataFrame and then merge with the original dataframe based on index.
lst = []
my_date = pd.read_csv( 'Link-Tests.csv', sep = "\t")
for index,row in my_data.iterrows():
x = shortener.short(row[0])
lst.append(X)
df = pd.DataFrame(lst, columns=["Short-Url"])
my_data = my_data.join(df, how= 'outer')
A: First try doing this:
from pyshorteners import Shortener
import csv
def generate_short(url):
x = shortener.short(url)
return x
with open('Links_Test.csv') as csvfile:
my_data = csv.reader(csvfile, dialect = 'excel')
for row in my_data:
print(row) # output: ['URL'], ['google.com']...
You probably want to use next() or maybe look at this thread to ignore the header. Also, you probably want to use row[0] to get the first item in the list. So your final code might be
from pyshorteners import Shortener
import csv
def generate_short(url):
x = shortener.short(url)
return x
with open('Links_Test.csv') as csvfile:
next(csvfile) # skip the header row
my_data = csv.reader(csvfile, dialect = 'excel')
for row in my_data:
print(row[0]) # output: 'google.com' ....
# do the link shortener stuff here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45155856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to print a multi-dimensional array in a GridView? I print unidimensional array fine - it works.
http://aspsnippets.com/Articles/Binding-Arrays-to-GridView-in-ASP.Net.aspx
string[,] arr2D =
{
{ "John", "21" },
{ "Smith", "33" },
{ "Ryder", "15" },
{ "Jake", "18"},
{ "Tom","34" }
};
ArrayList arrList = new ArrayList();
for(int i=0;i<5;i++)
{
arrList.Add(new ListItem(arr2D[i, 0], arr2D[i, 1]));
}
Grid2D.DataSource = arrList;
Grid2D.DataBind();
But the problem is when I try to put "ArrayList", it does not exist in the context of the language. any idea how to fix this, or another method to do this. and i try with this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//enter code here
BindGridview();
}
}
private void BindGridview()
{
string[,] arrlist = {
{"Suresh", "B.Tech"},
{"Nagaraju","MCA"},
{"Mahesh","MBA"},
{"Mahendra","B.Tech"}
};
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Education");
for (int i = 0; i < arrlist.GetLength(0);i++)
{
dt.Rows.Add();
dt.Rows[i]["Name"] = arrlist[i,0].ToString();
dt.Rows[i]["Education"] = arrlist[i,1].ToString();
}
gvarray.DataSource = dt;
gvarray.DataBind();
}
But DataTable doensn't exist.
A: your code to fill the datatable is not correct - please try the below eg.
private void BindGridview()
{
string[,] arrlist = {
{"Suresh", "B.Tech"},
{"Nagaraju","MCA"},
{"Mahesh","MBA"},
{"Mahendra","B.Tech"}
};
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Education", typeof(string)));
//dr = dt.NewRow();
for (int i = 0; i < arrlist.GetLength(0);i++)
{
dr = dt.NewRow();
dr["Name"] = arrlist[i,0].ToString();
dr["Education"] = arrlist[i,1].ToString();
}
gvarray.DataSource = dt;
gvarray.DataBind();
}
A: Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim str_array(,) As String ' 2D array declaration
str_array = {{"Suresh", "B.Tech"}, {"Nagaraju", "MCA"}, {"Mahesh", "MBA"}, {"Mahendra", "B.Tech"}} ' array initialization
For i As Integer = 0 To (str_array.Length / 2) - 1 'limit is set to this because the length includes both the indices and white space
gv.Rows.Add(str_array(i, 0), str_array(i, 1))
Next
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25009815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to efficiently extract the visible areas of a Bitmap? I have a bitmap and would like to create and use a filter that would take all the visible parts of the bitmap (all pixels with alpha != 0) and set them into a particular value while drawing on an Android view.
I was able to achieve this with a simple for-loop on the bitmap:
private int maskAlpha = 0xAA;
private Paint maskPaint;
private Bitmap targetViewLayoutBitmap;
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskPaint.setColor(Color.argb(maskAlpha, 0, 0, 0));
}
...
private void setTargetViewLayoutBitmap(final Bitmap viewBmp) {
for (int x = 0; x < viewBmp.getWidth(); x++) {
for (int y = 0; y < viewBmp.getHeight(); y++) {
int pixel = viewBmp.getPixel(x, y);
boolean isVisiblePixel = ((pixel & 0xff000000) != 0);
targetViewLayoutBitmap.setPixel(x, y, isVisiblePixel ? 0x00ffffff : 0xff000000);
}
}
}
@Override
protected void onDraw(Canvas canvas) {
...
canvas.drawBitmap(targetViewLayoutBitmap, targetViewLeft, targetViewTop, viewMaskPaint);
}
Is there a more efficient way of achieving this?
A: You can use a PorterDuffColorFilter with a PorterDuff.Mode.SRC_IN.
This example takes a Drawable and changes every non transparent pixel to green:
drawable.setColorFilter(new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN));
Note: You can easily apply it to a Bitmap converting it into a Drawable using
Drawable drawable = new BitmapDrawable(getResources(), yourBitmap);
A: After some testing I figured out the solution below using a ColorMatrixColorFilter works in an optimal way (applying the matrix takes less than 1/20 of the for-loop).
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
viewMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
viewMaskPaint.setAlpha(maskAlpha);
colorFilterMatrixPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
colorFilterMatrixPaint.setColorFilter(new ColorMatrixColorFilter(new float[] {
0, 0, 0, 255, 0,
0, 0, 0, 255, 0,
0, 0, 0, 255, 0,
0, 0, 0, -255, 255
}));
setWillNotDraw(false);
}
private void setTargetViewLayoutBitmap(final Bitmap viewBmp) {
targetViewLayoutBitmap = Bitmap.createBitmap(viewBmp.getWidth(), viewBmp.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(targetViewLayoutBitmap);
canvas.drawBitmap(viewBmp, 0, 0, colorFilterMatrixPaint);
}
@Override
protected void onDraw(Canvas canvas) {
...
canvas.drawBitmap(targetViewLayoutBitmap, targetViewLeft, targetViewTop, viewMaskPaint);
}
Thank you for @Selvin for pointing me to the right direction (this solution was an interpretation of what you suggested).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37837652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: More than one path from A*? I have written an A* that works nice. It gives me the shortest path between two nodes. However, I would like to have two or maybe even three paths. The best, the second best and the third path (if there is more than one path available). Kinda like directions on Google Maps where you can see multiple options between two cities.
Is this possible with A* or am I stuck with only getting the best result? If it is possible, please point me in the right direction. If not possible with A*, what algorithm should I look at that can do this?
My implementation of A* is from the pseudocode on wikipedia (http://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode), and is written in VB .NET. If that is of any importance.
Thank you.
A: when you perform A* search you change state of priority queue. When you come to finish you put away the best vertex nearest to the finish. Also there some other vertices near finish already, you can peek them from the queue too and get "another best path".
But you can get different results: sometimes the paths can diff in only last edge.
Like this: -------<=>finish. If there is really another best path with similar length then you will find it.
I think Google provides many paths because they use different metrics simultaneously. The metrics give different results and solve path optimization problem using different parameters.
A: Getting the exact second-shortest path requires something like this.
If you don't care about that kind of precision, then you can introduce a bit of randomness into the shortest path:
*
*Cut a vertex or edge from the shortest path and recompute.
*At some point along the shortest path, make an intentional wrong turn somewhere and recompute from there.
A: Recompute the A* algorithm using the same graph but with different weightings. The weighting on each arc, for the fastest journey, ought to be the time taken to traverse that arc, which is the length of the arc divided by the expected speed to travel along it.
You can create a new set of weightings using only the distance, not the expected speed (it is more convenient to assign the same speed to every arc). That will give the shortest path, not the fastest one.
You can then create a compromise between shortest and fastest. You now have three (possibly) different routes.
Other options:
(i) add a weight to every arc to account for the junctions at start and end; tinker with this weight, allowing you to create routes that minimise turns. You can also add extra weights for very sharp turns, or turns across the traffic flow (right turns in UK, Australia, India, etc.; left turns in USA, France, etc.).
(ii) Create a route that avoids motorways / freeways by setting the cost of them to a very high value.
(iii) Use time of day, or actual on-line information, to estimate traffic flow and modify weightings based on that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8168243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using std::string in c++ for unmanaged c# dll I'm trying to set up an unmanaged DLL package for c# for a c++ SDK that a client has provided. This SDK uses std::string and std::wstring variables. I found out that it's hard/impossible to use STL variables like string and wstring for this but it's kind of my last resort. I'm really hoping for someone that could tell me a possible way of building a c# dll wrapper for c++ methods that use std::string & std::wstring.
A: Have you tried converting std::string to System::String^ as stated in MSDN docs
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37413008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does only one Thread executing a Kernel implement the declaration of an array in Shared Memory in CUDA I am implementing the following CUDA kernel that stores an array in Shared Memory:
// Difference between adjacent array elements
__global__ void kernel( int* in, int* out ) {
int i = threadIdx.x + blockDim.x * blockIdx.x;
// Allocate a shared array, one element per thread
__shared__ int sh_arr[BOCK_SIZE];
// each thread reads one element to sh_arr
sh_arr[i] = in[i];
// Ensure reads from all Threads in Block complete before continuing
__syncthreads();
if( i > 0 )
out[i] = sh_arr[i] - sh_arr[i-1];
// Ensure writes from all Threads in Block complete before continuing
__syncthreads();
}
BLOCK_SIZE is a constant declared outside the kernel.
It seems like every Thread that executes this Kernel will create a new array because every Thread that executes this Kernel will see this line:
__shared__ int sh_arr[BOCK_SIZE];
Is it the case that only the first Thread that executes this Kernel will "see" this line, and all subsequent kernels overlook this line?
A: Shared variables in CUDA are shared between threads in the same block. I don't know exactly how it is done under the hood but threads in the same thread-block will see __shared__ int sh_arr[BOCK_SIZE]; however, since it has the __shared__ modifier, only one thread will create the array while the others will just use it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27671087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I remove some empty closing and opening divs? I'm working with some HTML markup that I can't change, and in some instances on particular pages it breaks a layout. What I need to do is remove - using empty() or remove() or some other jQuery function - the tags commented below </div> and <div>.
Can I do this with jQuery?
How can I select those two tags?
...
<div class="woocommerce-product-details__short-description">
<p>Text</p>
</div>
</div> // Remove this closing div
<div> // Remove this opening div
<form class="cart" action="example.com" method="post" enctype='multipart/form-data'>
<div class="wc-pao-addons-container">
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69801913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to display website in cordova? i'm just wanted to know how to simply display my website into a crossplatform mobile app using cordova? What I need to change into index.html or config.xml?
A: You can use the Cordova plugin InAppBrowser https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/
A: No need to change, if you just want your cordova project would run on web as well then use below command :
cordova platform add browser
This works for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46539317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: [IfcOpneShell]Unabled to add instance from IFC2X3 schema to file with IFC4 schema I am using IfcOpenShell in python.
When I try to createed a new file and added entity, I get the following error.
How can I get rid of the error?
[program]
ifc_file = ifcopenshell.file()
ifc_file.add({IfcBuildingElementProxy})
[error]
Unabled to add instance from IFC2X3 schema to file with IFC4 schema
Thanks for any help.
A: I found my own answer.
I had to set 'schema'
ifc_file = ifcopenshell.file(schema=other_ifc_file.schema)
ifc_file.add({IfcBuildingElementProxy})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71389048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R - Replace selective rows data frame I have a dataframe "A" with the following shape
log P1 P2 P3 P4 P5 Method Round #TSamples #Samples0 #Samples1 FP TN TP FN Time Det_Time
data1 2 0 0 0 LOF 1 3 3 0 0 3 0 0 0.00800108909606934 1
data1 2 0 0 0 Mahalanobis 1 3 3 0 0 3 0 0 0.00100016593933105 1
data1 2 0 0 0 Cook 1 3 3 0 0 3 0 0 0.00900101661682129 1
...........
And another dataframe "B" with
log P1 P2 P3 P4 P5 Method Round #TSamples #Samples0 #Samples1 FP TN TP FN Time Det_Time
data1 2 0 0 0 Mahalanobis 1 3 3 0 0 3 0 0 0.00200080871582031 1
data1 3 0 0 0 Mahalanobis 1 3 3 0 0 3 0 0 0.000999927520751953 1
Basically, I would like to replace the rows "FP", "TN", "TP" and "FN" from the dataframe A from those from dataframe B when the columns "P1", "P2", "P3", "P4", "P5", "Method" and "Round" match in both A and B dataframe.
RaΓΊl
A: Something like this:
require(sqldf)
C <- sqldf('select A.log, A.P1, A.P2, A.P3, A.P4, A.P5, A.Method, A.Round, "A.#TSamples", "A.#Samples0", "A.#Samples1", B.FP, B.TN, B.TP, B.FN, A.Time, A.Det_Time
from A
inner join B on (A.log = B.log and
A.P1 = B.P1 and
A.P2 = B.P2 and
A.P3 = B.P3 and
A.P4 = B.P4 and
A.P5 = B.P5 and and
A.Method = B.Method and
A.Round = B.Round)
')
C <- rbind(A,C)
C <- C[!duplicated(C[c("log", "P1", "P2", "P3", "P4", "P5", "Method", "Round", "#TSamples", "#Samples0", "#Samples1", "Time", "Det_Time")]),]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33936362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Why are many of the characters of a string change when copied/pasted in JavaScript or assigned to a form input element I have built the following string in JavaScript using the String.fromCharCode function and assigned it to variable h.
var h=String.fromCharCode(127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146)
When I print the string using console.log, the a space and 19 boxes show up (there are 20 characters in the string).
Now if I select these characters, copy them and paste them in a Hex Editor it shows the following:
7F 3F 81 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 8D 3F 8F 90 3F 3F
which are the ASCII codes for the characters in the given string.
7F is ok, but 3F is wrong, it should have been 80, 81 is correct but next 11 character are shown as 3F, then 8D but the next character code is again 3F then next 2 character i.e 8F and 90 are fine but next 2 character are again wrong.
Can anyone tell me why is this happening? h.charCodeAt(1) shows 128 though.
Thanks in advance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63650709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Angular Form Validations - values have to be different to initial values I have reactive form validations set up as follows:
ngOnInit(): void {
this.userForm = this.formBuilder.group({
status: {checked: this.selectedUser.status == 1},
username: [this.selectedUser.username, [Validators.required, Validators.minLength(LlqaConstants.USERNAME_MIN_LENGTH)]],
realname: [this.selectedUser.realname, [Validators.required, Validators.minLength(LlqaConstants.REALNAME_MIN_LENGTH)]],
password: ['', this.selectedUser.passhash.length > 0 ? [Validators.required, Validators.minLength(LlqaConstants.PASSWORD_MIN_LENGTH)] : null],
usercomment: [this.selectedUser.comment]
});
}
I'd like to enable the submit button, as soon as one input value is not equal to the initial value anymore. The simplest way I could find is:
disableSaveButton(): boolean {
return !this.userform.dirty || this.userForm.invalid;
}
My problem with the dirty property ist, as soon as I enter something, dirty is true, also if I enter the same value as the initial value. I'd to have a property which tells me if one input value is not equal to the initial value. Is this possible out of the box or do I have to check each userForm.value equals to this.selectedUser.someValue?
A: I created a custom validator to solve this issue.
The validator:
export function oneValueHasToBeChangedValidator(values: { controlName: string, initialValue: string | number | boolean }[]): ValidatorFn {
return (form: FormControl): { [key: string]: any } => {
let sameValues = true;
for (let comparingValues of values) {
if (form.value[comparingValues.controlName] != comparingValues.initialValue) {
sameValues = false;
break;
}
}
return sameValues ? {'sameValues': {values: values}} : null;
};
}
How I took use of it:
this.userForm = this.formBuilder.group({
status: this.selectedUser.status == 1,
username: [this.selectedUser.username, [Validators.required, Validators.minLength(LlqaConstants.USERNAME_MIN_LENGTH)]],
realname: [this.selectedUser.realname, [Validators.required, Validators.minLength(LlqaConstants.REALNAME_MIN_LENGTH)]],
password: ['', [Validators.minLength(LlqaConstants.PASSWORD_MIN_LENGTH)]],
usercomment: this.selectedUser.comment == null ? "" : this.selectedUser.comment
});
this.userForm.setValidators(oneValueHasToBeChangedValidator([{
controlName: "status",
initialValue: this.selectedUser.status == 1
}, {
controlName: "username",
initialValue: this.selectedUser.username
}, {
controlName: "realname",
initialValue: this.selectedUser.realname
}, {
controlName: "password",
initialValue: ""
}, {
controlName: "usercomment",
initialValue: this.selectedUser.comment == null ? "" : this.selectedUser.comment
}]));
this.userForm.updateValueAndValidity();
A: You could cache the initial value as soon as you set the form object. Then change your disableSaveButton method to check the equality of the two values.
For instance:
export class MyComponent {
initialValue: any;
constructor(private fb: FormBuilder) {
this.form = fb.group({...});
this.initialValue = this.form.value;
}
disableSaveButton() {
return JSON.stringify(this.initialValue) === JSON.stringify(this.form.value);
}
}
The disable method will check if the current form value is the same as the initial value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46667375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to send mail with attachement in PHP Here is my complete code of php mail. My code is working fine but I want to include file as attachement. Where should i add which code to send mail with attachement. No new code is needed. I want to use the same code. can any one find it out and fix it.
<?php
if(isset($_POST["submit"])){
$file_name = $_FILES['fileToUpload']['name'];
$file_name1 = rand().$file_name;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
move_uploaded_file($file_tmp,"cv/".$file_name1);
$conn = mysqli_connect("localhost", "", "", "");
if($conn === false){
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$CV = $_REQUEST['fileToUpload'];
$Name = $_REQUEST['name'];
$Email = $_REQUEST['email'];
$Mobile = $_REQUEST['mobile'];
$CGPA = $_REQUEST['cgpa'];
$RegNo = $_REQUEST['regno'];
$Position = $_REQUEST['position'];
$Why = $_REQUEST['why'];
$sql = "INSERT INTO `ExecutiveBody`(`ID`, `CV`, `Name`, `Email`, `Mobile`, `CGPA`, `RegNo`, `Position`, `Why`) VALUES ('','$file_name1','$Name','$Email','$Mobile','$CGPA','$RegNo','$Position','$Why')";
if(mysqli_query($conn, $sql)){
echo "<script>alert('Thanks For Your Interest. Check Your Email For Confirmation.');</script>";
} else{
echo "ERROR: Hush! Sorry $sql. "
. mysqli_error($conn);
}
$to = "mail@hotmail.com"; // this is your Email address
$from = $_REQUEST['email']; // this is the sender's Email address
$name = $_REQUEST['name'];
$mobile = $_REQUEST['mobile'];
$cgpa = $_REQUEST['cgpa'];
$regno = $_REQUEST['regno'];
$position = $_REQUEST['position'];
$why = $_REQUEST['why'];
$cv = $_REQUEST['cv'];
$subject = "Executive Body | Application";
$subject2 = "Copy Of Your Executive Body Application Submission";
$message = "<b>Name: </b>" . $name . "<br><br>" . "<b>Email: </b>" . $from . "<br><br>" ."<b>Mobile: </b>" . $mobile . "<br><br>" . "<b>CGPA: </b>" . $cgpa . "<br><br>" . "<b>Reg No: </b>" . $regno . "<br><br>" . "<b>Position: </b>" . $position . "<br><br>" . "<b>Why You Want To Be Part Of Society?: </b><br><br>" . $why;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From:" . $from;
mail($to,$subject,$message,$headers);
// Close connection
mysqli_close($conn);
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74416104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: response redirect to a different page when 405 raise I have a view function which I want to use only request method is POST. I got to know about require_POST decorator here, but what I want is that if method is not POST then redirect user to different view using HttpResponseRedirect. How can I do this ?
from django.views.decorators.http import require_POST
@require_POST
def my_view(request):
# I can assume now that only POST requests make it this far
# ...
I know I can do it by adding two lines of code, without using require_POST redirect in my method itself like
if request.method != 'POST':
return HttpResponseRedirect(view_url)
but I am more interested in using decorator itself and when this decorator raises 405, then redirect to another view.
A: You would have to use a custom decorator. You can see the code for the Django decorator here. It's already returned a response before your code is reached at all, so absolutely nothing you do in your view function would be run anyway.
There is nothing wrong with manually returning a redirect if the request is not a POST. If you use this pattern in a few different places in your code I would then refactor it into a decorator later. But if this is the first place you are using it then it's overkill.
A: A custom decorator is the way to go.
I myself use one similar to the one you need and I'll post the code.
Do upvote @aychedee s answer since he was first. :)
def require_post_decorator(function=None, redirect_url='/'):
def _decorator(view_function):
def _view(request, *args, **kwargs):
if request.method == 'POST':
#do some before the view is reached stuffs here.
return view_function(request, *args, **kwargs)
else:
return HttpResponseRedirect(redirect_url)
_view.__name__ = view_function.__name__
_view.__dict__ = view_function.__dict__
_view.__doc__ = view_function.__doc__
return _view
if function:
return _decorator(function)
return _decorator
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15859935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get HTML form element when respective form value is null.? Have a form, need to validate it.
Have used serializearray to get all the form elements on clicking submit button.
Parsing trough each value, if value is null need to add a class to respective HTML element.
Code below
$(document).ready(function(){
$("#sumbit_button").click(function(){
var formElements = $("#ImageSliderForm").serializeArray();
$(formElements).each(function(x){
if(formElements[x]["value"] == ""){
//get the respective html element and add a class
}
});
});
});
Need a way to find the respective HTML element.
Output of console.log($("#ImageSliderForm").serializeArray());
[Object { name="ImageSliderImageURL", value=""}, Object { name="ImageHeader", value=""}, Object { name="ImageHeaderSubText", value=""}, Object { name="ImageSliderSubTextURL", value=""}]
A: If condition is wrong Try this
if(formElements[x]["value"] == "" || formElements[x]["value"] == null){
A: Try this:
var formElements = $("#ImageSliderForm").serializeArray();
$(formElements).each(function (x, element) {
if (element.value == "" || element.value == null) {
//get the respective html element and add a class
$("[name='" + element.name + "']").addClass('someclass');
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16189407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I properly decouple URLConf in Django tutorial 3? I am following the Django tutorial and have made it to Decoupling the URLConfs in tutorial 3. Prior to this step, everything was working. Now, when I do the final step of Removing hardcoded URLs in templates which is changing
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
to
<li><a href="{% url 'polls.views.detail' poll.id %}">{{ poll.question }}</a></li>
I get this error:
NoReverseMatch at /polls/
Reverse for ''polls.views.detail'' with arguments '(1,)' and keyword arguments '{}' not found.
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for ''polls.views.detail'' with arguments '(1,)' and keyword arguments '{}' not found.
Exception Location: e:\Django\development\tools\PortablePython\PortablePython2.7.3.1\App\lib\site-packages\django\template\defaulttags.py in render, line 424
Python Executable: e:\Django\development\tools\PortablePython\PortablePython2.7.3.1\App\python.exe
My views.py looks like this:
from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p})
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
My project urls.py looks like this:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And polls/urls.py looks like this:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('polls.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
Obviously I missed something, but I have been over part 3 a few times now and can't figure out what I missed. What do I need to correct to correctly decouple these URLs?
A: This is a version issue. You've somehow found a link for the development version of Django, while you're using release 1.4. One of the things that's changed since the release is that URL names in templates used not to need quotes, but now they do. That's why the error message has the URL name within two sets of quotes.
You should use this version of the tutorial to match the Django version you have. (You could install the development version, but that's not recommended - stick to the release.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11748497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to click on img element? I am trying to access the below class in selenium but it shows element not found error.
Html
<button class="gpquestion-plusicon">
<img src="./assets/images/viewdetails.png">
</button>
Code
driver.find_elements_by_css_selector("//img[@src='./assets/images/viewdetails.png']").click()
OR
driver.find_element_by_css_selector("//img[@src='./assets/images/viewdetails.png']").click()
driver.find_elements_by_xpath("//img[@src='./assets/images/viewdetails.png']").click()
Exception
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector:
An invalid or illegal selector was specified
Unfortunately none of them works. The xpath shows no element found error.
Any suggestions?
A: You are tring to use xpath as css_selector. Try
driver.find_element_by_css_selector("[src='./assets/images/viewdetails.png']").click()
Or
driver.find_element_by_xpath("//img[@src='./assets/images/viewdetails.png']").click()
You can also use explicit wait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
wait = WebDriverWait(driver, 10)
wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, "[src='./assets/images/viewdetails.png']"))).click()
# or
wait.until(ec.element_to_be_clickable((By.XPATH, "//img[@src='./assets/images/viewdetails.png']"))).click()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60413219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Print the return of a method I know in php I can do something like this
echo "{$this->method}";
and I swear there was a way to do it in perl
Update:
What I am trying to do is print a scalar that the method returns. I was kind of hoping of doing within the string like in php, just because I'm lazy :P.
A: Are you just trying to evaluate an arbitrary expression inside a double quoted string? Then maybe you're thinking of
print "@{[$this->method]}";
There is also a trick to call the method in scalar context, but the syntax is a little less clean.
print "${\($this->method)}";
A: Well, if $this->method outputs a string or a number (like PHP, Perl can automatically convert numbers to strings when required), then you can do print $this->method . "\n";.
If $this->method outputs a data structure (eg an array reference or a hash reference), you can use Data::Dumper to look at the structure of the data. Basically, print Dumper($foo) is the Perl equivalent of PHP's var_dump($foo).
What are you trying to do, exactly?
A: If $this->method is returning a string, you can do this:
print $this->method . "\n";
without quotes. That will print your string. Sometimes, that can lead to a clumsy looking statement:
print "And we have " . $this->method . " and " . $that->method . " and " . $there->method . "\n";
In that case you can use a little programming trick of:
print "And we have @{[$this->method]} and @{[that->method]} and @{[$their->method]}\n";
Surrounding a function with @{[]} prints out the function's value. Someone explained this to me once, but I can't remember why it works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7490622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to edit the attached menu section for buddypress? I would like to know if there is a line of code I could use to add in functions.php or a file edit to add and remove some of the fields from the current section I have attached in WordPress.
It's a WordPress website running buddypress. This section has all the relevant menu items by default. I need to remove some from this and a new one if possible
This section is located in the top right section when hovered:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39900768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sqlite design for cross linked tables and foreign keys usage I don't know if this is the right place to ask. Because it is a question regarding sql database design I was thinking about database administrator but because the target of that site is database professionals (and I'm absolutely not a professional) I'll just post my question here. Please point me to the right place if you think there's a better place for this type of question.
Getting to the question.
I'm designing a database for translations of literary works. Because this involves people and people often don't fit in a "static" data model I have a pretty convoluted schema. Here is just a section of it, regarding people's names. Because foreign authors are involved (expecially Japanese) I have the added problem of transliteration for people names. At present the structure of the database for people and names is as follows
Let's take an example:
I have a person called "Kyokutei Bakin", which transliterates as ζ²δΊι¦¬η΄ in ideograms and γγ§γ―γγ€ γγγ³ in japanese phonetic alphabet. This author is also known as "Takizawa Bakin" (ζ»ζ²’馬η΄, γΏγγΆγ― γγγ³οΌ and so on...
The 3 table structure with one to many relationships account for a person having multiple names (biographical_name, pen_name, ecc...) and for the fact that every name can have multiple phonetic readings.
This is all good. When I search for someone I just LEFT JOIN the tables and add OR conditions for the various fields. eg:
SELECT DISTINCT name.name_text, phonetic_name.name_text FROM name
LEFT JOIN phonetic_name ON (name.name_id=phonetic_name.name_id)
WHERE (name.name_text LIKE "%bak%")
OR (phonetic_name.name_text LIKE "%馬η΄%");
My problem is that I want one of the names to be the main name of that person. The way I've done it is adding a "main_name" column in the "person" table that points to the "name_id" column of the "name" table. So that I can JOIN name ON (person.main_name=name.name_id) when I want just the main name.
My doubt is:
-Is it a good practice to cross-link two tables?
(Here "name" references "person" on person_id, but at the same "person" references "name" for main_name).
-Can this cause problems?
-How do I set foreign keys in this kind of situation?
-In case this is way too messy, how can I improve the design?
Additional info:
Being a design problem the sql implementation should not be so important, but just in case it does, I'm using sqlite3.
A: I would personally simplify the design like this:
Table: person
*
*person_id (primary key)
*...
Table: name
*
*name_id (primary key)
*name
*name_type
*parent_name_id (foreign key of itself)
*person_id (foreign key of person table)
The table name has a recursive relationship where parent_name_id contains the name_id of the main name of the person. Note that for the main name name_id=parent_name_id. In the column name_type you can store the type of name (phonetic, ideogram, kanji, etc.). You can possibly normalize further the name_type into a dedicated table if you wish to have pure third normal form.
I would say the main benefit of this design is that it greatly simplifies your query when querying for names of any type. You can simply run something like this:
Select distinct b.person_id, b.name as main_name
From name a
Inner join name b on a.parent_name_id=b.name_id
Where a.name like β%...%β
In addition you can store as many names as you want for a single person.
If you want to return several names from different types you can do like this:
Select distinct b.person_id,
b.name as main_name,
c.name as kanji_name,
d.name as katakana_name
From name a
Inner join name b on a.parent_name_id=b.name_id
Left join name c on b.parent_name_id=c.parent_name_id and c.name_type=βkanjiβ
Left join name d on b.parent_name_id=d.parent_name_id and d.name_type=βkatakanaβ
Etc...
Where a.name like β%...%β
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48678413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Remove the baseline border of NSWindow title bar Is there a way to remove the baseline border of the NSWindow title bar without subclass
the window and implement a title bar view myself? (traffic lights button is real tricky)
I wanted to make view and put it just under the window's title bar without the baseline
border so that the my view below will appear to be "stick" or "continued" from the
title bar, that is, if I made my view the same color as the title bar.
A: You can achieve that by:
window?.toolbar?.showsBaselineSeparator = false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27250761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I get the GUID value of a new row after inserting it? I am trying to get the Id of newly inserted record in Sqlserver. I have checked the Scope_Identity() but this is said to return the value of the autoincrement column. The column I am using for Id is Guid. I want this Guid column value after the insert. How should this be achieved? Or I must have to write a custom tedious function to get the Id of newly inserted record.
A: You can try and use OUTPUT, it would be something like:
INSERT INTO ExampleTable (<Column1>, <Column2>, <Column3>)
OUTPUT INSERTED.ID
VALUES (<Value1>, <Value2>, <Value3>)
Also, this question, has a lot more info on the different types of identity selection, you should check it out.
EDIT
You would use this as a regular scalar:
var command = new SqlCommand("...");
Guid id = (Guid) command.ExecuteScalar();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16654491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Python asyncio wait() with cumulative timeout I am writing a job scheduler where I schedule M jobs across N co-routines (N < M). As soon as one job finishes, I add a new job so that it can start immediately and run in parallel with the other jobs. Additionally, I would like to ensure that no single job takes more than a certain fixed amount of time. Any jobs that take too long should be cancelled. I have something pretty close, like this:
def update_run_set(waiting, running, max_concurrency):
number_to_add = min(len(waiting), max_concurrency - len(running))
for i in range(0, number_to_add):
next_one = waiting.pop()
running.add(next_one)
async def _run_test_invocations_asynchronously(jobs:List[MyJob], max_concurrency:int, timeout_seconds:int):
running = set() # These tasks are actively being run
waiting = set() # These tasks have not yet started
waiting = {_run_job_coroutine(job) for job in jobs}
update_run_set(waiting, running, max_concurrency)
while len(running) > 0:
done, running = await asyncio.wait(running, timeout=timeout_seconds,
return_when=asyncio.FIRST_COMPLETED)
if not done:
timeout_count = len(running)
[r.cancel() for r in running] # Start cancelling the timed out jobs
done, running = await asyncio.wait(running) # Wait for cancellation to finish
assert(len(done) == timeout_count)
assert(len(running) == 0)
else:
for d in done:
job_return_code = await d
if len(waiting) > 0:
update_run_set(waiting, running, max_concurrency)
assert(len(running) > 0)
The problem here is that say my timeout is 5 seconds, and I'm scheduling 3 jobs across 4 cores. Job A takes 2 seconds, Job B takes 6 seconds and job C takes 7 seconds.
We have something like this:
t=0 t=1 t=2 t=3 t=4 t=5 t=6 t=7
-------|-------|-------|-------|-------|-------|-------|-------|
AAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
However, at t=2 the asyncio.await() call returns because A completed. It then loops back up to the top and runs again. At this point B has already been running for 2 seconds, but since it starts the countdown over, and only has 4 seconds remaining until it completes, B will appear to be successful. So after 4 seconds we return again, B is successful, then we start the loop over and now C completes.
How do I make it so that B and C both fail? I somehow need the time to be preserved across calls to asyncio.wait().
One idea that I had is to do my own bookkeeping of how much time each job is allowed to continue running, and pass the minimum of these into asyncio.wait(). Then when something times out, I can cancel only those jobs whose time remaining was equal to the value I passed in for timeout_seconds.
This requires a lot of manual bookkeeping on my part though, and I can't help but wonder about floating point problems which cause me to decide that it's not time to cancel a job even though it really is). So I can't help but think that there's something easier. Would appreciate any ideas.
A: You can wrap each job into a coroutine that checks its timeout, e.g. using asyncio.wait_for. Limiting the number of parallel invocations could be done in the same coroutine using an asyncio.Semaphore. With those two combined, you only need one call to wait() or even just gather(). For example (untested):
# Run the job, limiting concurrency and time. This code could likely
# be part of _run_job_coroutine, omitted from the question.
async def _run_job_with_limits(job, sem, timeout):
async with sem:
try:
await asyncio.wait_for(_run_job_coroutine(job), timeout)
except asyncio.TimeoutError:
# timed out and canceled, decide what you want to return
pass
async def _run_test_invocations_async(jobs, max_concurrency, timeout):
sem = asyncio.Semaphore(max_concurrency)
return await asyncio.gather(
*(_run_job_with_limits(job, sem, timeout) for job in jobs)
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63589225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# REGEX need to be corrected I'm making a C# regex to find and replace patterns related to html content.
i need to get all the stuff like that:
<table border=0 align=center id=mytable5>
corrected like that:
<table border="0" align="center" id="mytable5">
i tried out this:
String pattern = @"\s(?<element>[a-z])=(?<valeur>\d+?[a-z])\s?[\>]";
String replacePattern = "${element}=[\"]${valeur}[\"]";
html = Regex.Replace(html, pattern, replacePattern, RegexOptions.IgnoreCase);
but there is absolutly no effect.
Any help would be greatly appreciated.
thank you all
Actually King King, there is a problem with your regex
<table border=0 align="center" id="mytable5">
will give
<table border="0" align=""center"" id=""mytable5"">
thats why the regex must check this
[a space][a-z]=[a-z0-9][a space or '>']
A: var html = "<table border=0 align=center id=mytable5>";
html = Regex.Replace(html, @"=\s*(\S+?)([ >])", "=\"${1}\"${2}", RegexOptions.IgnoreCase);
A: I got it
String pattern = @"([a-z]+)=([a-z0-9_-]+)([ >])";
String replacePattern = "${1}=\"${2}\"${3}";
html = Regex.Replace(html, pattern, replacePattern, RegexOptions.IgnoreCase);
will get
<table border=0 align="center" id="mytable5">
corrected to this:
<table border="0" align="center" id="mytable5">
thanks for King King that showed me the path
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18505478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MYSQL TRIGGER with DECLARE value I want to set value using declare on trigger. The trigger is as follow:
CREATE DEFINER=`root`@`localhost` TRIGGER `update_queue_after_insert` AFTER INSERT ON `encounter_note` FOR EACH ROW DECLARE is_exist INT;
SET is_exist = ( SELECT count(*) FROM practice_last_updated_module WHERE practice_id = NEW.practice_id );
IF NEW.enc_source = 'OP' THEN
UPDATE practice_queue_list PQL SET
PQL.vital_check = IF (NEW.vs_weight <> 0 OR NEW.vs_height <> 0 OR NEW. vs_temperature <> 0 OR LENGTH(NEW.vs_blood_pressure) > 0 <> NEW.vs_pulse <> 0 OR NEW.vs_respiration <> 0, 1, 0)
WHERE PQL.encounter_id = NEW.id AND PQL.practice_place_id = NEW.practice_id;
END IF;
IF is_exist > 0 THEN
UPDATE practice_last_updated_module SET encounter = UNIX_TIMESTAMP(NOW()) where practice_id = NEW.practice_id;
ELSE:
INSERT INTO practice_last_updated_module (practice_id, encounter) VALUES (NEW.practice_id, UNIX_TIMESTAMP(NOW()));
END IF;"
But it returns error on saving
The following query has failed: "CREATE DEFINER=root@localhost
TRIGGER update_queue_after_insert AFTER INSERT ON encounter_note
FOR EACH ROW DECLARE is_exist INT; SET is_exist = ( SELECT count(*)
FROM practice_last_updated_module WHERE
What's wrong with the statement?
A: Use 13.6.1 BEGIN ... END Compound-Statement Syntax.
Try (maybe you need to use DELIMITER):
DELIMITER //
CREATE TRIGGER `update_queue_after_insert` AFTER INSERT ON `encounter_note`
FOR EACH ROW
BEGIN -- <- BEGIN
DECLARE is_exist INT;
SET is_exist = ( SELECT count(*) FROM practice_last_updated_module WHERE practice_id = NEW.practice_id );
IF NEW.enc_source = 'OP' THEN
UPDATE practice_queue_list PQL
SET PQL.vital_check = IF (NEW.vs_weight <> 0 OR NEW.vs_height <> 0 OR NEW.vs_temperature <> 0 OR LENGTH(NEW.vs_blood_pressure) > 0 <> NEW.vs_pulse <> 0 OR NEW.vs_respiration <> 0, 1, 0)
WHERE PQL.encounter_id = NEW.id AND PQL.practice_place_id = NEW.practice_id;
END IF;
IF is_exist > 0 THEN
UPDATE practice_last_updated_module SET encounter = UNIX_TIMESTAMP(NOW()) where practice_id = NEW.practice_id;
-- ELSE:
ELSE
INSERT INTO practice_last_updated_module (practice_id, encounter) VALUES (NEW.practice_id, UNIX_TIMESTAMP(NOW()));
END IF;
END// -- <- END
DELIMITER ;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51924090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ Flat Array vs Multidimensional Array Memory Footprint In C++, the delete[] operator deletes an array. It is able to access the length of the array because the allocator keeps track of it.
Does that mean that a flattened one-dimensional array takes up less memory than a multi-dimensional array?
To be more specific, if I allocate Object** c, does the allocator store the lengths of both the first and second dimensions, while allocating Object* c (but with the same number of elements as the two-dimensional array) only stores one length?
A: If you do this:
Object **c = new Object*[n];
for (size_t i=0; i!=n; ++i) {
c[i] = new Object[m];
}
then it will typically take more memory than doing this:
Object *c = new Object[n*m];
for just the reasons you stated.
Every memory allocation has a certain amount of overhead. In addition to needing to keep the number of elements, there is overhead for the memory allocator itself. It also takes more memory for all the extra pointers for each row.
Note that it is possible to have a situation where breaking it up would use less memory. If your heap was fragmented, then finding one large chunk of memory may require allocating more memory from the operating system, whereas if your array was broken into smaller pieces, those pieces may be able to fit in the holes of your fragmented heap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17518396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to delete first 5 line of specific column? I have a data frame (pandas) with columns A to J. I want to remove the first 7 lines from column A.
I know: a function form remove the entre column. But How can I remove the first 7 lines from the specific column?
df.drop(['your_column_name'], axis=1, inplace=True)
#A
#B
#C
#D
#F
#G
#H
#I
#J
#Index #A #B
#0 #NAN #234
#1 #NAN #235
#2 #NAN #236
#3 #NAN #237
#4 #NAN #238
#5 #NAN #239
#6 #NAN #240
#7 #123 #241
#8 #124 #245
#9 #125 #236
#10 #126 #4562
A: In case you will remove the whole rows which contain NAN, you can use simply
df.dropna()
However you can't remove particular row from specified dataframe column because each row indexed by default which means all columns in a row cohere, and if you remove rows from first column the other columns are longer which is not possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61784187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Session ID lenght (characters) increases in weblogic 12c We are migrating java application from java 1.6 to 1.8 and weblogic 10 to weblogic 12c,While we are checking the sessionID in Java 1.6 and weblogic10 ,which creating in jsp by using (session.getId()) ,we are getting session ID as Seesion =MT6GdnxL!1248180010!1971739048476
but for java 1.8 and WebLogic 12c while checking Session ID length increases Session =2jLynJb9dJOx8AvTjyWSK9UZblqFh4XU!-1492917096!1571733411581
Can anyone please explain why this session ID length increases.
Due to the increase of length which is affecting our business logic
A: It seems that your old weblogic (10) had a different session descriptor on the weblogic.xml.
If you want to keep the same sessionID lenght you should update your weblogic 12c's weblogic.xml:
session-descriptor node id-length value (default is 52).
Reference: https://docs.oracle.com/cd/E24329_01/web.1211/e21049/weblogic_xml.htm#WBAPP587
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58518004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using curl to get a URL from the network Hi guys so i'm using a third party iframe and I would like to load that iframe "internally" or at backend? , once it is loaded a link would be fetch at the iframe and it's at the network, fetching a link from CDN and I would like to get that link and display it to the frontend. But i'm not quite sure if i'm using curl the right away or is there a better way.
(just in case)
Network = when you inspect your google tab you will see a tab called network
$filtering = "https://streamwebsite.com/movie/batman";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $filtering);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($curl);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55137785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Binding ColumDefinition Width I am creating a Windows 8.1 app using https://slideview.codeplex.com in the Windows 10 with help of Visual Studio 2015.
I have added grid to the design with 1 row and two column. In the first page there is big image and no text and in other pages there is icon and text. So I am putting if 4* in first column for first page and 2* in first for second page all works good but I wanted to make it dynamic in ContentPresenter and then I can assign it from C#.
Kindly somebody help me.
I tried in different way like I put below code in SlideApplicationFrame.cs
#region FirstColumnWidth (DependencyProperty)
/// <summary>
/// header Image First Column Width
/// </summary>
public GridLength FirstColumnWidth
{
get { return (GridLength)GetValue(FirstColumnWidthProperty); }
set { SetValue(FirstColumnWidthProperty, value); }
}
public static readonly DependencyProperty FirstColumnWidthProperty =
DependencyProperty.Register("FirstColumnWidth", typeof(GridLength), typeof(SlideApplicationFrame),
new PropertyMetadata(new GridLength(4, GridUnitType.Star)));
#endregion
#region ContentFirstColumnWidth (Attached DependencyProperty)
public static readonly DependencyProperty ContentFirstColumnWidth =
DependencyProperty.RegisterAttached("ContentFirstColumnWidth", typeof(GridLength), typeof(SlideApplicationFrame), new PropertyMetadata(new GridLength(4, GridUnitType.Star)));
public static void SetContentFirstColumnWidth(DependencyObject o, GridLength value)
{
o.SetValue(ContentFirstColumnWidth, value);
}
public static GridLength GetContentFirstColumnWidth(DependencyObject o)
{
return (GridLength)o.GetValue(ContentFirstColumnWidth);
}
#endregion
Then I use it in my ContentPresenter Like this
<ContentPresenter library:SlideApplicationFrame.ContentFirstColumnWidth="{TemplateBinding FirstColumnWidth}" Grid.Column="1"/>
and at the end in style setter
<ColumnDefinition Width="{Binding library:SlideApplicationFrame.ContentFirstColumnWidth}"/>
Whole Style Setter is as below
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<Grid x:Name="GridHeader">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding library:SlideApplicationFrame.ContentFirstColumnWidth}"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
and setting from MainPage.xaml.cs
SlideApplicationFrame RootFrame = Window.Current.Content as SlideApplicationFrame;
RootFrame.FirstColumnWidth = new GridLength(4, GridUnitType.Star);
Please help me I will be highly appreciated
A: Well first you have to have in mind that the values of ColumnDefinition Width and RowDefinition Height are not of type Double but of type GridLength
And after that there are two scenarios that I can think of:
*
*Binding to another element's value
*Binding to value from the ViewModel or the code behind
Case 1:
If You're binding to some value that is double you will need to also use a Converter to convert this value to GridLength
Case 2:
If You're binding to something in the code you could create the property of type GridLength and bind directly, or if the value is double again use Converter like in the previous use case.
Some References on the type
GridLength Structure
GridUnitType Enumeration
*
*Auto - The size is determined by the size properties of the content object.
*Pixel - The value is expressed as a pixel.
*Star - The value is expressed as a weighted proportion of available space.
Edit - Just a simple example of working binding
Still didn't manage to find time to recreate your exact situation so I just used GridView (as it has also header) - Content is purple, header consists of two grid columns - green and red, green is bound to dependency property defined in main page
XAML
<Page
...
x:Name="root">
<Page.Resources>
<Style TargetType="GridView" >
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<Grid x:Name="GridHeader" Height="200">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="{Binding ElementName=root, Path=TestGridLength}"/>
</Grid.ColumnDefinitions>
<Grid Background="Red" Grid.Column="0"></Grid>
<Grid Background="Green" Grid.Column="1"></Grid>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<GridView Background="Purple">
</GridView>
</Page>
Code behind
public GridLength TestGridLength
{
get { return (GridLength)GetValue(TestGridLengthProperty); }
set { SetValue(TestGridLengthProperty, value); }
}
public static readonly DependencyProperty TestGridLengthProperty =
DependencyProperty.Register(
"TestGridLength",
typeof(GridLength),
typeof(MainPage),
new PropertyMetadata(null));
public MainPage()
{
this.InitializeComponent();
this.TestGridLength = new GridLength(10, GridUnitType.Star);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33591523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Lock Row for Particular Month My data has cell A1 containing Month.
A2:Z999 : Employee details.
Column P: Date of joining.
I want to code such that, when P>A1, it should lock the row for that employee since it's old data. Only rows without date, or empty rows 999 onward, should be empty.
Please help! Right now my code below locks everything.
Dim DestSh As Worksheet
Dim lastrow As Long
Set DestSh = Sheets("Consultant & Teacher")
With DestSh
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Columns("A:z").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
MsgBox "Insufficient rows"
End If
If Range("A1").Value = "April" Then
.Unprotect Password:="MyPassword"
.Cells.Locked = False
.Range("A2:Z" & lastrow).Locked = True
A: I'm not so sure what you were trying to accomplish with the existing code, but based purely on what you explained, I think this should do the trick :
Dim DestSh As Worksheet
Dim lastrow As Long
Dim i As Integer
Set DestSh = Sheets("Consultant & Teacher")
With DestSh
'finds the last row with data on A column
lastrow = Range("A65536").End(xlUp).Row
'parse all rows
For i = 2 To lastrow
'if your conditions are met
If Month(.Cells(i, 16)) > Month(.Cells(1, 1)) Then
.Range("A" & i).EntireRow.Cells.Locked = True 'lock the row
End If
Next i
End With
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39872623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to pass a chart from MPAndroidChart from one activity to another? The charts that I create using the MPAndroidChart library are populated using data that comes from a web service which takes a little time. Hence in this time I wish to show a Splashscreen so the network calls can be made in the back ground, a chart will be formed and then passed to the MainActivity where it is to be shown.
For this I wish to pass two BarChart and a RadarChart object from the Splachscreen activity to the MainActivity.
So how can I accomplish that?
A: Pass the data not the graph. You can pass the data as so:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
and get it it new activity this way:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
You might have to pass the data as parcelable or serializable depending on what kind of data you have.
Then you can draw the graph on the new activity with the data you passed.
A: In my opinion your overall design approach needs a little refinement.
First, I recommend you avoid using a splash Activity to 'contain' the network operations. From a user experience perspective this could be poor, because the splash screen could be in view for an indeterminate amount of time from one use to the next. If the splash screen stays for more than, say, two seconds, then the application might appear to have become unresponsive. If you insist on doing it this way, I recommend that the splash screen at least contains dynamic status information to inform the user what's going on.
Next, be sure to perform your networking operation on a dedicated Thread, not on the main UI thread.
For the MainActivity to reference the fetched data, I suggest you look at the singleton pattern to hold it in memory. That is, either use a dedicated singleton object, or hold it in a subclass of Application. This way, the networking operation sets the data in that singleton, and the MainActivity obtains it from the singleton. Optionally, when you create the Intent for the MainActivity, the Bundle could perhaps contain a String which acts as a key to obtain the data. The reason I'm suggesting this strategy is because I am assuming that there might be a large amount of data involved. If on the other hand it's a very small amount of data, perhaps you might be able to get away with putting the data itself into the Bundle, perhaps as JSON in a String, or something.
Do keep in mind that if the application goes to the background and is then later resumed, you might be in a situation where your Activity stack is resumed, but all of your application's 'global' state is gone. This means that your MainActivity would be resumed, but the data you expected to be in your singleton class isn't there any more. Your MainActivity should have the means to cope with this, perhaps by setting off a fresh network request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31511533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Internal references in a VS2005.NET project I have a C++/CLI class library project in VS2005 that i am having some problems with. I have defined a class called Languages which is a an enum class. which looks like this:
"Language.cpp"
namespace Company
{
namespace product
{
public eunm class Languages : int
{
English = 1,
German = 2,
//etc for other languages
};
}
};
I then have another class that tries to references this which lives in the same namespace:
"Language.cpp"
namespace Company
{
namespace product
{
public class LanguageConsumer
{
public:
LanguageConsumer()
{
}
public:
Languages DoSomething(Languages input)
{
if (input == Languages::English)
{
//Do something and return
}
};
}
};
However my project doensn't compile. From what i can figure out the different classes can't see each other even thought they are in the same namespace. I assume that i might need to have header files and #includes for the header files but i just don't know enough about C++/CLI to be sure (i come from C# background with hardly any C experience) and i have tried as many different combinations as i can think of. I'm sure i'm missing something very obvious to anybody who knows what they are doing, but alas i do not.
Thanks in advance.
A: C++/CLI still compiles like C++, file files are compiled separately and then linked together. This is different from C# which compiles all the files together. At compile time the files don't know about each other so the code doesn't compile (what is this enum?!). You need to have the enum definition in the same file (compilation unit) as the class.
The simple way to do this is to move the code into the same file. The header file solution is to move the enum definition into a header file and then include it (#include) in the other file. #include inserts the text of another file, giving the same effect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/726659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Numpy ordered subtraction of elements with full vectorization Imagine a mxn array a, and a 1xn array b, we want to subtract b from a so that b is subtracted from the first element of a, then maximum of zero and b-a[0] is subtracted from a[1], and so on...
So:
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
a = np.repeat(x, 100000).reshape(10, 100000)
b = np.repeat(np.array([5]), 100000).reshape(1, 100000)
So we want to get: [ 0, 0, 1, 4, 5, 6, 7, 8, 9, 10], repeated 100,000 times.
I've managed the function below which provides the desired outcome:
def func(a, b):
n = np.copy(a)
m = np.copy(b)
for i in range(len(n)):
n[i] = np.where(n[i] >= m, n[i] - m, 0)
m = np.maximum(0, m - a[i])
if not m.any():
return n
return n
However, it's not fully vectorized. So:
>> timeit func(a, b)
3.23 ms Β± 52.3 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each)
Ideally, I'd like to get rid of the for-loop and make this as vectorized as possible.
Thanks.
A: I think you can vectorize your function like this:
import numpy as np
def func_vec(a, b):
ar = np.roll(a, 1, axis=0)
ar[0] = 0
ac = np.cumsum(ar, axis=0)
bc = np.maximum(b - ac, 0)
return np.maximum(a - bc, 0)
Quick test:
import numpy as np
def func(a, b):
n = np.copy(a)
m = np.copy(b)
for i in range(len(n)):
n[i] = np.where(n[i] >= m, n[i] - m, 0)
m = np.maximum(0, m - a[i])
if not m.any():
return n
return n
np.random.seed(100)
n = 100000
m = 10
num_max = 100
a = np.random.randint(num_max, size=(m, n))
b = np.random.randint(num_max, size=(1, n))
print(np.all(func(a, b) == func_vec(a, b)))
# True
However, your algorithm has an important advantage over the vectorized algorithm, which is that it stops the iteration when it finds that there is nothing else to subtract. This means that, depending on the size of the problem and the specific values (which is what determines when does the early stop happens, if at all), the vectorized solution may actually be slower. See for the above example:
%timeit func(a, b)
# 5.09 ms Β± 78.5 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each)
%timeit func_vec(a, b)
# 12.4 ms Β± 939 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each)
You can, however, get something of a "best of both worlds" solution using Numba:
import numpy as np
import numba as nb
@nb.njit
def func_nb(a, b):
n = np.copy(a)
m = np.copy(b)
zero = np.array(0, dtype=a.dtype)
for i in range(len(n)):
n[i] = np.maximum(n[i] - m, zero)
m = np.maximum(zero, m - a[i])
if not m.any():
return n
return n
print(np.all(func(a, b) == func_nb(a, b)))
# True
%timeit func_nb(a, b)
# 3.36 ms Β± 461 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54651188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Optimise a MySQL query I am using MySQL 8.0.20 and I have a huge table with some data in it.
CREATE TABLE `db_table` (
`utcDateTime` datetime DEFAULT NULL,
`dateTime` datetime DEFAULT NULL,
`col1` varchar(250) DEFAULT NULL,
`col2` varchar(10) DEFAULT NULL,
`col3` varchar(5) NOT NULL DEFAULT '1',
`col4` varchar(5) NOT NULL DEFAULT '1',
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_dateIns` (`utcDateTime`,`col2`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8'
Below is the query I am trying to optimise,
SELECT col3,col4
from db_table
WHERE col2='123456'
AND (dateTime BETWEEN '2020-11-25 00:01' AND '2020-11-26 00:00')
group by utcDateTime
order by utcDateTime asc limit 1;
This query takes about 12 seconds to execute. But if I change the sorting order to desc, it takes about 0.015 seconds.
Can someone please help optimise the query or the database table?
Thank you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65008658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Discord.py (Rewrite) on_member_update not working properly I have a question about the on_member_update function of the discord.py package.
My Issue is that the on_member_update function only triggers when the bot itself is updated (like a role update) and not when an other user is updated (how it's supposed to work).
Here is a breakdown of my Code:
import discord
from discord.ext import commands
import sys
TOKEN = 'myToken'
BOT_PREFIX = '!'
Intents = discord.Intents()
Intents.members = True
Intents.presences = True
bot = commands.Bot(command_prefix=BOT_PREFIX, Intents = Intents)
@bot.event
async def on_ready():
print("Logged in as: " + bot.user.name + "\n")
@bot.event
async def on_member_update(before, after):
if str(before.status) == "online":
if str(after.status) == "offline":
print("{} has gone {}.".format(after.name,after.status))
else:
print("lol")
@bot.command(pass_context=True)
async def stop(ctx):
await ctx.author.send("bot stopped")
sys.exit(0)
bot.run(TOKEN)
Hope you have an idea how to make it work.
Thank you for your help!
A: You should enable the presences intents for your bot from the developers portal like in the image below.
discord developer portal
https://i.stack.imgur.com/cAn8m.png
A: The accepted solution didn't work for me.
I needed to change:
on_member_update to on_presence_update according to the migration guide:
https://nextcord.readthedocs.io/en/latest/migrating_2.html
"on_presence_update() replaces on_member_update() for updates to Member.status and Member.activities."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64838972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: I am trying to make a real-time auto-correct sort of add-on for Google Docs using Google Apps Script I am trying to make a real-time auto-correct sort of add-on for Google Docs using Google Apps Script. I have written a lot of code, yet cannot figure out why the fixWords function does not work. Whenever I type a word, it does not auto-correct. This is my code:
function fixWords() {
var body = DocumentApp.getActiveDocument().getBody();
//The start of replacing...
body.replaceText("accomodate","accommodate");
body.replaceText("accomodation","accommodation");
body.replaceText("acheive","achieve");
body.replaceText("accross","across");
body.replaceText("agressive","aggressive");
body.replaceText("agression","aggression");
body.replaceText("apparantly","apparently");
body.replaceText("appearence","appearance");
body.replaceText("arguement","argument");
body.replaceText("assasination","assassination");
body.replaceText("basicly","basically");
}
Any suggestions? I am a newbie to Apps Script but have programming for three years.
A: There is something in Docs for automatic substitution. Under the tools, menu, click preferences. You can also add a personal dictionary.
If you could add a personal dictionary from code, that would probably work, but I don't see a way to do that.
There is no trigger or way to monitor a Google doc for every keystroke made. See the documentation:
Trigger Events
Something would need to trigger your function to run on every keystroke. In a spreadsheet, there is an onEdit() simple trigger that monitors every change to a cell. But there is nothing like that for Google Docs.
The only event type available to a Google Doc is open.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30315225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: HSQL + Hibernate Exception: Wrong column type: Found: double, expected: float I am using in-memory HSQL (HSQLDB) with Hibernate for all my unit tests, because it is very fast. I have a table with a column defined as follows:
float qw;
When hibernate starts, I get the following error:
org.hibernate.HibernateException: Wrong column type in MyTable for column qw.
Found: double, expected: float
Why does it find double when the column is declared as float?
A: This is happening due to a series of unfortunate events.
*
*The problem begins with the fact that HSQLDB does not support the
float data type.
(Duh? Yes, I know, but Documentation
here.)
*The problem starts becoming ugly due to the fact that HSQLDB does
not simply fail when you specify a float column, but it
silently re-interprets it as double. If you later query the type
of that column, you will find that it is not float, it is
double.
A typical example of programmers applying their misguided
notions of "defensive programming", creating far more trouble than
they are saving. HSQLDB is essentially pretending to the
unsuspecting programmer that everything went fine, but it is only
trolling them: nothing went fine, and there will be trouble.
*Then, later, hibernate finds this column to be double, while it
expects it to be float, and it is not smart enough to know that
float is assignable from double, so it fails.
Everyone knows that a double is better than a float, so
hibernate should actually be happy that it found a double while
all it needed was a float, right? --but no, hibernate will not
have any of that: when it expects a float, nothing but a float
will do.
*Then, there is this funny thing about hibernate supposedly having
built-in support for HSQLDB, as evidenced by the fact that it
includes a class org.hibernate.dialect.HSQLDialect, but the
dialect does not take care of floats.
So, they don't believe that a data type incompatibility is a
dialect issue? they never tested it with floats? I don't know what
to suppose, but the truth of the matter is that the hibernate
dialect for HSQLDB does not provide any correction for this
problem.
So, what can we do?
One possible solution to the problem is to create our own hibernate dialect for HSQLDB, in which we correct this discrepancy.
In the past I came across a similar problem with MySQL and boolean vs. bit, (see this question: "Found: bit, expected: boolean" after Hibernate 4 upgrade) so for HSQLDB I solved the problem with float vs. double by declaring my own HSQLDB dialect for hibernate:
/**
* 'Fixed' HSQL Dialect.
*
* PEARL: HSQL seems to have a problem with floats. We remedy this here.
* See https://stackoverflow.com/q/28480714/773113
*
* PEARL: this class must be public, not package-private, and it must have a
* public constructor, otherwise hibernate won't be able to instantiate it.
*/
public class FixedHsqlDialect extends HSQLDialect
{
public FixedHsqlDialect()
{
registerColumnType( java.sql.Types.FLOAT, "double" );
}
}
And using it as follows:
ejb3cfg.setProperty( "hibernate.dialect", FixedHsqlDialect.class.getName() );
//Instead of: org.hibernate.dialect.HSQLDialect.class.getName();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28480714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: could not access all 'gmail' messages using pop3 in java My Mail receive programme in java
i use mail.1.4.jar and activation jar in my java programme
There are 5 steps i followed to receive the email using JavaMail API.
They are:
Get the session object
create the POP3 store object and connect with the pop server
create the folder object and open it
retrieve the messages from the folder in an array and print it
close the store and folder objects
here is my code :
public class receive_Email {
public static void main(String[] args) {
String host="pop.gmail.com";
String mailStorType="pop3";
String Username="***********@gmail.com";
String Password="*******";
receiveMail(host, mailStorType, Username, Password);
}
// method for Receive email.....!
public static void receiveMail(String pop3Host,String sotreType,String user,String password){
/// 1) get session object
Properties props=new Properties();
props.put("mail.pop3.host", pop3Host );
Session sessEmail=Session.getDefaultInstance(props);
// 2) create pop3 store object and connect with pop server
try {
POP3Store emailStore=(POP3Store)sessEmail.getStore(sotreType);
emailStore.connect(user,password);
// 3) create Folder object and open it
Folder emailFolder=emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// 4) Retrieve the messages in the folder and display it
Message[] messages=emailFolder.getMessages();
int i=0;
for(Message m : messages){
System.out.println("------------------------------------------------");
System.out.println("Email Number : "+m.getMessageNumber());
System.out.println("Subject : "+m.getSubject());
System.out.println("From : "+m.getFrom());
try {
System.out.println("Subject : "+m.getContent().toString());
} catch (IOException e) {
System.out.println("No messages are available.............!");
e.printStackTrace();
}
} // end for loop
// 5) Close the Folder and email store
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Exception I got is :
javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:148)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:176)
at com.mwh.DBConnect.receive_Email.receiveMail(receive_Email.java:37)
at com.mwh.DBConnect.receive_Email.main(receive_Email.java:22)
Caused by: java.net.ConnectException: Connection timed out: connect
.....
..
any suggestions to get rid of this exception... thanks in advance....
A: Im quite certain that GMail only accepts SSL Connections. Try following Code:
import com.sun.mail.pop3.POP3Store;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import java.io.IOException;
import java.util.Properties;
public class receive_Email {
public static void main(String[] args) {
String host="pop.gmail.com";
int port=995;
String mailStorType="pop3";
String Username="***********@gmail.com";
String Password="*******";
receiveMail(host, port, mailStorType, Username, Password);
}
// method for Receive email.....!
public static void receiveMail(String pop3Host, int port, String sotreType,String user,String password){
/// 1) get session object
Properties props = new Properties();
props.put("mail.pop3.ssl.enable", "true"); // Use SSL
Session sessEmail = Session.getInstance(props);
// 2) create pop3 store object and connect with pop server
try {
POP3Store emailStore = (POP3Store) sessEmail.getStore(sotreType);
emailStore.connect(pop3Host, port, user, password);
// 3) create Folder object and open it
Folder emailFolder=emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// 4) Retrieve the messages in the folder and display it
Message[] messages=emailFolder.getMessages();
for(Message m : messages){
System.out.println("------------------------------------------------");
System.out.println("Email Number : "+m.getMessageNumber());
System.out.println("Subject : "+m.getSubject());
System.out.println("From : "+m.getFrom());
try {
System.out.println("Subject : "+m.getContent().toString());
} catch (IOException e) {
System.out.println("No messages are available.............!");
e.printStackTrace();
}
} // end for loop
// 5) Close the Folder and email store
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
A: I got Answer as i required thanks user user1232141 for ur kind replay..
I got the solution from this reference stactoverflow : reding all new mails
Here is the code that worked for me :
public static void receiveEmail(String pop3Host, String storeType,final String user, final String password) {
try {
//1) get the session object
Properties props = new Properties();
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.ssl.enable", "true"); // Use SSL
props.put("mail.pop3.user", user);
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
//2) create the POP3 store object and connect with the pop server
Store emailStore = (Store) session.getStore(storeType);
emailStore.connect("pop.gmail.com",995,user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (MessagingException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
as you can see i edited provided method receiveEmail(..){....} and got the answer,
Thank you srackoverflow user @wael your question helped me to find my required solution... Thank u all...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22246680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: p tag will slide down but wont slide up Have a question and answer system where the answer starts of hidden, then when the question is clicked, the answer slides down. This is working fine, but then I would like it so that if the question is then clicked again, the answer slides back up. At the moment it is just ignoring that command. The remove/add class is working so I cant think what else it can be?
HTML:
<h2 class="traverse">What subjects are covered in the Core Knowledge Sequence UK?</h2>
<p class="traversing">The Core Knowledge Sequence UK is a guideline of the fundamental skills and content to cover in English, maths, history and geography, science, music and visual arts.</p>
Jquery:
$(".traverse").click(function(){
$(this).next("p.traversing").slideDown();
$(this).removeClass('traverse');
$(this).addClass('traversed');
});
$(".traversed").click(function(){
$(this).next("p.traversing").slideUp();
$(this).removeClass('traversed');
$(this).addClass('traverse');
});
A: The trick is you are adding the traversed class upon the user action... after you have attached the event handler to all matches with jQuery (thus the new element isn't caught)
I'd recommend a change of approach. Keep a class on the elements that can be toggled, and just slide up/down as needed using .toggle();
e.g.
$('.collapsible').toggle(function(){
$(this).next('p.traversing').slideUp();
}, function(){
$(this).next('p.traversing').slideDown();
}
);
Here's a demo: http://jsfiddle.net/7aVkx/1/
A: dont attach click handler multiple times instead use slideToggle()
$(".traverse").click(function(){
$(this).next("p.traversing").slideToggle();
$(this).removeClass('traverse');
$(this).addClass('traversed');
});
A: you could do a live click bind. as you are adding this class to the paragraph after the load, it wont find a reference to it.
$(".traversed").live("click",function(){});
Is there a reason why you want to change the class? An aternative might be to use slideToggle() and leave the class alone.
A: You would have to use .live for this since you (in your click handlers) constantly adding/removing classes that are used to select elements to handle.
Doing just:
$(".traverse").click(....)
Doesn't "track" future elements that may have "traverse" class. It should work fine if you will use:
$(".traverse").live("click", ....)
A: $('p.traversing').slideUp();
$(".traverse").click(function() {
$(this).removeClass('traverse').addClass('traversed');
$(this).next("p.traversing").slideToggle();
});
$(".traversed").click(function() {
$(this).next("p.traversing").slideToggle();
$(this).removeClass('traversed').addClass('traverse');
});
A: You're setting the handler on all elements of class .traversed, but at that time your desired elements don't have that class.
Use .live instead:*
$(".traverse").live('click', function(){
$(this).next("p.traversing").slideDown();
$(this).removeClass('traverse');
$(this).addClass('traversed');
});
$(".traversed").live('click', function(){
$(this).next("p.traversing").slideUp();
$(this).removeClass('traversed');
$(this).addClass('traverse');
});
Live demo.
* "Description: Attach a handler to the event for all elements which match the current selector, now and in the future."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7190778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tracking pinterest pinit button I was trying to implement a way to track pinit button as described here
here is my code:
var fbUrl = RootLink;
var trackUrl = "//pinterest.com/pin/create/button/?url=" + RootLink + "&media=" +
RootLink + "trackPinit.php?userId=" + userId + "%26itemId=" +
items[cnt].item_id +
"%26image="+encodeURIComponent(items[cnt].item_img) +
"&description=Next%20stop%3A%20Pinterest";
trackUrl = encodeURIComponent(trackUrl);
var url = "<a href='JavaScript:newPopup(\"" + trackUrl + "\",\"" +
items[cnt].item_id +
"\");'><img src='//assets.pinterest.com/images/pidgets/pin_it_button.png'/></a>"
jQuery( "#i-cell-" + cnt_rows + "-" +
cnt_cells).append($("<div>").append($(url))
);
and php page:
$userAgent = isset($_SERVER['HTTP_USER_AGENT'])
? $_SERVER['HTTP_USER_AGENT']
: '';\
if ( preg_match('/^Pinterest/d+.d+.*$/', $userAgent) ) {
echo "ccccc";
}
header('Location: ' . $_GET['image'] . "&size=" . $_GET['size'] .
"&tid=".$_GET['tid'] , true, 301
);
image is uploaded when window popup, but when i click the button pinit, I am getting the error "Sorry we could not fetch the image."
could you please help to figure out what is the problem.
A: Mohammed,
The Pinterest web service tries to access the image you send in the 'media' parameter in order to display the image in the Pinterest popup.
If the Pinterest service cannot locate the image at the specified path (http status 404), or does not have access to the image (for example status 403 - forbidden), you will see the error you mention above.
I suggest you ensure the image is located at a URL that will respond with http status 200 - success.
A: I discover that I am using the local Domain, which is not accessible by pinterest, I uploaded all files to online server with real domain and problem solved
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18959875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get an incoming SMS' phone number? How do I get an incoming SMS' phone number?
I wrote BroadcastReciever as in this link, but I don't get any output. Also the Toast message in that BroadcastReciever does not get displayed.
Here is another sms.java file for which I used that BroadcastReciever.
public class SMS extends Activity {
/** Called when the activity is first created. */
Button btn;
EditText edt1;
EditText edt2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button) findViewById(R.id.btn1);
edt1=(EditText) findViewById(R.id.edt1);
edt2=(EditText) findViewById(R.id.edt2);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String phone=edt1.getText().toString();
String message=edt2.getText().toString();
if (phone.length()>0 && message.length()>0)
sendSMS(phone, message);
else
Toast.makeText(getApplicationContext(),
"Enter the phone_no & message.", Toast.LENGTH_SHORT).show();
}
});
}
private void sendSMS(String phoneNumber, String message)
{
Intent i1 = new Intent(this, SMS.class);
PendingIntent pi = PendingIntent.getActivity(this, 0,
i1 , 0);
SmsManager SMS1 = SmsManager.getDefault();
SMS1.sendTextMessage(phoneNumber, null, message, pi, null);
}
}
A: You can get the phone number of incoming SMS in the following manner.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String string = "";
String phone = "";
if (bundle != null)
{
//---receive the SMS message--
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
phone = msgs[i].getOriginatingAddress(); // Here you can get the phone number of SMS sender.
string += msgs[i].getMessageBody().toString(); // Here you can get the message body.
}
}
And important thing you need is to mention permission in menifest file.(i.e. ). And in your Broadcast receiver class you have to mention <actionandroid:name="android.provider.Telephony.SMS_RECEIVED"> in your intent-filter.
A: Use the getOriginatingAddress method.
A: Set the correct manifest file settings for receiving an incoming SMS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5693914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Writing unit test for service function I need some help to write test for the below method in the service layer. I am not sure how to mock those methods (in DAO as wells as in same service layer) in Mockito for this service. Before that I think I should mock whole for loop to avoid mocking of each of those methods. What is the proper way to write unit test for such method.
public List<CheckupHistoryDto> getCaseHistory(Individual patient, Individual doctor) {
List<CheckupHistoryDto> checkupHistoryList = new ArrayList<ClaimHistoryDto>();
List<CaseHistory> caseHistoryIds = caseDetailDao.fetchCaseIds(patient.getId(), doctor.getId());
for(CaseHistory caseHistory : caseHistoryIds) {
CheckupHistoryDto checkupHistoryDto = new CheckupHistoryDto();
checkupHistoryDto.setDateOfCall(formatter.format(caseHistory.getCreateDate()));
checkupHistoryDto.setPatientInfo(getPatientInfo(patient));
checkupHistoryDto.setDoctorInfo(getDoctorInfo(doctor));
checkupHistoryDto.setServiceProvided(caseDetailDao.fetchServiceHistory(caseHistory.getEventId()));
checkupHistoryList.add(checkupHistoryDto);
}
return checkupHistoryList;
}
public Patient getPatientInfo(patient) {
...
}
public Doctor getDoctorInfo(doctor) {
...
}
And my test case
@Test
public void testHistoryList() {
Individual patient = Mockito.mock(Individual.class);
Individual doctor= Mockito.mock(Individual.class);
List<CheckupHistoryDto> checkupHistory = caseService.getCaseHistory(patient, doctor);
assertEquals(MOCK_LIST_SIZE, checkupHistory.size());
}
A: Forget about "mocking the for loop", that makes no sense since it is part of the functionality you want to test; specifically, when you unit test class XQ, you never mock any portion of class XQ.
you need to mock the following:
*
*Individual.getId for the patient.
*Individual.getId for the doctor.
*whatever methods on the Individual class that are used by getPatientInfo method, for the patient.
*whatever methods on the Individual class that are used by the getDoctorInfo method, for the doctor.
*caseDetailDao.fetchCaseIDs
*caseDetailDao.fetchServiceHistory
*caseHistory.getCreateDate, if you return a list of mock objects from fetchCaseIds.
*caseHistory.getEventId, if you return a list of mock objects from fetchCaseIds.
You have some terrible code:
*
*caseHsitory.fetchCaseIds is clearly not returning caseIDs, it is returning case details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26589708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding football foul that results in succesful shot on target I have a dataframe that contains a foul made by a player which eventually leads to a shot on target.
What I want to do is create a new column that puts either TRUE/FALSE, where TRUE is set, if the foul of a player leads to a successful shot on target by the opponent (thus the opposite team of the player that made a foul). This should happen within 120 seconds (from the time_seconds column). Rows 15 and 16 provide an example:
In row 15 the away-team (i.e. home_team == FALSE) commits a foul,
where in row 16, the home-team (i.e. home_team == TRUE) successfully shoots on target.
The timedifference is time_seconds[16] - time_seconds[15], which is approximately 99 seconds.
If this occurs, the new column should put TRUE in row 15.
df1 <- structure(list(game_id = c(303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L, 303377L, 303377L,
303377L, 303377L, 303377L, 303377L, 303377L), period_id = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), time_seconds = c(37.89,
84.336, 180.625, 362.881, 550.039, 704.435, 834.098, 854.326,
903.619, 1019.792, 1295.223, 1334.372, 1535.632, 1753.75, 1879.466,
1978.405, 2066.09, 2130.795, 2238.76, 2328.484, 2463.017, 2559.583,
2652.39, 2793.922, 2835.15, 2873.929, 125.536, 208.099, 537.49,
706.794, 729.908, 748.267, 801.87, 903.612, 908.616, 1199.159,
1203.156, 1254.885, 1344.534, 1410.775, 1449.815, 1559.749, 1608.552,
1622.401, 1706.33, 1707.425, 1790.318, 1836.601, 1863.396, 1911.467,
2065.581, 2184.689, 2235.202, 2407.699, 2570.467, 2676.898, 2720.759,
2884.097), home_team = c(TRUE, FALSE, FALSE, FALSE, FALSE, TRUE,
TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE,
TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE,
TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE,
TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE,
TRUE, FALSE, FALSE), player_name = c("Frenkie de Jong", "Jorge Molina Vidal",
"Marc Cucurella Saseta", "DjenΓ© Dakonam Ortega", "Mauro Wilney Arambarri Rosa",
"Lionel AndrΓ©s Messi Cuccittini", "Lionel AndrΓ©s Messi Cuccittini",
"Jaime Mata Arnaiz", "Allan Romeo Nyom", "Oghenekaro Etebo",
"Jorge Molina Vidal", "Allan Romeo Nyom", "Marc Cucurella Saseta",
"Allan Romeo Nyom", "Jaime Mata Arnaiz", "Antoine Griezmann",
"Jorge Molina Vidal", "Arthur Henrique Ramos de Oliveira Melo",
"Anssumane Fati", "Sergi Roberto Carnicer", "Mauro Wilney Arambarri Rosa",
"Jaime Mata Arnaiz", "Samuel Yves Umtiti", "Mauro Wilney Arambarri Rosa",
"Mauro Wilney Arambarri Rosa", "Lionel AndrΓ©s Messi Cuccittini",
"Oghenekaro Etebo", "Samuel Yves Umtiti", "Gerard PiquΓ© BernabΓ©u",
"Anssumane Fati", "Γngel Luis RodrΓguez DΓaz", "DjenΓ© Dakonam Ortega",
"Lionel AndrΓ©s Messi Cuccittini", "Xabier Etxeita Gorritxategi",
"DjenΓ© Dakonam Ortega", "Arthur Henrique Ramos de Oliveira Melo",
"Sergio Busquets i Burgos", "Γngel Luis RodrΓguez DΓaz", "Mauro Wilney Arambarri Rosa",
"Mauro Wilney Arambarri Rosa", "Anssumane Fati", "Sergio Busquets i Burgos",
"Γngel Luis RodrΓguez DΓaz", "Jaime Mata Arnaiz", "Anssumane Fati",
"Antoine Griezmann", "Frenkie de Jong", "Robert Kenedy Nunes do Nascimento",
"Amath Ndiaye", "Antoine Griezmann", "Jaime Mata Arnaiz", "HΓ©ctor Junior Firpo Adames",
"Jaime Mata Arnaiz", "Allan Romeo Nyom", "Robert Kenedy Nunes do Nascimento",
"Lionel AndrΓ©s Messi Cuccittini", "Xabier Etxeita Gorritxategi",
"Γngel Luis RodrΓguez DΓaz"), type_name = c("foul", "foul", "foul",
"foul", "foul", "shot", "shot", "foul", "foul", "foul", "shot",
"foul", "shot", "foul", "foul", "shot", "foul", "foul", "foul",
"shot", "foul", "foul", "foul", "foul", "foul", "shot", "foul",
"foul", "foul", "foul", "foul", "foul", "shot", "foul", "foul",
"foul", "foul", "shot", "foul", "foul", "shot", "foul", "shot",
"foul", "shot", "shot", "foul", "foul", "foul", "shot", "shot",
"foul", "foul", "foul", "foul", "shot", "foul", "foul"), result_name = c("success",
"success", "success", "success", "success", "fail", "fail", "success",
"success", "success", "fail", "success", "fail", "success", "success",
"success", "success", "success", "success", "success", "success",
"success", "success", "success", "success", "fail", "success",
"yellow_card", "success", "success", "success", "success", "fail",
"success", "success", "success", "success", "success", "success",
"success", "fail", "success", "fail", "yellow_card", "fail",
"fail", "success", "success", "success", "fail", "fail", "yellow_card",
"success", "success", "yellow_card", "fail", "success", "success"
)), class = "data.frame", row.names = c(NA, -58L))
# Output
game_id period_id time_seconds home_team player_name type_name result_name
1 303377 1 37.890 TRUE Frenkie de Jong foul success
2 303377 1 84.336 FALSE Jorge Molina Vidal foul success
3 303377 1 180.625 FALSE Marc Cucurella Saseta foul success
4 303377 1 362.881 FALSE DjenΓ© Dakonam Ortega foul success
5 303377 1 550.039 FALSE Mauro Wilney Arambarri Rosa foul success
6 303377 1 704.435 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
7 303377 1 834.098 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
8 303377 1 854.326 FALSE Jaime Mata Arnaiz foul success
9 303377 1 903.619 FALSE Allan Romeo Nyom foul success
10 303377 1 1019.792 FALSE Oghenekaro Etebo foul success
11 303377 1 1295.223 FALSE Jorge Molina Vidal shot fail
12 303377 1 1334.372 FALSE Allan Romeo Nyom foul success
13 303377 1 1535.632 FALSE Marc Cucurella Saseta shot fail
14 303377 1 1753.750 FALSE Allan Romeo Nyom foul success
15 303377 1 1879.466 FALSE Jaime Mata Arnaiz foul success
16 303377 1 1978.405 TRUE Antoine Griezmann shot success
17 303377 1 2066.090 FALSE Jorge Molina Vidal foul success
18 303377 1 2130.795 TRUE Arthur Henrique Ramos de Oliveira Melo foul success
19 303377 1 2238.760 TRUE Anssumane Fati foul success
20 303377 1 2328.484 TRUE Sergi Roberto Carnicer shot success
21 303377 1 2463.017 FALSE Mauro Wilney Arambarri Rosa foul success
22 303377 1 2559.583 FALSE Jaime Mata Arnaiz foul success
23 303377 1 2652.390 TRUE Samuel Yves Umtiti foul success
24 303377 1 2793.922 FALSE Mauro Wilney Arambarri Rosa foul success
25 303377 1 2835.150 FALSE Mauro Wilney Arambarri Rosa foul success
26 303377 1 2873.929 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
27 303377 2 125.536 FALSE Oghenekaro Etebo foul success
28 303377 2 208.099 TRUE Samuel Yves Umtiti foul yellow_card
29 303377 2 537.490 TRUE Gerard PiquΓ© BernabΓ©u foul success
30 303377 2 706.794 TRUE Anssumane Fati foul success
31 303377 2 729.908 FALSE Γngel Luis RodrΓguez DΓaz foul success
32 303377 2 748.267 FALSE DjenΓ© Dakonam Ortega foul success
33 303377 2 801.870 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
34 303377 2 903.612 FALSE Xabier Etxeita Gorritxategi foul success
35 303377 2 908.616 FALSE DjenΓ© Dakonam Ortega foul success
36 303377 2 1199.159 TRUE Arthur Henrique Ramos de Oliveira Melo foul success
37 303377 2 1203.156 TRUE Sergio Busquets i Burgos foul success
38 303377 2 1254.885 FALSE Γngel Luis RodrΓguez DΓaz shot success
39 303377 2 1344.534 FALSE Mauro Wilney Arambarri Rosa foul success
40 303377 2 1410.775 FALSE Mauro Wilney Arambarri Rosa foul success
41 303377 2 1449.815 TRUE Anssumane Fati shot fail
42 303377 2 1559.749 TRUE Sergio Busquets i Burgos foul success
43 303377 2 1608.552 FALSE Γngel Luis RodrΓguez DΓaz shot fail
44 303377 2 1622.401 FALSE Jaime Mata Arnaiz foul yellow_card
45 303377 2 1706.330 TRUE Anssumane Fati shot fail
46 303377 2 1707.425 TRUE Antoine Griezmann shot fail
47 303377 2 1790.318 TRUE Frenkie de Jong foul success
48 303377 2 1836.601 FALSE Robert Kenedy Nunes do Nascimento foul success
49 303377 2 1863.396 FALSE Amath Ndiaye foul success
50 303377 2 1911.467 TRUE Antoine Griezmann shot fail
51 303377 2 2065.581 FALSE Jaime Mata Arnaiz shot fail
52 303377 2 2184.689 TRUE HΓ©ctor Junior Firpo Adames foul yellow_card
53 303377 2 2235.202 FALSE Jaime Mata Arnaiz foul success
54 303377 2 2407.699 FALSE Allan Romeo Nyom foul success
55 303377 2 2570.467 FALSE Robert Kenedy Nunes do Nascimento foul yellow_card
56 303377 2 2676.898 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
57 303377 2 2720.759 FALSE Xabier Etxeita Gorritxategi foul success
58 303377 2 2884.097 FALSE Γngel Luis RodrΓguez DΓaz foul success
The new dataframe should be like this (only 2 TRUE cases for this small example):
game_id period_id time_seconds home_team player_name type_name result_name
1 303377 1 37.890 TRUE Frenkie de Jong foul success
2 303377 1 84.336 FALSE Jorge Molina Vidal foul success
3 303377 1 180.625 FALSE Marc Cucurella Saseta foul success
4 303377 1 362.881 FALSE DjenΓ© Dakonam Ortega foul success
5 303377 1 550.039 FALSE Mauro Wilney Arambarri Rosa foul success
6 303377 1 704.435 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
7 303377 1 834.098 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
8 303377 1 854.326 FALSE Jaime Mata Arnaiz foul success
9 303377 1 903.619 FALSE Allan Romeo Nyom foul success
10 303377 1 1019.792 FALSE Oghenekaro Etebo foul success
11 303377 1 1295.223 FALSE Jorge Molina Vidal shot fail
12 303377 1 1334.372 FALSE Allan Romeo Nyom foul success
13 303377 1 1535.632 FALSE Marc Cucurella Saseta shot fail
14 303377 1 1753.750 FALSE Allan Romeo Nyom foul success
15 303377 1 1879.466 FALSE Jaime Mata Arnaiz foul success
16 303377 1 1978.405 TRUE Antoine Griezmann shot success
17 303377 1 2066.090 FALSE Jorge Molina Vidal foul success
18 303377 1 2130.795 TRUE Arthur Henrique Ramos de Oliveira Melo foul success
19 303377 1 2238.760 TRUE Anssumane Fati foul success
20 303377 1 2328.484 TRUE Sergi Roberto Carnicer shot success
21 303377 1 2463.017 FALSE Mauro Wilney Arambarri Rosa foul success
22 303377 1 2559.583 FALSE Jaime Mata Arnaiz foul success
23 303377 1 2652.390 TRUE Samuel Yves Umtiti foul success
24 303377 1 2793.922 FALSE Mauro Wilney Arambarri Rosa foul success
25 303377 1 2835.150 FALSE Mauro Wilney Arambarri Rosa foul success
26 303377 1 2873.929 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
27 303377 2 125.536 FALSE Oghenekaro Etebo foul success
28 303377 2 208.099 TRUE Samuel Yves Umtiti foul yellow_card
29 303377 2 537.490 TRUE Gerard PiquΓ© BernabΓ©u foul success
30 303377 2 706.794 TRUE Anssumane Fati foul success
31 303377 2 729.908 FALSE Γngel Luis RodrΓguez DΓaz foul success
32 303377 2 748.267 FALSE DjenΓ© Dakonam Ortega foul success
33 303377 2 801.870 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
34 303377 2 903.612 FALSE Xabier Etxeita Gorritxategi foul success
35 303377 2 908.616 FALSE DjenΓ© Dakonam Ortega foul success
36 303377 2 1199.159 TRUE Arthur Henrique Ramos de Oliveira Melo foul success
37 303377 2 1203.156 TRUE Sergio Busquets i Burgos foul success
38 303377 2 1254.885 FALSE Γngel Luis RodrΓguez DΓaz shot success
39 303377 2 1344.534 FALSE Mauro Wilney Arambarri Rosa foul success
40 303377 2 1410.775 FALSE Mauro Wilney Arambarri Rosa foul success
41 303377 2 1449.815 TRUE Anssumane Fati shot fail
42 303377 2 1559.749 TRUE Sergio Busquets i Burgos foul success
43 303377 2 1608.552 FALSE Γngel Luis RodrΓguez DΓaz shot fail
44 303377 2 1622.401 FALSE Jaime Mata Arnaiz foul yellow_card
45 303377 2 1706.330 TRUE Anssumane Fati shot fail
46 303377 2 1707.425 TRUE Antoine Griezmann shot fail
47 303377 2 1790.318 TRUE Frenkie de Jong foul success
48 303377 2 1836.601 FALSE Robert Kenedy Nunes do Nascimento foul success
49 303377 2 1863.396 FALSE Amath Ndiaye foul success
50 303377 2 1911.467 TRUE Antoine Griezmann shot fail
51 303377 2 2065.581 FALSE Jaime Mata Arnaiz shot fail
52 303377 2 2184.689 TRUE HΓ©ctor Junior Firpo Adames foul yellow_card
53 303377 2 2235.202 FALSE Jaime Mata Arnaiz foul success
54 303377 2 2407.699 FALSE Allan Romeo Nyom foul success
55 303377 2 2570.467 FALSE Robert Kenedy Nunes do Nascimento foul yellow_card
56 303377 2 2676.898 TRUE Lionel AndrΓ©s Messi Cuccittini shot fail
57 303377 2 2720.759 FALSE Xabier Etxeita Gorritxategi foul success
58 303377 2 2884.097 FALSE Γngel Luis RodrΓguez DΓaz foul success
foul_goal_concede
1 FALSE
2 FALSE
3 FALSE
4 FALSE
5 FALSE
6 FALSE
7 FALSE
8 FALSE
9 FALSE
10 FALSE
11 FALSE
12 FALSE
13 FALSE
14 FALSE
15 TRUE
16 FALSE
17 FALSE
18 FALSE
19 FALSE
20 FALSE
21 FALSE
22 FALSE
23 FALSE
24 FALSE
25 FALSE
26 FALSE
27 FALSE
28 FALSE
29 FALSE
30 FALSE
31 FALSE
32 FALSE
33 FALSE
34 FALSE
35 FALSE
36 FALSE
37 TRUE
38 FALSE
39 FALSE
40 FALSE
41 FALSE
42 FALSE
43 FALSE
44 FALSE
45 FALSE
46 FALSE
47 FALSE
48 FALSE
49 FALSE
50 FALSE
51 FALSE
52 FALSE
53 FALSE
54 FALSE
55 FALSE
56 FALSE
57 FALSE
58 FALSE
I hope this is clear enough ;')
A: Here is a data.table approach. Probably not the fastest, but it will get the job done.
library(data.table)
# Make it a data.table
setDT(df1)
# Create an id-column
df1[, rowid := .I]
# Set id column as key
setkey(df1, rowid)
# Create temp data.table with all succesfull shots
dt.shot.success <- df1[type_name == "shot" & result_name == "success", ]
# perform join on all fouls
df1[df1[type_name == "foul", ], foul_to_goal_within_120 := {
temp <- dt.shot.success[!home_team == i.home_team &
game_id == i.game_id &
period_id == i.period_id &
time_seconds %between% c(i.time_seconds, i.time_seconds + 120), ]
list(nrow(temp) > 0)
}, by = .EACHI][]
#fouls on row 15, 36 and 37 lead to a successfull shot for the other team within 120 seconds
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67299096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to parse MS Word using Apache POI and convert it into XML? Is it possible to convert a MS Word to XML file using Apache POI ?
If it is, can you point me to any tutorials for doing that?
A: The purpose of HWPF subproject is exactly that: process Word files.
http://poi.apache.org/hwpf/index.html
Then, to convert the data to XML you have to build XML by the ususal ways: StAX, JDOM, XStream...
Apache offers a Quick Guide:
http://poi.apache.org/hwpf/quick-guide.html
and I also have found that:
http://sanjaal.com/java/tag/simple-java-tutorial-to-read-microsoft-document-in-java/
If you want to process docx files, you might want to look at the OpenXML4J subproject:
http://poi.apache.org/oxml4j/index.html
A: I'd say you have two options, both powered by Apache POI
One is to use Apache Tika. Tika is a text and metadata extraction toolkit, and is able to extract fairly rich text from Word documents by making appropriate calls to POI. The result is that Tika will give you XHTML style XML for the contents of your word document.
The other option is to use a class that was added fairly recently to POI, which is WordToHtmlConverter. This will turn your word document into HTML for you, and generally will preserve slightly more of the structure and formatting than Tika will.
Depending on the kind of XML you're hoping to get out, one of these should be a good bet for you. I'd suggest you try both against some of your sample files, and see which one is the best fit for your problem domain and needs.
A: package com.govind.service;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* DOC to XML converter service
*
* @author govind.sharma
*
*/
public class DocToXmlConverter {
static final Logger logger = Logger.getLogger(DocToXmlConverter.class);
DocumentBuilderFactory docFactory = null;
DocumentBuilder docBuilder = null;
Element rootElement = null;
Document docxml = null;
boolean subHeaders = false;
Element UrlElement = null;
/**
* @param path
* @param fileName
*/
public void processDocxToXml(String path, String fileName) {
XWPFDocument xdoc = null;
FileInputStream fis = null;
String fullPath = path + "/" + fileName + ".docx";
try {
// Read file
fis = new FileInputStream(fullPath);
xdoc = new XWPFDocument(OPCPackage.open(fis));
initializeXml();
// get Document Body Paragraph content
List < XWPFParagraph > paragraphList = xdoc.getParagraphs();
for (XWPFParagraph paragraph: paragraphList) {
String styleName = paragraph.getStyle();
String paraText = paragraph.getParagraphText();
String bulletsPoints = paragraph.getNumFmt();
createXmlTags(styleName, paraText, bulletsPoints);
}
// write the content into XML file
generateXml(path, fileName);
logger.info("Doc to Xml Convertion completed.");
} catch (Exception ex) {
logger.error("Exception while generating XML from DOC" + ex.getMessage());
System.exit(0);
}
}
/**
* @param path
* @param fileName
*/
public void processDocToXml(String path, String fileName) {
HWPFDocument doc = null;
String fullPath = path + "/" + fileName + ".doc";
WordExtractor we = null;
try {
POIFSFileSystem fis = new POIFSFileSystem(new FileInputStream(fullPath));
doc = new HWPFDocument(fis);
} catch (Exception e) {
logger.error("Unable to Read File..." + e.getMessage());
System.exit(0);
}
try {
we = new WordExtractor(doc);
Range range = doc.getRange();
initializeXml();
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
int j = 0;
while (true) {
CharacterRun run = pr.getCharacterRun(j++);
StyleDescription style = doc.getStyleSheet().getStyleDescription(run.getStyleIndex());
String styleName = style.getName();
String paraText = run.text();
String bulletsPoints = null;
createXmlTags(styleName, paraText, bulletsPoints);
if (run.getEndOffset() == pr.getEndOffset()) {
break;
}
}
}
generateXml(path, fileName);
logger.info("Document to Xml Convertion completed.");
} catch (Exception ex) {
logger.error("Exception while generating XML from DOC" + ex.getMessage());
System.exit(0);
}
}
/**
*
*/
private void initializeXml() {
// initialize XML Document
try {
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
docxml = docBuilder.newDocument();
rootElement = docxml.createElement("ROOT");
docxml.appendChild(rootElement);
} catch (ParserConfigurationException e) {
logger.error("Exception while initializing XML" + e.getMessage());
}
}
/**
* @param styleName
* @param paragraphText
* @param bulletsPoints
*/
private void createXmlTags(String styleName, String paragraphText, String bulletsPoints) {
// create XML Tags
if (styleName != null && paragraphText.length() > 1) {
if (styleName.equalsIgnoreCase("Style4")) {
Element pragElement = docxml.createElement("TITLE");
pragElement.appendChild(docxml.createTextNode(paragraphText.trim()));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("Default")) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("Normal")) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("BodyCopy") && bulletsPoints != null) {
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
subHeaders = false;
} else if (styleName.equalsIgnoreCase("BodyCopy")) {
Element pragElement = docxml.createElement("PS");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("ListParagraph")) {
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
subHeaders = false;
} else if (styleName.equalsIgnoreCase("Subheader1")) {
UrlElement = docxml.createElement("UL");
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
rootElement.appendChild(UrlElement);
subHeaders = false;
} else {
Element pragElement = docxml.createElement("PS");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
}
} else if (paragraphText.trim().length() > 1) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
}
if (subHeaders) {
Element pragElement = docxml.createElement("NEWLINE");
pragElement.appendChild(docxml.createTextNode(""));
rootElement.appendChild(pragElement);
}
}
/**
* @param path
* @param fileName
*/
private void generateXml(String path, String fileName) {
try {
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(docxml);
StreamResult result = new StreamResult(new File(path + "/" + fileName + ".xml"));
transformer.transform(source, result);
} catch (Exception e) {
logger.error("Exception while generating XML" + e.getMessage());
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8224871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Get the name (or id) of the tile layer clicked in the onclick event (openlayers 3) I created my layers like this:
var wms_bmid_parcels = new ol.source.TileWMS({
url: 'http://176.7.69.145:8080/geoserver/wms',
params: { 'LAYERS': 'bmid-parcels' },
serverType: 'geoserver',
});
In the map.on('singleclick', function (evt) {....}
I need to know what layer was clicked. The
map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
does not work since it work only for vector layers.
Any help will be very much appreciated.
TIA
JJ.
A: You can use map.forEachLayerAtPixel, which will call your callback for any raster layers that are not transparent on the given pixel.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33021224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to process wrapped function arguments in the same order as visible for original function? I am trying to examine the types of functions arguments before the call (in this example it is foo). I am using python decorators to achieve this. I don't see how I can get arguments in the same order as they are visible to the function foo. In the following example, I get two different orderings but have essentially the same function call.
def wrapper(func):
def f(*args, **kwargs):
print([type(x) for x in args] + [type(v) for v in kwargs.values()])
return func(*args, **kwargs)
return f
@wrapper
def foo(a, b, c, d):
print(f"{a} {b} {c} {d}")
foo(10, 12.5, 14, 5.2) # all good: int, float, int, float
foo(10, 12.5, d=5.2, c=14) # not what I want: int, float, float, int
Is it possible to get arguments in a consistent order? If not, then is it at least possible to get them all keyed by argument name? Something that looks like this:
def wrapper(func):
def f(**kwargs):
# kwargs = {'a': 10, 'b': 12.5, 'c': 14, 'd': 5.2}
print([type(v) for v in kwargs.values()])
return func(*args, **kwargs)
return f
foo(10, 12.5, 14, 5.2) # obviously doesn't work
A: The type-checking is a bit weak, the annotations works as long you annotate your code but a more robust way can be achieved by using inspect from the standard library:
it provides full access to frame, ... and everything you may need. In this case with inspect.signature can be used to fetch the signature of the original function to get a the original order of the parameters. Then just regroup the parameters and pass the final group back to the original function. More details in the comments.
from inspect import signature
def wrapper(func):
def f(*args, **kwargs):
# signature object
sign = signature(func)
# use order of the signature of the function as reference
order = order = dict.fromkeys(sign.parameters)
# update first key-values
order.update(**kwargs)
# update by filling with positionals
free_pars = (k for k, v in order.items() if v is None)
order.update(zip(free_pars, args))
return func(**order)
return f
@wrapper
def foo(a, b, c, d):
print(f"{a} {b} {c} {d}")
foo(10, 12.5, 14, 5.2)
#10 12.5 14 5.2
foo(10, 12.5, d=5.2, c=14)
#10 12.5 14 5.2
The code is annotations compatible:
@wrapper
def foo(a: int, b: float, c: int, d: float) -> None:
print(f"{a} {b} {c} {d}")
The annotation's way, no imports required:
It is a copy past of the above code but using __annotations__ attribute to get the signature. Remember that annotations may or may not have an annotation for the output
def wrapper(func):
def f(*args, **kwargs):
if not func.__annotations__:
raise Exception('No clue... inspect or annotate properly')
params = func.__annotations__
# set return flag
return_has_annotation = False
if 'return' in params:
return_has_annotation = True
# remove possible return value
return_ = params.pop('return', None)
order = dict.fromkeys(params)
order.update(**kwargs)
free_pars = (k for k, v in order.items() if v is None)
order.update(zip(free_pars, args))
# update with return annotation
if return_has_annotation:
func.__annotations__ = params | {'return': return_}
return func(**order)
return f
@wrapper
def foo(a: int, b: float, c: int, d: float) -> None:
print(f"{a} {b} {c} {d}")
A: The first thing to be careful of is that key word arguments are implemented because order does not matter for them and are intended to map a value to a specific argument by name at call-time. So enforcing any specific order on kwargs does not make much sense (or at least would be confusing to anyone trying to use your decorater). So you will probably want to check for which kwargs are specified and remove the corresponding argument types.
Next if you want to be able to check the argument types you will need to provide a way to tell your decorator what types you are expected by passing it an argument (you can see more about this here). The only way to do this is to pass a dictionary mapping each argument to the expected type:
@wrapper({'a': int, 'b': int, c: float, d: int})
def f(a, b, c=6.0, d=5):
pass
def wrapper(types):
def inner(func):
def wrapped_func(*args, **kwargs):
# be careful here, this only works if kwargs is ordered,
# for python < 3.6 this portion will not work
expected_types = [v for k, v in types.items() if k not in kwargs]
actual_types = [type(arg) for arg in args]
# substitute these in case you are dead set on checking for key word arguments as well
# expected_types = types
# actual_types = [type(arg) for arg in args)] + [type(v) for v in kwargs.items]
if expected_types != actual_types:
raise TypeError(f"bad argument types:\n\tE: {expected_types}\n\tA: {actual_types}")
func(*args, **kwargs)
return wrapped_func
return inner
@wrapper({'a': int, 'b': float, 'c': int})
def f(a, b, c):
print('good')
f(10, 2.0, 10)
f(10, 2.0, c=10)
f(10, c=10, b=2.0)
f(10, 2.0, 10.0) # will raise exception
Now after all of this, I want to point out that this is functionality is probably largely unwanted and unnecessary in python code. Python was designed to be dynamically typed so anything resembling strong types in python is going against the grain and won't be expected by most.
Next, since python 3.5 we have had access to the built-in typing package. This lets you specify the type that you expect to be receiving in a function call:
def f(a: int, b: float, c: int) -> int:
return a + int(b) + c
Now this won't actually do any type assertions for you, but it will make it plainly obvious what types you are expecting, and most (if not all) IDEs will give you visual warnings that you are passing the wrong type to a function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72632468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: python responses library prepends part of the URL to the request params I am trying to mock an external API using the responses library.
I want to check I've passed my params correctly in my request, so I am using this minimum working example from the responses docs:
import responses
import requests
@responses.activate
def test_request_params():
responses.add(
method=responses.GET,
url="http://example.com?hello=world",
body="test",
match_querystring=False,
)
resp = requests.get('http://example.com', params={"hello": "world"})
assert responses.calls[0].request.params == {"hello": "world"}
The problem is, this breaks as soon as I replace http://example.com with a URL that resembles an API endpoint:
@responses.activate
def test_request_params():
responses.add(
method=responses.GET,
url="http://example.com/api/endpoint?hello=world",
body="test",
match_querystring=False,
)
resp = requests.get('http://example.com/api/endpoint', params={"hello": "world"})
assert responses.calls[0].request.params == {"hello": "world"}
Now responses has added part of the URL to the first query param:
> assert responses.calls[0].request.params == {"hello": "world"}
E AssertionError: assert {'/api/endpoint?hello': 'world'} == {'hello': 'world'}
Am I missing something?
A: You can pass a regex as the url argument, which ignores parameters:
@responses.activate
def test_request_params():
url = r"http://example.com/api/endpoint"
params = {"hello": "world", "a": "b"}
# regex that matches the url and ignores anything that comes after
rx = re.compile(rf"{url}*")
responses.add(method=responses.GET, url=rx)
response = requests.get(url, params=params)
assert responses.calls[-1].request.params == params
url_path, *queries = responses.calls[-1].request.url.split("?")
assert url_path == url
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62452119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Keep nav list item selected when submenu is open How do I change the CSS so that a main menu list item stays selected when clicked? I can change the background color on hover, but I'd really like the background color to change when clicked until I click on something else. My submenu displays on click, not hover, which is why hover does not work for me.
For example, on www.IBM.com, the style of the selected list item in the main menu changes when clicked, not just on hover.
Here is what I have:
<div class="header">
<ul class="site-nav">
<li class="first">
<a href="#">Home</a>
</li>
<li>
<div class="quick-more">
<a class="drop-link">Support</a>
<ul class="dropdown" style="display: block;">
......etc.
<li>Community</li>
<li>Contact</li>
</ul>
</div>
In my CSS, I have the following:
.site-nav {
background: #1f78c3;
}
.site-nav .dropdown {
background: #fff;
padding: 0;
border: 0;
}
.site-nav li a:hover{
background: #fff;
color: #1f78c3;
}
I've also tried a:visited and a:target, but neither of those did the trick. Any idea of what I'm missing?
A: You could add a .selected to a link on different pages and target it with CSS.
A: The method I would use is a javascript/jQuery approach.
Similar to what htmltroll said, create a class, such as .selected, that has all of the styles you'd like the active link to have. Then in javascript, add something like this:
$(your-links).click(function(){
if (!$(this).hasClass("selected"))$(this).addClass("selected");
})
Something along those lines.
A: As @htmltroll and @Joel said, you'd need to use a little bit of JS(jQuery in my case) to achieve this, as CSS doesn't handle click events.
To make it a bit more modular, you could check to see if any .site-nav li has a nested ul, and then apply the 'active' class accordingly.
// any <li> that is a direct descendant of 'site-nav
var links = $('.site-nav').find('> li');
// bind the click event
links.on('click', function() {
var clkd = $(this);
// if the <li> has a <ul> in it
if(clkd.has('ul').length) {
// and if that <li> doesn't have the 'active' class
if(!clkd.hasClass('active')) {
// Add the active class to the <li>
clkd.addClass('active');
} else {
// if the dropdown was already open, remove class to close
clkd.removeClass('active');
}
}
})
I threw together a quick fiddle to demonstrate: http://jsfiddle.net/uXB2T/7/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19713316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Send a ZIP file for a server using kotlin and retrofit I looking for a way to send a zip file for a server using retrofit in kotlin. Some functions are deprecated that's make this more dificulte. When I star the request the response is NULL, there is no error.
That is the function who start the request:
fun sendZipeFile() {
val retrofitClient = NetworkUtils
.getRetrofitInstance("http://url.com")
val sendZipeFileEndPoint = retrofitClient.create(SendZipeFile::class.java)
var file = File("/storage/emulated/0/Download/file.zip")
val requestImageFile = file?.asRequestBody("multipart/form-data".toMediaType())
val callback = startZipeFileUpload.zipeFileUpload("application/zip","AtualizaΓ§Γ£o", requestImageFile, "0.0.2")
callback.enqueue(object : Callback<UploadZipFile> {
override fun onFailure(call: Call<UploadZipFile>, t: Throwable) {
t.message
t.fillInStackTrace()
}
override fun onResponse(call: Call<UploadZipFile>, response: Response<UploadZipFile>) {
val responseString = response.body()
}
})
}
Below is an interface
interface SendZipeFile{
@Headers("Content-Type: multipart/form-data")
@Multipart
@POST("updateModelsAndParameters/" +
"")
fun zipeFileUpload(
@Header("Content-Type") contentType: String?,
@Part("description") description: String?,
@Part("Zip") file: RequestBody?,
@Part("flag")flag: String?,
): Call<UploadZipFile>
}
And the data class
import com.google.gson.annotations.SerializedName
data class UploadZipFile(
@SerializedName("status_code") var statusCode: Int? = null,
@SerializedName("message") var message: String? = null,
@SerializedName("elapsed_ms") var elapsedMs: Double? = null,
@SerializedName("response") var resposta: Boolean? = null,
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72737139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery pause pre-display on hover for mega menu Got a lil one, need a mega menu to appear after a brief pause on hover else it shows up immediately with every mouse over which is a bit hectic.
Mega menu worked lovely until the hover thing became incredibly annoying!
Tried using hoverIntent but can't figure out the functions required for it to stop 'un-displaying' on mouse out of just the link, rather than the link and the menu if that makes sense?
My probably pants code is thus...
$("li.view_products a").add('.megamenu').hover(
function(){
$('.megamenu').removeClass('no_show');
},
function(){
$('.megamenu').addClass('no_show');
}
)
I have been scoping through previously asked questions and seen some mentions of SetTimeOut etc? but I can't make head or tail of it.
A: Do you try with a jquery accordion?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14821053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why Angular website (irctc.co.in) require to put Script WaitForAngularEnabled false.? without this code is not worked describe('Protractor Alert steps', function () {
it('Open Angular js website Alerts', function () {
browser.waitForAngularEnabled(false);
browser.get("https://www.irctc.co.in/nget/train-search");
element(by.xpath("//button[contains(text(),'Ok')]")).click();
})
})
Now it is worked with above code but can u explain me
This is angular website then why below statement is required to be false
browser.waitForAngularEnabled(false); ?
Without above line code is not worked ...
A: This is an error below The promise do not require to handel -
[31mF[0mA Jasmine spec timed out. Resetting the WebDriver Control Flow.
Failures:
1) Protractor Alert steps Open Angular js website Alerts
Message:
[31m Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.[0m
Stack:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
Message:
[31m Failed: script timeout
A: You're getting a timeout error. Modify your timeout limits in your Configuration file.
exports.config = {
allScriptsTimeout: 90 * 1000, // Set to 90 seconds
getPageTimeout: 15 * 1000, // Set to 15 seconds
// if you're using Node, you might want to adjust this as well:
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 60 * 1000, // 60 second timeout
print: function() {}
},
};
Just a word of caution: long tests are fragile tests. Adjust your timeouts carefully.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61521178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Safe to use a nancy module property as 'per-request' storage? Aside from being a bad, bad pattern in general, are there any ramifications of doing something like this to store an object as a property on the nancy module for the life of the request? Everything looks okay but not sure if this will result in any weirdness at scale... ie, cross-talk between requests, memory leaks, general shenanigans.
public class APIModule : NancyModule
{
public SomeConvolutedThing MyThing { get; set; }
public APIModule()
{
Before += ctx => {
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies["MyThing"].Value);
MyThing = JsonConvert.DeserializeObject<SomeConvolutedThing>(ticket.UserData);
}
catch
{
MyThing = null;
}
return null;
};
Get["/api/callit"] = parameters => {
// check on status of MyThing before deciding what to return
};
}
}
A: You should be fine doing that, modules are constructed per request - there should be no need to use a before hook though, just stick that code in the start of your constructor as if you would when setting a property from a constructor parameter.
A: As @StevenRobbins said, you can, but the question is - why? For the snipped you provided, using local variable in the constructor is just enough.
I can envision few other reasons to want to have this:
*
*Your route(s) use a private methods to do their work. Then a private readonly field will work (for the same reasons, each module is constructed per request). Or even better, make these private functions to accept myThing as parameter, and still use local var in ctor.
*You want to access this outside of the module - it's better to create your own class to hold this outside the module. Register it "per request" and have a beforerequest hook to fill the data, and inject into whatever other functionality needs it.
To elaborate on (2):
public interface IMyThingBag
{
MyThing MyThing{get;set;}
}
public class MyBagFiller : IRequestStartup
{
private readonly IMyThingBag _bag;
public MyBagFiller(IMyThingBag bad)
{
_bad = bag;
}
public void Initialize(IPipelines pipelines, NancyContext context)
{
_bag.MyThing = new MyThing{.....};
}
}
Now, anywhere in the chain (need to have the parts registered per request), you can inject the bag and use the thing :)
You can even inject it in the module if you need the data there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29529022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bisecting K-Means in Pyspark/MLlib I have several doubts about the methods this algorithm uses for several purposes:
*
*How does it initialize the centroids every time it splits a cluster into two new ones?
*How many times does it apply the K-Means algorithm to divide each cluster into two new ones with different centroids?
*Which is the inner K-means algorithm used in bisection?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72259343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP - Extract content from atributte i have problem. I need extract content from atributte content:
<html>
<head>
<meta name="keywords" content="KEYWORDS">
<meta name="description" content="THIS TEXT">
</head>
I use this PHP code:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('meta');
foreach ($tags as $tag) {
echo $tag->getAttribute('content');
}
but the code find only first appearance of atributte content,
but i need the second apperance atributte content....
A: Please try this
$dom = new DOMDocument();
$dom->loadHTML($html);
$elements = $dom->getElementsByTagName('meta');
foreach ($elements as $child) {
echo $child->nodeValue;
}
A: Do something like this:
<?php
$nodes = $xml->getElementsByTagName ("meta");
$nodeListLength = $nodes->length;
for ($i = 0; $i < $nodeListLength; $i ++)
{
$node = $nodes->item($i)->getAttribute('content');
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16052860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't get HTML code through HttpWebRequest I am trying to parse the HTML code of the page at http://odds.bestbetting.com/horse-racing/today in order to have a list of races, etc.
The problem is I am not being able to retrieve the HTML code of the page. Here is the C# code of the function:
public static string Http(string url) {
Uri myUri = new Uri(url);
// Create a 'HttpWebRequest' object for the specified url.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
myHttpWebRequest.AllowAutoRedirect = true;
// Send the request and wait for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var stream = myHttpWebResponse.GetResponseStream();
var reader = new StreamReader(stream);
var html = reader.ReadToEnd();
// Release resources of response object.
myHttpWebResponse.Close();
return html;
}
When I execute the program calling the function it throws an exception on
HttpWebResponse myHttpWebResponse =
(HttpWebResponse)myHttpWebRequest.GetResponse();
which is:
Cannot handle redirect from HTTP/HTTPS protocols to other dissimilar ones.
I have read this question but I don't seem to have the same problem.
I've also tried iguring something out sniffing the traffic with fiddler but can't see anything to where it redirects or something similar. I just have extracted these two possible redirections: odds.bestbetting.com/horse-racing/2011-06-10/byCourse
and odds.bestbetting.com/horse-racing/2011-06-10/byTime , but querying them produces the same result as above.
It's not the first time I do something like this, but I'm really lost on this one. Any help?
Thanks!
A: I finally found the solution... it effectively was a problem with the headers, specifically the User-Agent one.
I found after lots of searching a guy having the same problem as me with the same site. Although his code was different the important bit was that he set the UserAgent attribute of the request manually to that of a browser. I think I had done this before but I may had done it pretty bad... sorry.
The final code if it is of interest to any one is this:
public static string Http(string url) {
if (url.Length > 0)
{
Uri myUri = new Uri(url);
// Create a 'HttpWebRequest' object for the specified url.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
// Set the user agent as if we were a web browser
myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var stream = myHttpWebResponse.GetResponseStream();
var reader = new StreamReader(stream);
var html = reader.ReadToEnd();
// Release resources of response object.
myHttpWebResponse.Close();
return html;
}
else { return "NO URL"; }
}
Thank you very much for helping.
A: There can be a dozen probable causes for your problem.
One of them is that the redirect from the server is pointing to an FTP site, or something like that.
It can also being that the server require some headers in the request that you're failing to provide.
Check what a browser would send to the site and try to replicate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6305292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: PDF::Create module installation failed using cpan linux command? When I tried to install cpan module, i get the following error, i have tried by googling it,am unable to find solution.
Catching error: "Can't locate object method \"Create\" via package \"install PDF\" (perhaps you forgot to load \"install PDF\"?) at /usr/share /perl5/CPAN.pm line 376, <STDIN> line 1.\cJ" at /usr/share/perl5/CPAN.pm line 392, <STDIN> line 1.
CPAN::shell() called at /usr/share/perl5/App/Cpan.pm line 295
App::Cpan::_process_options('App::Cpan') called at /usr/share/perl5/App/Cpan.pm line 364
App::Cpan::run('App::Cpan') called at /usr/bin/cpan line 11
A: Your error can be reproduced by doing the following:
$ cpan
...
cpan shell -- CPAN exploration and modules installation (v2.10)
Enter 'h' for help.
cpan[1]> "install PDF::Create"
Catching error: "Can't locate object method \"Create\" via package \"install PDF\" (perhaps you forgot to load \"install PDF\"?) ...
The problem is you putting quotes around the whole command, apparently.
Solution: Remove the quotes:
cpan[2]> install PDF::Create
... works fine here.
Also, you can just do cpan PDF::Create without entering the cpan shell.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32709853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Connect slack with simple web api token but not with Slack bot or slack app As a leisure project, I created a small project that updates slack status whenever an event is added/updated in Google Calendar (Just like the Google calendar app on Slack). Whatever I implemented till now works as expected but I did so by creating a new Slack app, which I don't want to do - In other words, I am trying to integrate Google Calendar with Slack, without any Slack bot or Slack app setup. At least this is what Zapier does - It asks for authentication to Google calendar & Slack, and integrates them without having a Slack bot or Slack app.
I referred to Slack API docs but couldnβt find any page helpful enough to work without a Slack bot or Slack app, and simply with a Web API token.
I think I found a page closer to what I need but this too requires a client ID and client secret which are possible if a new app is created.
A: It's no longer possible to generate an API token on its own for Slack. If it helps, you can just think of a Slack app as a simple container representing what you want to accomplish. Install the Slack app to get the token and then use the token for that purpose. You don't need to learn or implement OAuth or provide much more than a name to retrieve a token scoped to the activities you wish to accomplish.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75301341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A^k for matrix multiplication in R? Suppose A is some square matrix. How can I easily exponentiate this matrix in R?
I tried two ways already: Trial 1 with a for-loop hack and Trial 2 a bit more elegantly but it is still a far cry from Ak simplicity.
Trial 1
set.seed(10)
t(matrix(rnorm(16),ncol=4,nrow=4)) -> a
for(i in 1:2){a <- a %*% a}
Trial 2
a <- t(matrix(c(0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0),nrow=4))
i <- diag(4)
(function(n) {if (n<=1) a else (i+a) %*% Recall(n-1)})(10)
A: Indeed the expm's package does use exponentiation by squaring.
In pure r, this can be done rather efficiently like so,
"%^%" <- function(mat,power){
base = mat
out = diag(nrow(mat))
while(power > 1){
if(power %% 2 == 1){
out = out %*% base
}
base = base %*% base
power = power %/% 2
}
out %*% base
}
Timing this,
m0 <- diag(1, nrow=3,ncol=3)
system.time(replicate(10000, m0%^%4000))#expm's %^% function
user system elapsed
0.31 0.00 0.31
system.time(replicate(10000, m0%^%4000))# my %^% function
user system elapsed
0.28 0.00 0.28
So, as expected, they are the same speed because they use the same algorithm. It looks like the overhead of the looping r code does not make a significant difference.
So, if you don't want to use expm, and need that performance, then you can just use this, if you don't mind looking at imperative code.
A: A shorter solution with eigenvalue decomposition:
"%^%" <- function(S, power)
with(eigen(S), vectors %*% (values^power * t(vectors)))
A: If A is diagonizable, you could use eigenvalue decomposition:
matrix.power <- function(A, n) { # only works for diagonalizable matrices
e <- eigen(A)
M <- e$vectors # matrix for changing basis
d <- e$values # eigen values
return(M %*% diag(d^n) %*% solve(M))
}
When A is not diagonalizable, the matrix M (matrix of eigenvectors) is singular. Thus, using it with A = matrix(c(0,1,0,0),2,2) would give Error in solve.default(M) : system is computationally singular.
A: The expm package has an %^% operator:
library("sos")
findFn("{matrix power}")
install.packages("expm")
library("expm")
?matpow
set.seed(10);t(matrix(rnorm(16),ncol=4,nrow=4))->a
a%^%8
A: Although Reduce is more elegant, a for-loop solution is faster and seems to be as fast as expm::%^%
m1 <- matrix(1:9, 3)
m2 <- matrix(1:9, 3)
m3 <- matrix(1:9, 3)
system.time(replicate(1000, Reduce("%*%" , list(m1,m1,m1) ) ) )
# user system elapsed
# 0.026 0.000 0.037
mlist <- list(m1,m2,m3)
m0 <- diag(1, nrow=3,ncol=3)
system.time(replicate(1000, for (i in 1:3 ) {m0 <- m0 %*% m1 } ) )
# user system elapsed
# 0.013 0.000 0.014
library(expm) # and I think this may be imported with pkg:Matrix
system.time(replicate(1000, m0%^%3))
# user system elapsed
#0.011 0.000 0.017
On the other hand the matrix.power solution is much, much slower:
system.time(replicate(1000, matrix.power(m1, 4)) )
user system elapsed
0.677 0.013 1.037
@BenBolker is correct (yet again). The for-loop appears linear in time as the exponent rises whereas the expm::%^% function appears to be even better than log(exponent).
> m0 <- diag(1, nrow=3,ncol=3)
> system.time(replicate(1000, for (i in 1:400 ) {m0 <- m0 %*% m1 } ) )
user system elapsed
0.678 0.037 0.708
> system.time(replicate(1000, m0%^%400))
user system elapsed
0.006 0.000 0.006
A: Simple solution
`%^%` <- function(A, n) {
A1 <- A
for(i in seq_len(n-1)){
A <- A %*% A1
}
return(A)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9459421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Error with the java code pls I have this code on the internet and i can't run them pls tell me know
why???
public static void main( String[] args ) {
keyboard[Scanner] = new Scanner(System.in);
System.out.print( "Hello. What is your name? " );
name[String] = keyboard[Scanner].next();
System.out.print( "Hi, " + name[String] + "! How old are you? " );
age[int] = keyboard[Scanner].nextInt();
System.out.println("So you're " + age[int] + ", eh? That's not so old.");
System.out.print( "How much do you weigh, " + name[String] + "? " );
weight[double] = keyboard[Scanner].nextDouble();
System.out.println( weight[double] + "! Better keep that quiet!!" );
System.out.print("Finally, what's your income, " + name[String] + "? " );
income[double] = keyboard[Scanner].nextDouble();
System.out.print( "Hopefully that is " + income[double] + " per hour" );
System.out.println( " and not per year!" );
System.out.print( "Well, thanks for answering my rude questions, " );
System.out.println( name[String] + "." );
}
Help me please!! Thanks!!!
A: from the book you mentioned in the comments. . just after this code ... the statement in the book is :
Whew! Aren't you glad you don't ahve to do that every time you use a variable ??
what you need is below :
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.print( "Hello. What is your name? " );
String name = keyboard.next();
System.out.print( "Hi, " + name+ "! How old are you? " );
int age = keyboard.nextInt();
System.out.println("So you're " + age + ", eh? That's not so old.");
System.out.print( "How much do you weigh, " + name + "? " );
double weight = keyboard.nextDouble();
System.out.println( weight + "! Better keep that quiet!!" );
System.out.print("Finally, what's your income, " + name + "? " );
double income = keyboard.nextDouble();
System.out.print( "Hopefully that is " + income + " per hour" );
System.out.println( " and not per year!" );
System.out.print( "Well, thanks for answering my rude questions, " );
System.out.println( name + "." );
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42810033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Why is the JVM stack-based and the Dalvik VM register-based? I'm curious, why did Sun decide to make the JVM stack-based and Google decide to make the DalvikVM register-based?
I suppose the JVM can't really assume that a certain number of registers are available on the target platform, since it is supposed to be platform independent. Therefor it just postpones the register-allocation etc, to the JIT compiler. (Correct me if I'm wrong.)
So the Android guys thought, "hey, that's inefficient, let's go for a register based vm right away..."? But wait, there are multiple different android devices, what number of registers did the Dalvik target? Are the Dalvik opcodes hardcoded for a certain number of registers?
Do all current Android devices on the market have about the same number of registers? Or, is there a register re-allocation performed during dex-loading? How does all this fit together?
A: There are a few attributes of a stack-based VM that fit in well with Java's design goals:
*
*A stack-based design makes very few
assumptions about the target
hardware (registers, CPU features),
so it's easy to implement a VM on a
wide variety of hardware.
*Since the operands for instructions
are largely implicit, the object
code will tend to be smaller. This
is important if you're going to be
downloading the code over a slow
network link.
Going with a register-based scheme probably means that Dalvik's code generator doesn't have to work as hard to produce performant code. Running on an extremely register-rich or register-poor architecture would probably handicap Dalvik, but that's not the usual target - ARM is a very middle-of-the-road architecture.
I had also forgotten that the initial version of Dalvik didn't include a JIT at all. If you're going to interpret the instructions directly, then a register-based scheme is probably a winner for interpretation performance.
A: I can't find a reference, but I think Sun decided for the stack-based bytecode approach because it makes it easy to run the JVM on an architecture with few registers (e.g. IA32).
In Dalvik VM Internals from Google I/O 2008, the Dalvik creator Dan Bornstein gives the following arguments for choosing a register-based VM on slide 35 of the presentation slides:
Register Machine
Why?
*
*avoid instruction dispatch
*avoid unnecessary memory access
*consume instruction stream efficiently (higher semantic density per instruction)
and on slide 36:
Register Machine
The stats
*
*30% fewer instructions
*35% fewer code units
*35% more bytes in the instructions stream
*
*but we get to consume two at a time
According to Bornstein this is "a general expectation what you could find when you convert a set of class files to dex files".
The relevant part of the presentation video starts at 25:00.
There is also an insightful paper titled "Virtual Machine Showdown: Stack Versus Registers" by Shi et al. (2005), which explores the differences between stack- and register-based virtual machines.
A: I don't know why Sun decided to make JVM stack based. Erlangs virtual machine, BEAM is register based for performance reasons. And Dalvik also seem to be register based because of performance reasons.
From Pro Android 2:
Dalvik uses registers as primarily units of data storage instead of the stack. Google is hoping to accomplish 30 percent fewer instructions as a result.
And regarding the code size:
The Dalvik VM takes the generated Java class files and combines them into one or more Dalvik Executables (.dex) files. It reuses duplicate information from multiple class files, effectively reducing the space requirement (uncompressed) by half from traditional .jar file. For example, the .dex file of the web browser app in Android is about 200k, whereas the equivalent uncompressed .jar version is about 500k. The .dex file of the alarm clock is about 50k, and roughly twice that size in its .jar version.
And as I remember Computer Architecture: A Quantitative Approach also conclude that a register machine perform better than a stack based machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2719469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "107"
}
|
Q: Deduce parameter pack w/out passing it explicitly as a template parameter? Forgive any ignorance of C++ type deduction in this, but I'd like to be able to carry around the parameter pack's definition, so that later I could test for an inner type. Is this possible? Something like:
template <typename... Args> struct Entity {
struct Inner {
typedef Args... entity_args_t;
};
struct SomeOtherInner {
typedef Args... entity_args_t;
};
};
struct ThingA : Entity<int, string> {
};
struct ThingB : Entity<string, string> {
};
//Want to accept variations of Entity<...>::Inner,
//not Entity<...>::SomeOtherInner
template<typename I>
struct is_Entity_Inner {
static const bool value
= is_same<
typename Entity<typename I::entity_args_t...>::Inner
, I
>::value
;
};
Oui? Non?
A: Define:
template<typename ...> struct types;
Then:
template <typename... Args> struct Entity {
struct Inner {
typedef types<Args...> entity_args_t;
};
struct SomeOtherInner {
typedef types<Args...> entity_args_t;
};
};
Then you can pass entity_args_t to a template that has a partial specialization for types<T...>. If you typedef the Entity, you can instead write a partial specialization for Entity<T...>, which may make more sense for your case
template <typename... Args> struct Entity {
struct Inner {
// Equivalent: typedef Entity entity_args_t;
typedef Entity<Args...> entity_args_t;
};
struct SomeOtherInner {
typedef Entity<Args...> entity_args_t;
};
};
So having a typedef for entity_args_t equal Entity<Args...>, you could write this as follows (untested, but should work):
template<typename ProbablyInner, typename ProbablyEntity>
struct is_inner_impl : std::false_type
{ };
template<typename ProbablyInner, typename ...Args>
struct is_inner_impl<ProbablyInner, Entity<Args...>>
: std::is_same<
typename Entity<Args...>::Inner
ProbablyInner>
{ };
template<typename ProbablyInner, typename = std::true_type>
struct is_inner : std::false_type
{ };
template<typename ProbablyInner>
struct is_inner<ProbablyInner,
std::integral_constant<bool, is_inner_impl<
ProbablyInner,
typename ProbablyInner::entity_args_t>::value>>
: std::true_type
{ };
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6033601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to exit knitr on error but still generate the partial output I generate a standardized report using knitr. To document errors easier (the input data is not always what is expected), I need a log file amended with plus nice HTML formatting and figure embedding. A log file lists results until an error occurs, then ends.
The default of knitr, however, is to print the error message into the output and then continue with the next chunks. Alternatively, using knitr::opts_chunk$set(error = FALSE), one can abort the whole process when an error occurs, creating no markdown output at all.
But I want knitr to print until reaching an error, then stop.
I can stop early and generate a HTML output using knitr::knit_exit(), but I cannot use it as an error handler. See the two examples below. The first does as expected, but the second one is supposed to output the error message "Test" as the last chunk. How can I achieve this?
MWE 1: knit_exit()
knitr::knit(output = stdout(), text = "
```{r}
1 + 1
```
```{r}
knitr::knit_exit()
```
```{r}
2 + 2
```
")
## ```r
## 1 + 1
## ```
##
## ```
## ## [1] 2
## ```
##
##
## ```r
## knitr::knit_exit()
## ```
MWE 2: No error handling
options(error = knitr::knit_exit); knitr::knit(output = stdout(), text = "
```{r}
1 + 1
```
```{r}
stop('Test')
```
This text should not be in the output.
```{r}
2 + 2
```
")
## ```r
## 1 + 1
## ```
##
## ```
## ## [1] 2
## ```
##
##
## ```r
## stop('Test')
## ```
##
## ```
## Error in eval(expr, envir, enclos): Test
## ```
##
## This text should not be in the output.
##
##
## ```r
## 2 + 2
## ```
##
```
## [1] 4
```
A: That's correct, it does not work to directly use knitr::knit_exit() as an error handler. However, you can override the error output hook with it to achieve your desired outcome:
knitr::knit(
output = stdout(),
text = "
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, error = TRUE)
# override error output hook here
knitr::knit_hooks$set(error = function(x, options) {
knitr::knit_exit()
})
```
```{r}
1 + 1
```
```{r}
stop('Test')
```
This text should not be in the output.
```{r}
2 + 2
```
")
```
#>
#>
#>
#>
#> ```r
#> 1 + 1
#> #> [1] 2
#> ```
#>
#>
#> ```r
#> stop('Test')
#> ```
Created on 2022-10-24 with reprex v2.0.2
A: In addition to the accepted answer (which helped me a lot and you should upvote ;-) ) one might want the error message to be printed. In that case, the error hook can be used to signal knitr to quit but also save the error message, for example in a global variable. Then, the chunk hook can be used to print the error message in a last output block:
For that, use the following hooks
knitr::knit_hooks$set(error = function(x, options) {
ERROR <<- x
knitr::knit_exit()
})
knitr::knit_hooks$set(chunk = function(x, options){
if(exists('ERROR')) paste0(x,'```\n',ERROR,'```\n\n**Skript stopped with error**')
else x
})
Or, in the complete example:
knitr::knit(
output = stdout(),
text = "
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, error = TRUE)
# override error output hook here
knitr::knit_hooks$set(error = function(x, options) {
ERROR <<- x
knitr::knit_exit()
})
knitr::knit_hooks$set(chunk = function(x, options){
if(exists('ERROR')) paste0(x,'```\n',ERROR,'```\n\n**Skript stopped with error**')
else x
})
```
```{r}
1 + 1
```
```{r}
stop('Test')
```
This text should not be in the output.
```{r}
2 + 2
```
")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74097101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Diff between Dotfuscator (PreEmptive solutions) & Application Insights I am trying to find a way to track the usage of some desktop applications and came across PreEmptive solutions and application insights and I still can't see clearly the difference in their perimeter, maybe I have the wrong impression but I feel like app. insights is "included" in what PreEmptive solutions offers, can I someone help me see the difference ?
Thks
A: As with many usage analytics solutions, there is a large body of features/capabilities that are common (at least from 10K feet), and have many smaller differences when examined closely.
However, there are few fundamental differences in approaches between App Insights and Preemptive:
*
*AI is SaaS offering, Preemptive is a "box" product (I believe they are also offer cloud-hosted version). This also assumes different pricing models
*Main instrumentation model for Preemptive is through code injection (potentially as part of obfuscation process). AI offers a sophisticated SDK and tight integration into Visual Studio IDE. Preemptive also has an SDK
*AI offers Usage Analytics as part of the broader Application Performance and Analytics offering. AI is capable of capturing a wider range of telemetry information, including traces, exceptions (Preemptive does it too), metrics, dependencies, etc. and also enables both metric and log analyst. Preemptive is more focused
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33282551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pthread_join constantly causes segfault This issue is definitely the source of a stupid mistake, but for the life of me I cannot get to the bottom of it.
I'm writing a much larger program, but I've narrowed down a constant segfault error that is coming up whenever I call pthread_join. I've included the relevant code below, hopefully someone can help me figure out what I'm doing wrong. Cheers :)
Functions for managing pthreads
void *scalloc(size_t nmemb, size_t size)
{
void *p;
p = calloc(nmemb, size);
if (p == NULL)
sys_error("Error allocating memory block (calloc).", 1);
return p;
}
pthread_t *new_thread_array(int n)
{
return scalloc(n, sizeof(pthread_t));
}
int spthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg)
{
int ret;
if ((ret = pthread_create(&thread, attr, start_routine, arg)) != 0)
sys_error("Error at pthread_create.", ret);
return 0;
}
int spthread_join(pthread_t thread, void **retval)
{
int ret;
if ((ret = pthread_join(thread, retval)) != 0)
sys_error("Error at pthread_join.", ret);
return 0;
}
int create_threads(pthread_t *thread_arr, int n, const pthread_attr_t *attr,
void *(*start_routine) (void *), void **arg_arr)
{
for (int i = 0; i < n; i++) {
spthread_create(&thread_arr[i], attr, start_routine, arg_arr[i]);
debug("created thread %d", i);
}
return 0;
}
int join_threads(pthread_t *thread_arr, int n, void **ret_arr)
{
debug("Starting join");
for (int i = 0; i < n; i++) {
if (ret_arr != NULL)
spthread_join(thread_arr[i], ret_arr[i]);
else {
debug("Attempting to join %d", i);
spthread_join(thread_arr[i], NULL);
debug("Joined %d", i);
}
}
return 0;
}
Test code that produces the error
void *threadfunc(void *id)
{
fflush(stdout);
fprintf(stdout, "Thread %d printing.\n", *(int *)id);
fflush(stdout);
return;
}
int threadtest(int nodes)
{
int ret;
int *targs = scalloc(nodes, sizeof(int));
int *pass[nodes];
for (int i = 0; i < nodes; i++) {
targs[i] = i;
pass[i] = &targs[i];
}
printf("Starting L1 thread test...\n");
pthread_t *threads = new_thread_array(nodes);
debug("Allocated pthread array for %i threads.", nodes);
create_threads(threads, nodes, NULL, &threadfunc, pass);
join_threads(threads, nodes, NULL);
debug("Successfully joined %i threads.", nodes);
free(targs);
free(threads);
return 0;
}
int main()
{
return threadtest(5);
}
Finally, here is the output of running the function threadtest, confirming that the segfault (appears) to occur in the parent thread, at the call to pthread_join.
Starting L1 thread test...
Allocated pthread array for 5 threads.
created thread 0
created thread 1
Thread 0 printing.
created thread 2
Thread 1 printing.
Thread 2 printing.
created thread 3
Thread 3 printing.
created thread 4
Thread 4 printing.
Starting join
Attempting to join 0
zsh: segmentation fault ./tests/L1tests
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67130014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: show image from folder to page using asp.net c# I am trying to make image gallery for my website .
in my case i am showing thumbnail of all images and if we clicks
on the image it shows image in modal window .
there are 2 folders
*
*Thumbs (consist thumbnail)
*Full image (consist full image)
i have put the image with the same name ,as well i can do it by giving path of my images hard coded like this code
<ul id="gallery">
<li><a href="http://ppplugins.com/demo/ppgallery/images/l_01.jpg" title="Title will be here"><img class="GalleryThumbnail" src="http://ppplugins.com/demo/ppgallery/images/s_01.jpg"></a></li>
</ul>
But dont know how can we do it without giving value hard coded .
please help me .
like if i add more iages in that folders it must show the image on page .
checkout here
1>http://182.50.154.23/elweb//CheckImagesFromFolder.aspx(trying to make it as 2nd link given below but not using source hard coded)
2>http://182.50.154.23/elweb//Gallery.aspx (required output)
A: var thumbs = Directory.GetFiles("your thumbs directory");
var images = Directory.GetFiles("your images directory");
foreach (var image in images)
{
var thumbname = thumbs.Where(x => x.Substring(2) == image.Substring(2));
}
I'm not sure if it's what you want, but if the files are in two seperate folders it will take their paths.
You can also match thumb with image comparing their names.
A: Use Database to store image name and Path. use reapeter control to show image list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17361033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Refactor tree nodes with vectors v_i and multiplications v_i * B into one matrix multiplication A * B I have a Tree with a complex data-model in each node. Each leaf of the tree has its own vector of doubles leaf.v. There is a universal matrix B. In my algorithm in each leaf, I calculate a new vector leaf.u = leaf.v * B. I found that this computation is currently the performance bottleneck of my algorithm. The complexity is say, O(n^2) for one leaf and O(n^3) for all leafs combined.
The attentive reader will notice that I can combine the vectors leaf.v of all leafs into one matrix A and then use a matrix multiplication library to compute U = A*B, which can be computed more efficiently than O(n^3) (Wikipedia). From the matrix U I can then extract the vectors leaf.u for all the leafs.
This requires some bookkeeping, as the matrix A needs to be created and it needs to be tracked which row of U will be the leaf.u of which leaf and those need to be copied back. How can I do this bookkeeping while still keeping the code readable?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65494881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pyst2 - How to reconnect Asterisk manager? I'm using pyst2 to connect to the AMI (Asterisk manager interface). I have a event for shutdown, so it can close it and try to reconnect every minute.
My shutdown event:
def handle_shutdown(event, manager, hass, entry):
_LOGGER.error("Asterisk shutting down.")
manager.close()
host = entry.data[CONF_HOST]
port = entry.data[CONF_PORT]
username = entry.data[CONF_USERNAME]
password = entry.data[CONF_PASSWORD]
while True:
sleep(30)
try:
manager.connect(host, port)
manager.login(username, password)
_LOGGER.info("Succesfully reconnected.")
break
except asterisk.manager.ManagerException as exception:
_LOGGER.error("Error reconnecting to Asterisk: %s", exception.args[1])
It works fine, until Asterisk started up again and it can connect. Instead of connecting I get this error: RuntimeError: threads can only be started once.
Does anybody knows how to do this correctly?
Here is my entire code.
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71629151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: White flash on transition between HTML pages I'm trying to implement some JavaScript code I found here on stackoverflow to make a smooth transition between one link on a page and other section in other page using the standar:
<a href="example.html#anchor">
The issues is that when the user clik the link, 1 second white flash appears before the smooth scroolling makes. I dont like this behavior for the "User Experience"
How can I to prevent this?
The JavaScript:
(function($){
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top
},1000, function()
{
location.hash = target;
});
}
$('html, body').hide()
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show()
jump()
}, 0);
}else{
$('html, body').show()
}
});
})(jQuery)
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18790007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the point of javascript templating engines? I know the answers people typically give, but I need a concrete example as to why they are needed.
The latest impression I'm getting (mostly from underscore.js) is that it makes the code more PHP like in that you can have <% %> like ?> in PHP
The idea is to make your code less like spaghetti and have a clear difference between presentation and logic. That's what everyone says, but I'm not sure why this warrants the need for a templating engine.
Why can't you just do this in pure javascript? All you need is a function that takes in data as arguments and you can do keep javascript syntax without inventing a new language, which seems ridiculous. For example you can just do:
populateTable(obj) {
$('#model').html('
<h2>' + obj.title + '</h2>' +
<ul> ... </ul>
}
This seems fine to me. It's a function dedicated to rendering a table using some model data that you pass into it. Why do we need to invent new syntax?
A: One reason for me is that I prefer writing this:
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
Over writing this:
var createEntryTemplate = function(obj) {
return '<div class="entry">' +
'<h1>' + obj.title + '</h1>' +
'<div class="body">' + obj.body +
'</div>' +
'</div>';
};
The latter method is also more error prone - if not for you then maybe for another person. Imagine you're working with a designer who doesn't have a lot of programming experience and he needs to go in and replace a significant chunk of HTML.
Oh crap...
A: Basically, using a client-sided templating engine, trades server-sided rendering against client-sided execution, so these come to mind
*
*Pro: You might easily save significant bandwidth, as the raw data most often is much smaller than the HTML rendering
*Pro: You might easily save significant server CPU cycles by doing rendering work on the client
*Pro: The client might have more or easier accessible knowledge about the rendering restrictions (e.g. screen size)
*Con: You move the rendering from a well known and stable environment to a moving target outside your control
*Con: A non-interactive client (e.g. a search engine) will not see your final rendering, making SEO, indexing etc. hard
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21842781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A POI related code block running dead slow I have below piece of code block containing loops:
Row row = null;
Cell cell = null;
String dataVal = null;
String[] temp = null;
for (int j = 0; j < this.myDataValues.size(); j++) {
row = sheet.createRow(rownum++);
temp = this.finalRowValues.get(j);
for (int i = 0; i < 4; i++) {
cell = row.createCell(i);
dataVal = temp[i];
if (NumberUtils.isNumber(dataVal)) {
double d = Double.valueOf(dataVal);
cell.setCellValue(d);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(styles.get("currency"));
} else if (isValidDate(dataVal)) {
cell.setCellValue(dataVal);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(styles.get("date"));
} else {
cell.setCellValue(temp[i]);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(styles.get("data"));
}
sheet.autoSizeColumn(i);
}
}
Where myDataValues is a List of String[] with each String[] object containing 4 values.
I am running this in Rational Application Developer version 8 and Apache POI 3.8.
There are around 5500 elements in myDataValues which is a pretty small value I believe.
However, this code block is taking more then a hour to run.
I think there is something wrong with this. 5500 elements with each containing 4 elements should run pretty fast and should be a question of several minutes. What could be the possible cause? Is there a way to make this block run faster?
There is nothing wrong with available memory of the machine or any other such issues. Everything is working as expected and I have verified it. The issue is in this block only.
A: Your processing is very slow because you're calling autoSizeColumn for every row. From the Javadocs for the autoSizeColumn method:
This process can be relatively slow on large sheets, so this should
normally only be called once per column, at the end of your
processing.
Place the calls to autoSizeColumn outside of the loop that creates the rows, in its own for loop only on the columns. This will minimize calls to this method and improve your performance.
A: Just for reference...
In my case, I had 1 millions plus, and the AutoSizeColumn still slow (even in the end).
So, I considerely boost the performance, just storing the column index and content length of every values (in a Dictionary), when it is large than last stored.
In the end of all process, just "foreach" the list and set the width of the column with sheet.SetColumnWidth.
*
*With autosize: never end;
*With witdh: 3 seconds.
Pseudo-code
if(!dictionary.Any(a => a.Key == columnIndex))
{
dictionary.Add(columnIndex, columnContent.Length);
}
else if(dictionary.Any(a => a.Key == columnIndex && a.Value < columnContent.Length))
{
dictionary[columnIndex] = columnContent.Length;
}
And in the end
foreach (KeyValuePair<int, int> column in dictionary)
{
sheet.SetColumnWidth(column.Key, column.Value*300);
}
A: try this...
for (int j = 0; j < this.myDataValues.size(); j++) {
row = sheet.createRow(rownum++);
temp = this.finalRowValues.get(j);
for (int i = 0; i < 4; i++) {
cell = row.createCell(i);
dataVal = temp[i];
if (NumberUtils.isNumber(dataVal)) {
double d = Double.valueOf(dataVal);
cell.setCellValue(d);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(styles.get("currency"));
} else if (isValidDate(dataVal)) {
cell.setCellValue(dataVal);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(styles.get("date"));
} else {
cell.setCellValue(temp[i]);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(styles.get("data"));
}
}
}
for (int i = 0; i < 4; i++) {
sheet.autoSizeColumn(i);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18984785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Vue duplicate numbers in array breaks doom element Very weird situation, when I push any number which already exists in my array it duplicates and breaks my doom element. Array keeps normal, but doom displays something like this:
array:
my watcher :
lastWins(){
console.log(this.lastWins);
this.lastWins.shift();
}
Doom:
<ul class="gameHistoryList_rou">
<li :style="{background: historyCheckColor(win)}" v-for="win of lastWins" :key="win">{{ win }}</li>
</ul>
method to push(splice for watch):
this.lastWins.push(Math.round(Math.random() * 36));
this.lastWins = this.lastWins.splice(0);
A: You need to set an unique key for each item.
Try this:
<ul class="gameHistoryList_rou">
<li :style="{background: historyCheckColor(win)}" v-for="(win, index) of lastWins" :key="index">{{ win }}</li>
</ul>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74041406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to stream Azure Information Protection Activity Logs to an Event Hub? I have configured Azure Information Protection analytics through the Azure portal for my subscription and I am able to see log data under the Activity logs (preview) tab.
I want to forward that log data to a configured Event Hub but I have not found a way to do it. This data appears to be written to a table called InformationProtection_CL. How do I get that query output to stream to an Event Hub? Is what I'm trying to do possible?
A: You can use the REST API Query - Get to get the log data in the table.
GET https://api.loganalytics.io/v1/workspaces/{workspaceId}/query?query={query}
Then follow this doc to send events to the event hub programmatically, the specific situation and language depend on you.
https://learn.microsoft.com/en-us/azure/event-hubs/event-hubs-dotnet-standard-getstarted-send#send-events
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58612725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Validating token The query regards the method for validating an access token to the application's API.
From the rails api link, when searching for token, the documentation has evolved for the private method to authenticate
While
Apikey.exists?(access_token: token)
is obvious, the newer version is rather opaque to me
ActiveSupport::SecurityUtils.secure_compare(
::Digest::SHA256.hexdigest(token),
::Digest::SHA256.hexdigest(TOKEN)
)
What is the allCAPS version of the token representing? A stored and encrypted value of the token for that connecting entity, say User? This implies that the query URL needs to have a parameter to identify the User. Is that wise to pass it via a parameter, even if done under SSL ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49024528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Response code 401 while sending notification to Edge I am creating a web app that sends notifications to my subscribers. While testing with different browsers, I noticed only the Edge browser got an authorized error and has a different endpoint than the rest of the browsers (Chrome, Opera) sg2p.notify.windows.com
I am using Nuget WebPush for send notifications and Conveyor by Keyoti for testing on LAN
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65862439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PayPal Error - Please make sure all fields have been entered I have a problem in creating a working PayPal button in Sandbox environment.
After entering my email and password in the sandbox environment.
This is what I see.
Here are my codes
AndroidManifest.xml
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MypaypalActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.paypal.android.MEP.PayPalActivity"
android:configChanges="keyboardHidden|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</manifest>
MypaypalActivity
public class MypaypalActivity extends Activity implements OnClickListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout MainLayout= new LinearLayout(this);
setContentView(R.layout.main);
PayPal pp = PayPal.initWithAppID(this, "APP-80W284485P519543T", PayPal.ENV_SANDBOX);
LinearLayout layoutSimplePayment = new LinearLayout(this);
layoutSimplePayment.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layoutSimplePayment.setOrientation(LinearLayout.VERTICAL);
CheckoutButton COButton = pp.getCheckoutButton(this, PayPal.BUTTON_118x24, CheckoutButton.TEXT_PAY);
COButton.setOnClickListener(this);
layoutSimplePayment.addView(COButton);
MainLayout.addView(layoutSimplePayment);
setContentView(MainLayout);
}
public void onClick(View v) {
PayPalPayment payment = new PayPalPayment();
payment.setSubtotal(new BigDecimal("10"));
payment.setCurrencyType("USD");
payment.setRecipient("becozofeuu_92@hotmail.com");
// payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
startActivityForResult(checkoutIntent, 1);
}
A: I faced same problem, finally I solve it using this code to
pass integer value to Bigdecimal
payment.setSubtotal(new BigDecimal("10"));
instead of using:
payment.setSubtotal(new BigDecimal(10));
e.g.:
public void onClick(View v) {
PayPalPayment payment = new PayPalPayment();
payment.setSubtotal(new BigDecimal("10"));
payment.setCurrencyType("USD");
payment.setRecipient("becozofeuu_92@hotmail.com");
// payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
startActivityForResult(checkoutIntent, 1);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9963617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sorting from multiple loops I have 7 different loops grabbing information from different places in the same format but as they're coming from different areas the data is muddled up.
for event in soup.find('dual').find_all('event'):
print event
for event in soup.find('int').find_all('event'):
print event
I want to sort all the information returned from these loops by a specific column number (i.e column seven places along). They are currently in CSV format and I have tried writing them to a CSV file and sorting them from that. Is there a way of sorting from these different loops without having to write to any files.
A: master_list = []
for event in soup.find('dual').find_all('event'):
master_list.append(event)
for event in soup.find('int').find_all('event'):
master_list.append(event)
for event in soup.find('whatever').find_all('event'):
master_list.append(event)
print sorted(event)
You may have to write your own comparison function so that sorted knows how to sort the list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38174105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Debugging PDF for error I'm creating PDF files using PDFClown java library.
Sometimes, when openning these files with Adobe Acrobat Reader I get the famous error message:
"An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem."
The error shows while reading (with Adobe) the attached file only when scrolling down to the 8'th page, then scrolling back up to 3'td page. Alternatively, Zooming out to 33.3% will also produce the message.
Just for the record, Foxit reader reads the file flawlessly, as well as other PDF readers like browsers.
My questions are:
*
*What's wrong with my file?? (file is attached)
*How can I find what's wrong with it? is there a tool which tells you where does the error lie?
Thanks!
A: Ok, this wasn't easy -
Due to a bug in PDFClown the my main stream of information in the PDF page has been corrupted.
After it's end it had a copy of a past instance of it.
This caused a partial text section without the starting command "BT" - which left a single "ET" without a "BT" in the end of the stream.
once I corrected this, it ran great.
Thank you all for your help.
I would have much more difficult time debugging it without the tool RUPS which @Bruno suggested.
edit:
The bug was in the Buffer.java:clone() (line 217)
instead of line:
clone.append(data);
needs to be:
clone.append(data, 0, this.length);
Without this correction it clones the whole data buffer, and set the cloned Buffer's length to the data[].length. This is very problematic if the Buffer.length is smaller than the data[].length.
The result in my case was that in the end of the stream there was garbage.
A:
The error shows while reading (with Adobe) the attached file only when scrolling down to the 8'th page, then scrolling back up to 3'td page. Alternatively, Zooming out to 33.3% will also produce the message.
Well, I get it easier, I merely open the PDF and scroll down using the cursor keys. As soon as the top 2 cm of page 3 appear, the message appears.
What's wrong with my file??
The content of pages 1 and 2 look ok, so let's look at the content of page 3.
My initial attributing the issue to the use of text specific operations (especially Tf and Tw) outside of a text object was wrong as Stefano Chizzolini pointed out: Some text related operations indeed are allowed outside text objects, namely the text state operations, cf. figure 9 from the PDF specification:
So while being less common, text state operations at page description level are completely ok.
After my incorrect attempt to explain the issue, the OP's own answer indicated that the
main stream of information in the PDF page has been corrupted. After it's end it had a copy of a past instance of it. This caused a partial text section without the starting command "BT" - which left a single "ET" without a "BT" in the end of the stream.
An ET without a prior BT indeed would be an error, and quite likely it would be accompanied by operations at the wrong level... Inspecting the stream content of that third page (the focused page of this issue), though, I could not find any unmatched ET. In the course of that inspection, though, I discovered that the content stream contains more than 2000 trailing 0 bytes! Adobe Reader seems not to be able to cope with these 0 bytes.
The bug the OP found, can explain the issue:
in the Buffer.java:clone() (line 217)
instead of line:
clone.append(data);
needs to be:
clone.append(data, 0, this.length);
Without this correction it clones the whole data buffer, and set the cloned Buffer's length to the data[].length. This is very problematic if the Buffer.length`` is smaller than the data[].length.
Trailing 0 bytes can be an effect of such a buffer copying bug.
Furthermore symptoms as found by the OP (After it's end it had a copy of a past instance of it) can also be the effect of such a bug. So I assume the OP found those symptoms on a different page, not page 3, but fixing the bug healed all symptoms.
How can I find what's wrong with it? is there a tool which tells you where does the error lie?
There are PDF syntax checkers, e.g. the Preflight tool included in Adobe Acrobat. but even that fails on your file.
So essentially you have to extract the page content (using a PDF browser, e.g. RUPS) and check manually with the PDF specification on the other screen.
A: the general post about debugging pdf might have been also helpful as rups / pdfstreamdump etc is mentioned there How do you debug PDF files?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18812789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How Can I create an image with python PIL where there are two colors? Here is an example of the output I want to generate. I'm able to create an image with one color, but I don't have idea of how can use two colors, and how to color only certain parts of the image .
A: I solved in this way. I created two image with two different colors, and then paste them in another one image.
width = 400
height = 300
img = Image.new( mode = "RGB", size = (width, height), color = (209, 123, 193) )
#First IMG
img2 = Image.new( mode = "RGB", size = (width, height + 400), color = (255, 255, 255) )
#Second IMG
img3 = Image.new('RGB', (img.width, img.height + img2.height)) img3.paste(img, (0, 0)) img3.paste(img2, (img.width, 0))
#IMG + IMG2
I got my result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69735709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: MVC 3 DropDownList displays multiple values on Edit page I'm using an enum to populate my DropDownList that works fine with a List and Create views but my Edit view loads duplicate values in the DropDownList. The duplicate values are only the selected value for the property meaning, if Rented was the value saved in the DB the DropDownList would show Rented selected, Available, and another Rented in the list. What I need to know is how to load a DropDownList that selects the value previously stored in the DB for the PropertyStatus enum without any duplicates?
Controler:
public ActionResult Edit(int id)
{
Property property = db.Properties.Find(id);
ViewBag.PropertyStatus = SetViewBagPropertyStatus();
return View(property);
}
private IEnumerable<SelectListItem> SetViewBagPropertyStatus()
{
IEnumerable<ePropStatus> values =
Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>();
IEnumerable<SelectListItem> items =
from value in values
select new SelectListItem
{
Text = value.ToString(),
Value = value.ToString()
};
return items;
}
Model:
public enum ePropStatus
{
Available ,
Rented
}
public partial class Property
{
public int PropertyId { get; set; }
public string PropName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public int SqFeet { get; set; }
public int Bedrooms { get; set; }
public int Bathrooms { get; set; }
public int Garage { get; set; }
public string Notes { get; set; }
public ePropStatus PropertyStatus { get; set; }
}
Edit View:
@Html.DropDownList("PropertyStatus", Model.PropertyStatus.ToString())
A: Try this instead :
@Html.DropDownListFor(model => model.PropertyStatus, ViewBag.PropertyStatus)
Edit ::: Alternately try this
Controler:
public ActionResult Edit(int id)
{
Property property = db.Properties.Find(id);
ViewBag.PropertyStatusList = SetViewBagPropertyStatus(property.PropertyStatus);
return View(property);
}
private IEnumerable<SelectListItem> SetViewBagPropertyStatus(string selectedValue = "")
{
IEnumerable<ePropStatus> values =
Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>();
IEnumerable<SelectListItem> items =
from value in values
select new SelectListItem
{
Text = value.ToString(),
Value = value.ToString(),
Selected = (selectedValue == value.ToString())
};
return items;
}
View:
@Html.DropDownList("PropertyStatus", ViewBag.PropertyStatusList)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13329036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: find out windows in side-by-side mode The "View Side By Side" and "Synchronous Scrolling" made the comparison of 2 spreadsheets easier than ever. However, there isn't a "Synchronous Switching tab" feature, so if I switch to a different tab in one of the workbooks and continue scrolling, the sync'ed scrolling become quite funny.
Well, I shouldn't complain, because it's all done manually, and I should use this feature wisely.
As a lazy developer, I would like to write some code to dig myself out: Can I write a macro to automate the worksheet switching on the peer window in side-by-side mode?
It breaks down to 2 steps:
*
*how do I know if a window, most likely the ActiveWindow, is in side-by-side mode?
*if it is, how do I tell which window is its peer?
I did my homework. It seems Excel is not very programming friendly on this feature. There are 3 methods
*
*BreakSideBySide()
*CompareSideBySideWith(WindowName)
*ResetPositionsSideBySide()
and 1 Boolean property
*
*SyncScrollingSideBySide
on the Windows collection related to this feature, but are insufficient to solve my questions.
Does anyone have any idea how to achieve this? Or, is it indeed impossible? Thank you in advance.
A: You can achieve this using the Workbook_SheetActivate event:
http://msdn.microsoft.com/en-us/library/office/ff195710.aspx
if you put this code in your ThisWorkbook Object, then each time you change the active worksheet, it will...
*
*Cycle through all open workbooks with a different name
*Look for a worksheet with the same name as the sheet you just clicked on
*Activate the worksheet in the other Workbook
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
For i = 1 To Application.Workbooks.Count
If Application.Workbooks(i).Name <> ThisWorkbook.Name Then
Dim otherWB As Workbook
Set otherWB = Application.Workbooks(i)
otherWB.Sheets(Sh.Name).Activate
End If
Next
End Sub
Note that this requires the worksheet to exist in all open workbooks. An error will result if it does not. However, you could easily add error handling to ignore workbooks with unfound corresponding worksheets.
Also note that it's probably best to use this when only two workbooks are open. I have not looked into the other methods you mentioned, but there may exist a way to identify the two workbooks that are currently in side-by-side mode, at which point the code could shed its for loop and become more concise.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18644975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Android Datepicker Single Cell Color Hi I'd like to be able to choose a few dates in the month and change the color of it. Say in my application I want the dates 3, 4, 8 of September to be red so that the user would be able to know that at those specific dates there is already a submission. Is this possible, if so how? Thanks in advance!
edit. Ive tried searching the forums, searching other places, and have not been able to get an answer.
To make things clear, Im not just looking to change the color theme, Im looking to change the color of specific dates. Say the user has submitted something for the 8th of September. I want my application date picker to show that by changing the color of the number 8 in the datepicker window.
A: check the library to show date with the different colour themes:
Add to your styles.xml
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
<item name="android:colorAccent">@color/beautiful_color</item>
</style>
<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">@color/beautiful_color</item>
<item name="android:datePickerMode">calendar</item>
</style>
Moreover, if you want to change the entire theme of the date picker, use the following dependency
dependencies {
compile 'com.wdullaer:materialdatetimepicker:3.6.3'
}
You can use app:mcv_dateTextAppearance (or the Java setter) to do this. I don't have the full explanation, but for now, you can copy the default implementation and modify as you need. Essentially you need to supply a android:textColor that is a color state list with your desired colors.
Add a style:
<style name="TextAppearance.MyCustomDay" parent="android:TextAppearance.DeviceDefault.Small">
<item name="android:textSize">12sp</item>
<item name="android:textColor">@color/my_custom_day_color</item>
</style>
and create color/my_custom_day_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:enterFadeDuration="@android:integer/config_shortAnimTime"
android:exitFadeDuration="@android:integer/config_shortAnimTime">
<item android:state_checked="true" android:color="SELECTION_COLOR" />
<item android:state_pressed="true" android:color="SELECTION_COLOR" />
<item android:state_enabled="false" android:color="#808080" />
<item android:color="@android:color/black" />
</selector>
then set app:mcv_dateTextAppearance="@style/TextAppearance.MyCustomDay"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52268656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Can I change JVM parameters during execution I am writing a Java program and at some point during execution I want to change the JVM settings (decrease the heap) and after a while increase it again. Is it possible with Java?
A: Long story short: you can't. Heap size is fixed once you are running it, and there's no way to modify it from the code.
A: I do not think this is possible, but you could of course control the heap with -Xmx or -Xms.
You can also play with : -XX:MaxHeapFreeRatio : this is the maximum percentage (70 by default if I am no mistaken) of the heap that is free before GC will shrink it.
Giving a small -Xms will make the heap grow (if needed and will involve a full GC) and shrink back is possible also.
Generally people try to avoid as much as possible this shrinking and growing because it involves a gull GC aka stop-the-world events that will slow you down.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22402424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Why does node.js don't find the function if the files requires each other Here is my situation:
*
*file a.js require file b.js
*file b.js require file a.js
When I try to call a function which is in file b.js from file a.js then I get the exception that b.xy() is not a function.
If I remove the require in file b.js then node.js can find the function.
Why does node.js don't find the function if the files requires
each other?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56219637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get relative path for logging.ini and log file in python over multiple OS I have created one wrapper logger class which actually wraps the functionality of logging module. I have created it so that every class in my application using logging doesn't need to add logging.config.fileConfig() and logging.getLogger() at the top every-time.
My wrapper class looks like this -
class MyFileLogger():
# The config file for logging formatter.
logging.config.fileConfig('logging.ini', disable_existing_loggers=False)
def __init__(self, name):
self.logger=logging.getLogger(name)
def log_debug(self, message):
self.logger.debug(message)
logging.ini file -
[loggers]
keys=root
[handlers]
keys=fileHandler
[formatters]
keys=myFormatter
[logger_root]
level=NOTSET
handlers=fileHandler
[handler_fileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=myFormatter
args=('testlog.log','midnight',)
[formatter_myFormatter]
format=%(asctime)s |%(name)-12s |%(levelname)-8s |%(message)s
datefmt=
class=logging.Formatter
MyFileLogger.py and logging.ini file resides on the same path. My intention to create testlog.log is also in same path as logging.ini file.
Implementation of the MyFileLogger.py would be like -
imp.py -
fileLogger = MyFileLogger(__name__)
message = "hey!"
fileLogger.log_debug(message)
Now this imp.py doesn't reside on the same path as MyFileLogger.py and logging.ini. That's why when I run it, this gives me below error cause the python is running at imp.py path.
File "C:\Python34\lib\logging\config.py", line 76, in fileConfig
formatters = _create_formatters(cp)
File "C:\Python34\lib\logging\config.py", line 109, in _create_formatters
flist = cp["formatters"]["keys"]
File "C:\Python34\lib\configparser.py", line 937, in __getitem__
raise KeyError(key)
KeyError: 'formatters'
I know if I just give an absolute path to logging.ini and testlog.log it will work. But I don't want to go there, since this application can be ran in Windows or in Linux. So there would be path problem.
Now even if I don't care about the Windows-Linux thing and only concentrate on the Linux. There is another problem. So if we assume the current directory structure as this ("ProjectDir/src" is added in PYTHONPATH and assuming there is __init__.py in every module folders)-
ProjectDir
βββ src
β βββ sales
β βββ common
β β βββ logger
β β β βββ logging.ini
β β β βββ MyFileLogger.py
β β β βββ testlog.log
β β βββ implmnts
β β βββ imp.py
β βββ unitTest
β βββ test_MyFileLogger.py
βββ bar.txt
Let's assume:
imp.py -
fileLogger = MyFileLogger(__name__)
message = "From imp.py"
fileLogger.log_debug(message)
test_MyFileLogger.py -
fileLogger = MyFileLogger(__name__)
message = "from test_MyFileLogger.py"
fileLogger.log_debug(message)
Then if I run imp.py I need to change the logging.config.fileConfig('logging.ini', disable_existing_loggers=False) to logging.config.fileConfig('../logger/logging.ini', disable_existing_loggers=False)
After that it will run but when I try to run test_MyFileLogger.py I need to change again to logging.config.fileConfig('../common/logger/logging.ini', disable_existing_loggers=False)
So my code is dependent upon which file I am running which I want to get rid of. Is there any way I can dynamically get the path of logging.ini and testlog.log independent of which file(from other path) is invoking this? I don't want to hardcore the absolute path, since this needs to run in both Windows and Linux, any solution?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43199316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: String diff to show positions of changed characters? I'm looking for a way to diff two strings and return the index value of where the changes start and finish.
I'm already using diff-lcs to find out which lines have changed, but I need to figure out the positions of which characters have changed. I need the positions of the new characters so I can handle them with JavaScript, not the actual text, which is what most diff tools seem to give.
So, for example if I have this string:
The brown fox jumps over the lazy dog
and compare to this string:
The red fox jumps over the crazy dog
I would like to see something like:
[[5,8],[28,33]]
Those numbers being the position where the new characters are found.
Does anyone have any idea how I might get this done?
A: How about the Google diff-match-patch code? https://github.com/elliotlaster/Ruby-Diff-Match-Patch
I've used it in the past and been happy with the results.
Taken from the documentation linked above:
# Diff-ing
dmp.diff_main("Apples are a fruit.", "Bananas are also fruit.", false)
=> [[-1, "Apple"], [1, "Banana"], [0, "s are a"], [1, "lso"], [0, " fruit."]]
You would just need to iterate through the non-matches and find the character position in the appropriate string.
pos_ary = s.enum_for(:scan, /search_string/).map { regexp.last_match.begin(0) }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21566537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android studio/libGDX/admob cannot find dependecies() So I've been searching around for days trying to figure out why I can't implement admob into my Android Studio project.
Things I've tried:
I have the google play services installed and latest Android SDKs
File->Project Structure->ads->ticking admob
--this will try to load in the dependencies, and always fails with
(Error:Could not find method dependencies() for arguments [build_23ysmkvnpvbphbg3g4deijgq4$_run_closure6@4afc19b] on org.gradle.plugins.ide.idea.model.IdeaModel_Decorated@18b40be.)
I've tried deleting the .gradle folder, restarting AS and rebuilding with the same Error.
I've tried creating a new blank LibGDX project and importing that and directly getting the admob dependencies and still the same error message.
I'm honestly not sure what I'm overlooking here.
If there's any info you feel I've left out, please let me know.
A: So, I'm coming from the Eclipse environment, and whenever I built a libgdx project, I've never had to go into the "advanced" settings. so messing around some more I went into the advanced settings and saw a checkbox for IDEA(generates intellij IDEA project files) which has seemed to work in getting rid of that error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43525285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scraping data from HTML to return to cells in Excel I am very new to coding. I know the basics, but I don't need that advanced of knowledge for my field--aside from this project.
I am attempting to search a license number on the AZ Medical Board website, click the search result to pull up a profile, and transfer the information on a profile to cells in Excel.
So far my code looks like this and it works perfectly (aside from the data scraping part)
Sub AZMDSearch()
Dim lastrow As Long
Dim Name2 As Object
lastrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To lastrow
Application.ScreenUpdating = False
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "https://gls.azmd.gov/glsuiteweb/clients/azbom/public/WebVerificationSearch.aspx"
Application.StatusBar = "Submitting"
While IE.Busy
DoEvents
Cells(i, 1).Select
Selection.Copy
Wend
'**********************************************************************
With IE.document
delay 1
.getelementbyid("tbFileNumber").Value = Cells(i, 1).Value
delay 1
.getelementbyid("btnLicense").Click
delay 2
.getelementsbytagname("a")(0).Click
End With
'**********************************************************************
The code does exactly what I want it to do up until this point.
Now, here's what the HTML looks like for the data I want to transfer over:
<span id="dtgGeneral_ctl02_lblLeftColumnEntName"><b>Gabby Laub
MD</b><br /></span>
<span id="dtgGeneral_ctl02_lblLeftColumnPracAddr"><br />1234 S Pine<br
/>Scottsdale AZ 85258<br />Phone: (123) 456-7891<br /></span>
I need to be able to pull the Name (Gabby Laub) into Cell(i,2), the address part 1 (1234 s Pine) into Cell(i,3), address part 2 (Scottsdale, AZ) into Cell(i,4), and phone number into Cell(i,5).
I was working on something like this:
Set Name = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").innerHTML
But it doesn't work at all. I have been working on this project for weeks, and I would really appreciate some help. Obviously I'm aware that I am missing Next i and End sub.
Again, the ONLY part I need help on is how to actually get the data into Excel.
Thanks!
A: You could try something like:
Cells(i, 2).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText
Cells(i, 3).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText
Since address1, address2 and phone would all be in Cells(i, 3) you might want to use to use text to column to split them into their appropriate columns.
Additionally you could create an array to store these data in if you're doing a bigger search. Then you could paste the array values into their cells after you've finished scraping, like:
searchInfo(i, 1) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText
searchInfo(i, 2) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText
Then after looping:
For i = 1 to last row
Cells(i,2).Value = searchInfo(i, 1)
Cells(i,3).Value = searchInfo(i, 2)
Next i
You'd still have the text to column issue but that can be solved pretty easily with some code in the loop. Specifics just depend on how the third column's values come out.
EDIT: Based on your comments below, this worked for me. It might take a little customizing, but this is the idea.
' remove .getelementsbytagname("a")(0).Click and replace with this
.location = .getElementsByTagName("a").getAttributes("href")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44557137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Arduino IDE on Android tablet Hi am wondering if anyone knows of a IDE for my Android tablet that I can edit compile and upload sketches to my Arduino board via USB?
A: Really slow response, I know but once this gets out of beta phase it could work http://codebender.cc/
A: You can have Arduino IDE on android, but have some problem with the usb port
http://arduino.cc/forum/index.php/topic,114141.0.html
veckoff
A: Not that I know of, but maybe you could build something like it with this?
http://www.amarino-toolkit.net/
A: You can upload sketch, no root required:
http://arduinocommander.blogspot.com/2013/03/upload-sketch.html
A: Check out ArduinoDroid - full-featured Arduino IDE on android:
https://play.google.com/store/apps/details?id=name.antonsmirnov.android.arduinodroid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3863498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Error in declaring data in rstan for graded response model I am trying to use Stan, specifically through rstan, to fit a graded response model. Luo and Jiao (2018), available here, provide Stan code for doing so. Here is their code, edited only to include more white space:
data{
int<lower=2, upper=4> K;β//number of categories
int <lower=0> n_student;
int <lower=0> n_item;
int<lower=1,upper=K> Y[n_student,n_item];
}
parameters {
vector[n_student] theta;
real<lower=0> alpha [n_item];
ordered[K-1] kappa[n_item];β//category difficulty
real mu_kappa;β//mean of the prior distribution of category difficulty
real<lower=0> sigma_kappa;β//sd of the prior distribution of category difficulty
}
model{
alpha ~ cauchy(0,5);
theta ~ normal(0,1);
for (i in 1: n_item){
for (k in 1:(K-1)){
kappa[i,k] ~ normal(mu_kappa,sigma_kappa);
}}
mu_kappa ~ normal(0,5);
sigma_kappa ~ cauchy(0,5);
for (i in 1:n_student){
for (j in 1:n_item){
Y[i,j] ~ ordered_logistic(theta[i]*alpha[j],kappa[j]);
}}
}
generated quantities {
vector[n_item] log_lik[n_student];
for (i in 1: n_student){
for (j in 1: n_item){
log_lik[i, j] = ordered_logistic_log (Y[i, j],theta[i]*alpha[j],kappa[j]);
}}
}
However, when I try to use this code, the parser throws an error. Here is the R code to reproduce the error:
library("rstan")
n <- 100
m <- 10
K <- 4
example_responses <- sample(x = 1:4, size = n * m, replace = TRUE)
example_responses <- matrix(example_responses, nrow = n, ncol = m)
example_dat <- list(K = K,
n_student = n,
n_item = m,
Y = example_responses)
fit <- stan(file = "~/grm.stan", data = example_dat)
Here is the error I receive:
SYNTAX ERROR, MESSAGE(S) FROM PARSER:
error in 'modelf6471b3f018_grm' at line 2, column 21
-------------------------------------------------
2:
3: data {
4: int<lower=2, upper=4> K;β// number of categories
^
5: int<lower=0> n_student;
-------------------------------------------------
PARSER EXPECTED: <one of the following:
a variable declaration, beginning with type,
(int, real, vector, row_vector, matrix, unit_vector,
simplex, ordered, positive_ordered,
corr_matrix, cov_matrix,
cholesky_corr, cholesky_cov
or '}' to close variable declarations>
Error in stanc(file = file, model_code = model_code, model_name = model_name, :
failed to parse Stan model 'grm' due to the above error.
I've tried going through the code and the Stan manual to see what the issue is with the data declaration, but I can't find a problem with it. The declaration appears to be very similar to a declaration example in the Stan Language Reference:
int<lower = 1> N;
Can anyone tell me what I'm missing?
A: Your code has non-standard characters in some of the white space, including right after K;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61894312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.