text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
"In" vs. "of" after the superlative form of adjectives
Hanna's the youngest member of the team.
Why isn't it "in the team"?
The rule that we covered in out textbook New Total English pre-intermediate says that we use in with groups of people and places but of with everything else.
I do understand that it does sound perfectly well this way: "a member of". Member collocates with of, not something else. But how does the rule apply here?
A:
Both in and of are possible after superlatives. ‘An A-Z of English Grammar’ by Geoffrey Leech and others explains that ‘usually “of” is followed by a plural noun, while “in” is followed by a singular noun.’ Of is perhaps more usual with team because, although it is grammatically singular, it represents a group of people.
A:
The preposition does not depend on fact that it is a superlative, but on the following words. We say somebody is a "member of a team", so he is
the youngest member of the team.
On the other hand, we say somebody is a "player on a team", so he is
the youngest player on the team.
We say somebody is a "student in a class", so she would be
the youngest student in the class.
And we say somebody is a "student at a university", so she would be
the youngest student at the university.
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearch array only gives uniques to aggregation script
I would like to do some simple linear algebra in Elasticsearch with a scripted metric in an aggregation. I am trying to use an array type to store a vector. My issue is that in my script, I am receiving only a set of unique values from the array, rather than the full array with its original sorting. Is there a way to get the original array in the script?
Consider this example document:
curl -XPUT 'http://localhost:9200/arraytest/aoeu/1' -d '{
"items": [1, 2, 2, 3]
}'
It looks right in the _source:
curl -XGET 'http://localhost:9200/arraytest/aoeu/1'
result:
{"_index":"arraytest","_type":"aoeu","_id":"1","_version":1,"found":true,"_source":{
"items": [1, 2, 2, 3]
}}
However, it does not look right when I get the value in a script:
curl -XGET 'http://localhost:9200/arraytest/aoeu/_search?pretty&search_type=count' -d '{
"query": {
"match_all" : {}
},
"aggs": {
"tails": {
"scripted_metric": {
"init_script": "_agg.items = []",
"map_script": "_agg.items.add(doc.items)",
"reduce_script": "items = []; for (a in _aggs) { items.add(a.items) }; return items"
}
}
}
}'
result:
{
"took" : 103,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"tails" : {
"value" : [ [ ], [ ], [ [ 1, 2, 3 ] ], [ ], [ ] ]
}
}
}
I was expecting the result to include [1, 2, 2, 3], but instead it includes [1, 2, 3]. I tried accessing _source in the map script but it said there is no such field.
A:
I found the issue in the docs, in a discussion about a different but related problem. Arrays of inner objects are flattened for indexing. This means that the set of all values of an inner object (or one of its fields) becomes an array on the root document.
Rather than relying on dynamic mapping, which indexes arrays of inner documents with the above effect, one can specify a nested object mapping. Elasticsearch will then not flatten the array of inner documents, but rather store them separately and index them in a way that makes joins "almost as fast" as having them embedded in the same document. Having played with it a little, I found that it makes my use case, which doesn't involve joins, fast as well (in comparison with creating a separate root document for every sub document).
I don't think this solves for preserving the order of the vector, so I will include the index on each nested document.
Example mapping:
curl -XPUT 'http://localhost:9200/arraytestnested' '{
"mappings" : {
"document" : {
"properties" : {
"some_property" : {
"type" : "string"
},
"items": {
"type": "nested",
"properties": {
"index" : {
"type" : "long"
},
"itemvalue" : {
"type" : "long"
}
}
}
}
}
}
}'
| {
"pile_set_name": "StackExchange"
} |
Q:
How to enlarge grommets
I've installed a telescoping curtain rod that's 1-1/2" in diameter, and bought curtains with grommets that turned out to be only 1.6" in diameter (outer diameter 2.7").
Unsurprisingly, the grommets don't slide easily at all, especially over the two joint between the telescoping portions of the rod. A curtain wand wouldn't help because if I climb on a ladder and pull exactly where the wand would, the grommets still turn at an angle against the rod and block.
Is there some hack I haven't thought of, or another solution other than getting new curtains (expensive and hard to find - I need 100" W x 95"L blackout panels) or returning and replacing the rod (the brackets were a pain to mount)?
The must be a machine that could file the grommets from the inside, but I don't know the name for it. Essentially, a cone-shaped grinding stone/bit that spins around its axis, so I could lower the grommets and shave off a few millimeters from the inner diameter to reach the recommended 1/4" difference between grommet inner diameter and rod outer diameter.
A:
Grommets are typically thin wall tubing with the ends peened over to form the flange you see in the photo. Any tool used to grind away at the inside diameter will remove most or all of the thin wall tubing composing the grommet.
The primary option you have is to remove the existing grommets and purchase a grommet installation kit for the size you need. It's an anvil smaller than a hockey puck and a driving tool. The grommet half is placed through the hole, then set on the anvil with the other grommet half on top of the fabric. The driving tool has a recess and a point to match the inside and outside curves of the grommet. A solid strike with the hammer provides the bending and bonding force.
There are other types of grommet installation tools resembling mechanical presses with much higher prices. For the occasional or hobbyist use, the hammer method is more cost effective, with the slight penalty of inconsistent results.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I find which rpm package supplies a file I'm looking for?
As an example, I am looking for a mod_files.sh file which presumably would come with the php-devel package. I guessed that yum would install the mod_files.sh file with the php-devel x86_64 5.1.6-23.2.el5_3 package, but the file appears to not to be installed on my filesystem.
How do I find out which package installs a specific file? I'm looking for where I have not necessarily already locally downloaded the package which may include the file that I'm looking for.
I'm using CentOS 5.
A:
This is an old question, but the current answers are incorrect :)
Use yum whatprovides, with the absolute path to the file you want (which may be wildcarded). For example:
yum whatprovides '*bin/grep'
Returns
grep-2.5.1-55.el5.x86_64 : The GNU versions of grep pattern matching utilities.
Repo : base
Matched from:
Filename : /bin/grep
You may prefer the output and speed of the repoquery tool, available in the yum-utils package.
sudo yum install yum-utils
repoquery --whatprovides '*bin/grep'
grep-0:2.5.1-55.el5.x86_64
grep-0:2.5.1-55.el5.x86_64
repoquery can do other queries such as listing package contents, dependencies, reverse-dependencies, etc.
A:
To know the package owning (or providing) an already installed file:
rpm -qf myfilename
A:
The most popular answer is incomplete:
Since this search will generally be performed only for files from installed packages, yum whatprovides is made blisteringly fast by disabling all external repos (the implicit "installed" repo can't be disabled).
yum --disablerepo=* whatprovides <file>
| {
"pile_set_name": "StackExchange"
} |
Q:
bash scripting how convert log with key into csv
I have a log with format like a table
ge-1/0/0.0 up down inet 10.100.100.1/24
multiservice
ge-1/0/2.107 up up inet 10.187.132.193/27
10.187.132.194/27
multiservice
ge-1/1/4 up up
ge-1/1/5.0 up up inet 10.164.69.209/30
iso
mpls
multiservice
how we convert it to format csv like below:
ge-1/0/0.0,up,down,inet|multiservice,10.100.100.1/24
ge-1/0/2.107,up,up,inet|multiservice,"10.187.132.193/27,10.187.132.194/27"
ge-1/1/4,up,up
ge-1/1/5.0,up,up,inet|iso|mpls|multiservice,10.164.69.209/30
I've tried with grep interfacename -A4 but it's display other interface information.
A:
#!/bin/bash
show() {
[ "$ge" ] || return
[ "$add_quotes" ] && iprange="\"$iprange\""
out="$ge,$upd1,$upd2,$service,$iprange"
out="${out%%,}"
echo "${out%%,}"
}
while read line
do
case "$line" in
ge*)
show
read ge upd1 upd2 service iprange < <( echo "$line" )
add_quotes=
;;
[0-9]*)
iprange="$iprange,$line"
add_quotes=Y
;;
*)
service="$service|$line"
;;
esac
done
# Show last line
show
With your sample data provided as stdin, this script returns:
ge-1/0/0.0,up,down,inet|multiservice,10.100.100.1/24
ge-1/0/2.107,up,up,inet|multiservice,"10.187.132.193/27,10.187.132.194/27"
ge-1/1/4,up,up
ge-1/1/5.0,up,up,inet|iso|mpls|multiservice,10.164.69.209/30
How it works: This script reads from stdin line by line (while read line). Each line is then classified into one of three types: (a) a new record (i.e. a line that starts with "ge-"), (b) a continuation record that provides another IP range (i.e. a record that starts with a number), or (c) a continuation line that provides another service (i.e. a record that starts with a letter). Taking these cases in turn:
(a) When the line contains the start of a new record, that means that the previous record has ended, so we print it out with the show function. Then we read from the new line the five columns that I have named: ge upd1 upd2 service iprange. And, we reset the add_quotes variable to empty.
(b) When the line contains just another IP range, we add that to the current IP range. As per the example in the question, combinations of two or more IP ranges are separated by a comma and enclosed in quotes. Thus, we set add_quotes to "Y".
(c) When the line contains an additional service, we add that to the service variable. As per the example in the question, two services are separated by a vertical bar "|" and no quotes are used.
The function show first checks to make sure that there is a record to show by checking that the ge variable is non-empty. If it is empty, then the return statement is executed so that the function exits (returns) without processing any of its further statements. If $ge was non-empty, the function proceeds to the next statement which adds quotes around the IP range variable if they are needed. It then combines the variables with commas separating them, removes trailing commas (as per the example in the question), and sends the result to stdout.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a list through looping
I'm trying to make new list through looping conversions, but only the final conversion gets put in list because conversion variable always stays the same
celsius_temps = [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6]
number = 0
for i in range(1,len(celsius_temps)+1):
conversion = celsius_temps[0+number]*1.8000 + 32
number += 1
fahrenheit_temps = [conversion]
print fahrenheit_temps
A:
You are creating a new list object each iteration:
fahrenheit_temps = [conversion]
You'd create an empty list object outside the loop and append results to that:
number = 0
fahrenheit_temps = []
for i in range(1,len(celsius_temps)+1):
conversion = celsius_temps[0+number] * 1.8 + 32
number += 1
fahrenheit_temps.append(conversion)
You really want to clean up that loop though; you are not using i where you could simply produce number with it:
fahrenheit_temps = []
for number in range(len(celsius_temps)):
conversion = celsius_temps[number] * 1.8 + 32
fahrenheit_temps.append(conversion)
or better still, just loop over celcius_temps directly:
fahrenheit_temps = []
for temp in celsius_temps:
conversion = temp * 1.8 + 32
fahrenheit_temps.append(conversion)
You could also produce the whole fahrenheit_temps in one go with a list comprehension:
fahrenheit_temps = [temp * 1.8 + 32 for temp in celsius_temps]
A quick demo of that last line:
>>> celsius_temps = [25.2, 16.8, 31.4, 23.9, 28.0, 22.5, 19.6]
>>> [temp * 1.8 + 32 for temp in celsius_temps]
[77.36, 62.24, 88.52, 75.02, 82.4, 72.5, 67.28]
| {
"pile_set_name": "StackExchange"
} |
Q:
how do I get the listview id when the listview is clicked in bloc flutter?
I have successfully displayed the API responses in the listview, but I want when the listview is pressed then I can get the id of the listview item. How do I get the ID ???
I have API responses like the following:
"payload": [
{
"id": "402",
"desc": "FAR"
},
{
"id": "406",
"desc": "HGR"
},
{
"id": "403",
"desc": "Baf"
},
]
this is the bloc I made :
I am confused how to get the ID when the listview item is clicked, how is it ???
class ListMultibillBloc {
final _repository = EresidenceRepository();
SharedPreferences sPrefs;
final BehaviorSubject<List<Payload>> _subject = BehaviorSubject<List<Payload>>();
listMultibill() async{
try{
sPrefs = await SharedPreferences.getInstance();
ListServiceMultibill responses = await _repository.listServiceMultibill(sPrefs.getString("userid"), sPrefs.getString("password"), sPrefs.getString("imei"),
sPrefs.getString("coordinate"), sPrefs.getString("bnr"));
List<Payload> list = responses.data.payload;
_subject.sink.add(list);
}catch(e){
print(e.toString());
_subject.sink.add(e);
}
}
dispose(){
_subject.close();
}
BehaviorSubject<List<Payload>> get subject => _subject;
}
final listMultibill = ListMultibillBloc();
this is the UI part :
I can display the data list
class _ListMultibillState extends State<ListMultibill> {
@override
void initState() {
listMultibill.listMultibill();
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: StreamBuilder(
stream: listMultibill.subject,
builder: (context, AsyncSnapshot<List<Payload>> snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
return buildList(snapshot);
}else{
Error();
}
},
),
),
);
}
Widget buildList(AsyncSnapshot<List<Payload>> snapshot) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
snapshot.data[index].desc,
style: AppTheme.styleSubTitleBlackSmall,
),
);
}
);
}
}
A:
You can add onTap in ListTile,
onTap:() {
print("${snapshot.data[index].id}");
},
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add an exception to a jQuery that disables right-click?
I am trying to disable right-click in the whole page except for two elements that are meant to be copied. I know disabling right-click sounds like a bad idea about every time, but it makes sense to me in this case. I found some information about how to unbind elements to re-enable a behaviour that was prevented using preventDefault(); and also tried with return: true for the exceptions, but it wasn't successful. There's no trigger for re-enabling the right-click feature, it should be all at once.
$(function() {
$(document).ready(function() {
$(document).bind('contextmenu', function(e) {
e.preventDefault();
});
});
});
I also tried this:
var disablerightclick = function(e) {
e.preventDefault();
}
$(document).ready(function() {
$(document).bind('contextmenu', disablerightclick);
});
//]]>
It works everytime. But it doesn't let me unbind anything else directly below and it makes sense it doesn't, I will try something and update whether it works or not.
This is the update I mentioned previously. It doesn't work...
var disablerightclick = function(e) {
return false;
}
$(document).ready(function() {
$('img').mousedown(function(){return false});
$('body').bind('contextmenu', disablerightclick);
});
$('#AnyObject').hover(function() {
$('body').unbind('contextmenu', disablerightclick);
});
I will keep trying since I am not getting any answer.
A:
Just read this thread
Use this code:
$(document).on('contextmenu', function(e) {
if (!$(e.target).is("#special"))
return false;
alert('#special right clicked');
// you may want e.preventDefault() here
});
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Javascript T_VAR
I'm attempting to extract lat/long points from MySQL to eventually plot them in Leaflet using Javascript. I ran the following PHP code (planelatlong.php) and got an error:
Parse error: syntax error, unexpected 'var' (T_VAR) on line 24.
I looked at similar errors on Stack Overflow for T_VAR, but couldn't find a clear solution for my issue.
Code:
<?php
$username = "stackoverflow";
$password = "thanksstackoverflow";
$host = "localhost";
$database="homedb";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
echo "Connected successfully";
$myquery = "SELECT 'lat', 'lon' FROM 'test01';
$query = mysql_query($myquery);
if (!$query) {
echo mysql_error();
die;
}
$data = array();
echo "var planelatlong = [";
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
echo "[",$data[$x]['lat'],",",$data[$x]['lon'],"]";
if ($x <= (mysql_num_rows($query)-2) ) {
echo ",";
}
}
echo "];";
mysql_close($server);
?>
A:
I think you forgot to end double quote at line 13. Use below line
$myquery = "SELECT 'lat', 'lon' FROM 'test01'";
| {
"pile_set_name": "StackExchange"
} |
Q:
Lodash:Getting new array with multiple key-value matches in json
I have nessted JSON look like this
[
{arrivalTime: "10:30 PM"
availableSeats: 23
boardingPoints: [{id: "3882"
location: "abc"
time: "02:30PM"},{id: "3882"
location: "xyz"
time: "02:30PM"}]
busType: "Scania Metrolink"
operatorName:"sham"
commPCT: 8
departureTime: "1:15 PM"
droppingPoints: [{id: "3882"
location: "dex"
time: "02:30PM"},{id: "3882"
location: "afg"
time: "02:30PM"}]
},
{arrivalTime: "10:30 PM"
availableSeats: 23
boardingPoints: [{id: "3882"
location: "def"
time: "02:30PM"},{id: "3882"
location: "jkl"
time: "02:30PM"}]
busType: "Scania "
operatorName:"manu"
commPCT: 8
departureTime: "1:15 PM"
droppingPoints: [{id: "3882"
location: "ccd"
time: "02:30PM"},{id: "3882"
location: "eef"
time: "02:30PM"}]
}
]
From this i want to get new array that matches the these key values.
Here is the keys.
1.BoardingPoints.
2.DroppingPoints.
3.busType.
4.OperatorName.
Eg:
if the input like this
BoardingPoints=['abc']
DroppingPoints=['ccd','eef']
busType=['Scania Metrolink'],
OperatorName=['manu']
It should returns these two rows
{arrivalTime: "10:30 PM" availableSeats: 23 boardingPoints: [{id:
"3882" location: "abc" time: "02:30PM"},{id: "3882" location:
"xyz" time: "02:30PM"}] busType: "Scania Metrolink"
operatorName:"sham" commPCT: 8 departureTime: "1:15 PM"
droppingPoints: [{id: "3882" location: "dex" time: "02:30PM"},{id:
"3882" location: "afg" time: "02:30PM"}] },
{arrivalTime: "10:30 PM"
availableSeats: 23 boardingPoints: [{id: "3882" location: "def" time:
"02:30PM"},{id: "3882" location: "jkl" time: "02:30PM"}] busType:
"Scania " operatorName:"manu" commPCT: 8 departureTime: "1:15 PM"
droppingPoints: [{id: "3882" location: "ccd" time: "02:30PM"},{id:
"3882" location: "eef" time: "02:30PM"}] } ]
Note
Each input is passed as an array because i need to match multiple values in the keys.
A:
From the expected result, it looks like you are looking for the objects that match any of the 4 variables. Here is the filter that will match them:
var bpLocations = ['abc'];
var dpLocations = ['ccdll', 'eef'];
var busTypes = ['Scania Metrolink'];
var operatorNames = ['manu'];
var result = _.filter(inputArray, function(obj) {
return _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0
|| _(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
|| _.includes(busTypes, obj.busType)
|| _.includes(operatorNames, obj.operatorName);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Move files from a "Synced Folder" on my computer to a different folder on google drive
Hey guys Ive been trying to make a script that will take files from a folder on my computer that is synced to my google drive (shows up under Computers>My Computer) and move them to a folder under My Drive. So far this is what im working with. However, Im getting this error "ReferenceError: "target" is not defined. (line 10, file "Code")".
This is my first time trying to do something like this so I'm not very experience. I'm not sure what I have to change target to. Any advice would be appreciated or if you see anything else wrong with my code that would be helpful too.
Thanks!
function copyFilesAndTrash(source_folder, dest_folder) {
var source_folder = DriveApp.getFolderById('1N86jGD2EJjbpjdY5TTBAbHDAYLMRdGUe')
var dest_folder = DriveApp.getFolderById('1rveHeNuwKxnqWcVv3Da_N-uI_NJV-PpY')
var files = source_folder.getFiles();
while (files.hasNext()) {
var file = files.next();
file.makeCopy(target).setName(file.getName());
file.setTrashed(true);
}
}
A:
Your "target" variable is used in file.makeCopy(target), but it is not initialized anywhere in your code.
Likewise, dest_folder is defined but not used anywhere.
Try changing "target" for "dest_folder" as this will most likely correct your code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add a button at the last cell of UITableView
I currently have 2 UITableView to filter out 2 category,
my category is cat and dog, 1st UITableView that handles cat and 2nd UITableView that handles dog.
What i want is to have cat and dog into one UITableview,
so the in the UITableView, the first part will be the cats, and the second part is the dog. what i want to do is to put a button above the dog part where it will be used as a separator for two category.
this is the illustration:
the 2 cells in the top is the cat
and the one cell in the bottom is a dog there should be a button in the middle of the two category as a seperator.
A:
Try this code.
@interface ViewController () <UITableViewDelegate, UITableViewDataSource> {
NSArray *arrCat;
NSArray *arrDog;
}
- (void)viewDidLoad {
[super viewDidLoad];
arrCat = @[@"Cat 1", @"Cat 2", @"Cat 3", @"Cat 4", @"Cat 5"];
arrDog = @[@"Dog 1", @"Dog 2", @"Dog3 ", @"Dog4 ", @"Dog 5"];
}
I have Programatically create Header, You can also create it by creating xib.
Add UITableView delegate and DataSource like this.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return arrCat.count;
}
return arrDog.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"TableViewCell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil] objectAtIndex:0];
}
if (indexPath.section == 0) {
cell.lblCategory.text = arrCat[indexPath.row];
}
else {
cell.lblCategory.text = arrDog[indexPath.row];
}
return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 60)];
view.backgroundColor = [UIColor greenColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = view.frame;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.textColor = [UIColor blackColor];
[view addSubview:button];
if (section == 0) {
[button setTitle:@"CAT" forState:UIControlStateNormal];
}
else {
[button setTitle:@"DOG" forState:UIControlStateNormal];
}
return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 60.0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL: can a table get stuck in the table cache?
I've asked this question on the ServerFault stackexchange, someone directed me here.
I'm a PHP developer and am responsible for a set of PHP scripts that run on a shared host running FreeBSD, that has a MySQL server (version 4.1.14-standard). Before anyone makes the remark: the decision to use a MySQL 4 server was not made by me, and any decision to upgrade is unfortunately also not mine to make.
Last January, I added a table to the database, and updated the PHP script so that each time the application is started, a row is inserted into this table. I set up the table so it started with a number of rows already in it. In the mean time, our client has been merrily using their application, causing several rows to be added to the table.
Last week, I wrote a PHP script that fetches all rows from the table and builds a report from the result, and ran it, only to find that several rows were missing. In fact, only the rows I started off with, seemed to be present in the report. I attributed this to no-one having used the application in the mean time. Yesterday, however, I decided to check if this was actually true. So I fired up phpMyAdmin, exported the database, and ran the report locally, only to find new data present and accounted for. So I checked if the code on the live site was up to date, and this is the case. Stumped, I ran the report on the live site again, and presto: there the missing rows were.
My reasoning:
The issue has to be some kind of cache thing, because the table has two DATE columns, they are filled with INSERT queries, and possibly updated with UPDATE queries, each time with NOW() as the value, never any other value, and the dates in the table were spread across the past half year. Last week I saw no new rows since January, but yesterday morning I saw all these rows with these dates in them: the new rows cannot all have been added in the past week.
I did not publish any code, or push data to the MySQL server, since I first ran the report.
It can't be a browser cache issue, because I wrote the report script last week: if it were a browser cache issue, it would have been a cache entry from January. Since the script did not exist then, the information can't come from my browser cache; and besides, we web developers clear our browser caches weekly, if not several times per day and I am no exception.
If it's a cache issue and it's not a browser cache issue, it has to be a MySQL cache issue.
However, it can't be a MySQL cache issue either, because the query cache gets invalidated as soon as a new row is inserted, which has happened several times the last half year. It also can't be the table cache, because table_cache is set to 64, open_tables is 64, and opened_tables is about 13 million. So if there is something wrong with the table cache at all, I'd expect "too new" data, instead of "too stale" data.
My working theory, for lack of a better one, is that somehow, despite my reasoning, the table got "stuck" in the MySQL table cache, and that exporting the table data with phpMyAdmin caused the table to "unstick".
All database queries the application does, are done with PHP's mysql_* functions: again, not my decision: I'd much rather use PDO, but am stuck with PHP 4. Anyway, the application does not use Memcached, so that's ruled out.
My question is: why did I get the older version of the table data, and is there any way I can prevent this from happening again?
The table in question:
CREATE TABLE `offset` (
`id` int(10) NOT NULL auto_increment,
`version` int(10) NOT NULL default '0',
`user_id` int(10) NOT NULL default '0',
`client` varchar(255) NOT NULL default '',
`created_on` datetime default NULL,
`modified_on` datetime default NULL,
`hidden` tinyint(1) default '0',
PRIMARY KEY (`id`,`version`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=302 ;
A:
The table cache does not store data, only MySQL table structs. The query cache cannot return old results because all the queries sing it are invalidated on write, and selects are blocked until that happens (actually causing some contention problems).
I will not discard a MySQL bug, as you are using a 9-year old unsupported version of the server, but you were too quick to discard cache issues/errrors on the other many layers of your application (client, server code, connector, your report code running on the wrong server, etc.).
To solve problems like this, you need to monitor queries sent and results returned at MySQL level and others, so you have enough information to identify the problem. I also recommend you to get familiar with the mysql command line client, as it is the best way to debug server issues.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wrapping Wayfinder Menu in Modx: How to pass all vars (general PHP question, perhaps)
I have made a tiny ModX snippet that looks like this
<?php
$theMenu = $modx->runSnippet('Wayfinder',
array("startId" => 0, "level"=>1)
);
echo $theMenu;
?>
but I would like it to pass ALL params it receives to Wayfinder. I will only be modifying the "level" parameter from my snippet.
Is there any way, without naming all the relevant variables individually, to cycle through all the currently SET variables in PHP?
Edit: I don't think that get_defined_vars is the right way to go, as it gets too much stuff. This trivial PHP page prints out the number 14, for instance:
<?php
echo count(get_defined_vars());
?>
A:
This might be useful: get_defined_vars() ?
Edit
From http://bobsguides.com/modx-snippet-faq.html:
You can also access the parameters via
the associative array
$modx->event->params.
| {
"pile_set_name": "StackExchange"
} |
Q:
webRTC-enabled browser for iOS?
Preface: there are questions (some good, some bad) already in existance on StackOverflow about webRTC support on various browsers and platforms, including iOS. However I couldn't find anything definitive that was more recent than ~2012, and this is a rapidly-changing field.
I'm working on a browser-based webapp that uses webRTC for minimal-latency peer-to-peer data transfer (not for audio/video, unlike most applications it would seem - all I need is DataChannel).
I hit a snag when I started testing the data-transfer part of the project and discovered that iOS devices still don't natively support this in their built-in browsers (despite some recent rumors).
Bowser is a free open-source browser App for iOS that purports to support webRTC on iOS. The problem is that when I try to open the app, it simply crashes and closes. I've tested this on an iPhone 5 and 5s. Googling has failed to turn up alternatives - even Chrome for iOS doesn't currently support webRTC it seems.
My questions:
1) Are there alternative browsers (even iOS-version restricted) that are currently supporting webRTC, or is there anything promising coming down the pipeline?
2) Does Bowser actually work (webRTC) on iOS devices where it doesn't crash immediately upon launch?
3) What strategies have other people used to work around this limitation?
A:
As of iOS 11, WebRTC is now supported in Safari: https://developer.apple.com/library/archive/releasenotes/General/WhatsNewInSafari/Articles/Safari_11_0.html#//apple_ref/doc/uid/TP40014305-CH13-SW1
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add Application not website on IIS 7.5?
I am trying to add a new Application on IIS 7.5, but that option is not there!
any suggestions , am I missing something, or do I have to reinstall the IIS ?
tanks
A:
Think of the website as the parent entity and the application as a child.
You will need to add/create a website then you can add applications beneath the website.
I attempted to add some screen shots for you but apparently my reputation is not high enough.
| {
"pile_set_name": "StackExchange"
} |
Q:
Double child added on expandable listview
I have problem adding children ,when i add one child then on ui two child appear with same childposition..my problem is similar to these mentioned in following questions
Child Layout is repeating many times in ExpandableListView
https://stackoverflow.com/questions/10938763/double-child-entries-in-expandablelistview
But unable to find a solution .. please see my code here
Value for children is given using this double dimension array..
String[][] child = {
mContext.getResources().getStringArray(R.array.alerts),
mContext.getResources().getStringArray(R.array.alerts),
mContext.getResources().getStringArray(R.array.alerts),
mContext.getResources().getStringArray(R.array.alerts),
mContext.getResources().getStringArray(R.array.alerts) };
I used this :
@Override
public int getChildrenCount(int groupPosition) {
return child.length;
}
but for this also child count is 5 and it shows up 10 items..
A:
It seems you are hard-coded child position like,
@Override
public int getChildrenCount(int groupPosition) {
return 1;
}
where as it should be your_data_collection_size
Also, you have hard-coded childId like,
@Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
which should be childPosition not 0
If you further have any query/problem you can download and check my demo example from you github and can come back to me with your query if you have any thereafter.
A:
I had the exact same problem and turns out it's because I returned false in onGroupClick method in OnGroupClickListener. Here is a solution:
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int position, long id) {
// ... do stuff //
return true; // make sure you return true.
}
| {
"pile_set_name": "StackExchange"
} |
Q:
MYSQL HAVING with nonexistent entries
i want to select a max of s2.maxcol or 0 if there are no entries.
So far this works, but if there is no corresponding entry it is not returned:
SELECT MAX( s2.maxcol) AS max_col, s1 . *
FROM table AS s1
LEFT JOIN table AS s2 ON s2.parent = s1.id
GROUP BY s1.id
HAVING max_col <100
But i also want to have the rows where the left join returns no corresponding entry (so max(s2.maxcol) should be 0.
How can i solve that?
A:
changed HAVING max_col <100 to HAVING max_col is NULL or max_col <100
which works flawlessly.
| {
"pile_set_name": "StackExchange"
} |
Q:
convert json to array and get array value
Here i tried to conver json into array and then fetching array value.
I checked SO threads and tried with similar approach, but still giving error:
Warning: Invalid argument supplied for foreach() in
<?php
$json = '[{"post_content": "nyone pls. guide me, for launching the website from where we can get the webspace and what should be the speed etc, the domain is booked through godaddy, Your technical guidance is appreciated. Thanks","name": "Uncategorized","taxonomy": "category"}, {"post_content": "Anyone know of a good Indian design firm for startups which also codes clean HTML and CSS (using technologies like sass, compass, grunt etc...)
Basically both great design + web development","name": "services","taxonomy": "discussion_type"}, {"post_content": "Anyone know of a good Indian design firm for startups which also codes clean HTML and CSS (using technologies like sass, compass, grunt etc...)
Basically both great design + web development","name": "Design","taxonomy": "discussion_tag"}, {"post_content": "Anyone know of a good Indian design firm for startups which also codes clean HTML and CSS (using technologies like sass, compass, grunt etc...)
Basically both great design + web development","name": "Front End","taxonomy": "discussion_tag"}, {"post_content": "Ajit Nazre (Harvard )Whole world is visiting what are you waiting for visit my website & thanks for your visit !
get more updates on http://www.ajitnazre.com","name": "articles","taxonomy": "discussion_type"}, {"post_content": "Design Thinking for Startups.
Can a startup be designed specifically? Can you have a designer startup?
Maybe YES.
We are exploring the process of design thinking and how it applies to startups. Once complete, the process can be used to design a startup business, that will enable founders to take a correct roadmap, avoid traps and failures and post clear signs on strategy and direction.
Stay tuned.
#startupden","name": "Design Thinking","taxonomy": "discussion_tag"}, {"post_content": "Hello people! These are 5 questions, and will take less than a minute to fill up! This is really important for me. Thanks!
https://docs.google.com/forms/d/1Axk7UZsZkiVXLroOk9Cc2wCgFZBTBWNOGgRU9nyYI1E/edit","name": "Survey","taxonomy": "discussion_tag"}, {"post_content": "Hello people! These are 5 questions, and will take less than a minute to fill up! This is really important for me. Thanks!
https://docs.google.com/forms/d/1Axk7UZsZkiVXLroOk9Cc2wCgFZBTBWNOGgRU9nyYI1E/edit","name": "Food","taxonomy": "discussion_tag"}, {"post_content": "Please suggest best plagiarism tool other than smallseotool.com...","name": "Suggestion","taxonomy": "discussion_tag"}, {"post_content": "Please suggest best plagiarism tool other than smallseotool.com...","name": "Content","taxonomy": "discussion_tag"}, {"post_content": "Please suggest best plagiarism tool other than smallseotool.com...","name": "Tool","taxonomy": "discussion_tag"}, {"post_content": "Looking to buy short form video (30 seconds to 1 min ) across all genres . Should be original content only .","name": "buy-sell","taxonomy": "discussion_type"}, {"post_content": "Looking to buy short form video (30 seconds to 1 min ) across all genres . Should be original content only .","name": "Content","taxonomy": "discussion_tag"}]';
$arr = json_decode($json, TRUE);
foreach ($arr as $r)
{
echo $r['post_content'];
}
?>
A:
Your json is in different lines. It should be in one line. See below :-
<?php
$json = '[{"post_content": "nyone pls. guide me, for launching the website from where we can get the webspace and what should be the speed etc, the domain is booked through godaddy, Your technical guidance is appreciated. Thanks","name": "Uncategorized","taxonomy": "category"}, {"post_content": "Anyone know of a good Indian design firm for startups which also codes clean HTML and CSS (using technologies like sass, compass, grunt etc...)Basically both great design + web development","name": "services","taxonomy": "discussion_type"}, {"post_content": "Anyone know of a good Indian design firm for startups which also codes clean HTML and CSS (using technologies like sass, compass, grunt etc...)Basically both great design + web development","name": "Design","taxonomy": "discussion_tag"}, {"post_content": "Anyone know of a good Indian design firm for startups which also codes clean HTML and CSS (using technologies like sass, compass, grunt etc...)Basically both great design + web development","name": "Front End","taxonomy": "discussion_tag"}, {"post_content": "Ajit Nazre (Harvard )Whole world is visiting what are you waiting for visit my website & thanks for your visit !get more updates on http://www.ajitnazre.com","name": "articles","taxonomy": "discussion_type"}, {"post_content": "Design Thinking for Startups.Can a startup be designed specifically? Can you have a designer startup?Maybe YES.We are exploring the process of design thinking and how it applies to startups. Once complete, the process can be used to design a startup business, that will enable founders to take a correct roadmap, avoid traps and failures and post clear signs on strategy and direction.Stay tuned.#startupden","name": "Design Thinking","taxonomy": "discussion_tag"}, {"post_content": "Hello people! These are 5 questions, and will take less than a minute to fill up! This is really important for me. Thanks! https://docs.google.com/forms/d/1Axk7UZsZkiVXLroOk9Cc2wCgFZBTBWNOGgRU9nyYI1E/edit","name": "Survey","taxonomy": "discussion_tag"}, {"post_content": "Hello people! These are 5 questions, and will take less than a minute to fill up! This is really important for me. Thanks! https://docs.google.com/forms/d/1Axk7UZsZkiVXLroOk9Cc2wCgFZBTBWNOGgRU9nyYI1E/edit","name": "Food","taxonomy": "discussion_tag"}, {"post_content": "Please suggest best plagiarism tool other than smallseotool.com...","name": "Suggestion","taxonomy": "discussion_tag"}, {"post_content": "Please suggest best plagiarism tool other than smallseotool.com...","name": "Content","taxonomy": "discussion_tag"}, {"post_content": "Please suggest best plagiarism tool other than smallseotool.com...","name": "Tool","taxonomy": "discussion_tag"}, {"post_content": "Looking to buy short form video (30 seconds to 1 min ) across all genres . Should be original content only .","name": "buy-sell","taxonomy": "discussion_type"}, {"post_content": "Looking to buy short form video (30 seconds to 1 min ) across all genres . Should be original content only .","name": "Content","taxonomy": "discussion_tag"}]';
$arr = json_decode($json, TRUE);
foreach ($arr as $r)
{
echo $r['post_content'];
}
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
What does "there is something!" mean?
I have come across it in the 11th episode of the 10th season of Friends. Here is the context:
Rachel: (finishing the last of her drink) I am soo not going to do
good on my SATs tomorrow.
Chandler: Well maybe if you go to school here next year we can totally
hang out.
Rachel: (sarcastic) Oh yeah. There is a plan! Why don't I just start
taking my smart pills now?
Does it mean that the plan is good?
A:
If you ignore (sarcastic) at the front, then you are correct that "There's a plan" (as it would normally be said/written) means something close to 'good' - it's only a good plan if it works!
However, the entire sentence is spoken sarcastically, so that needs to be negated - Rachel is actually saying that she doesn't like the idea at all.
A:
Yes, it means the plan is good. I suppose “there is a plan” acknowledges that you see it and are therefore giving it recognition as being important.
Of course, as you’ve pointed out, this is said sarcastically, and so really means the opposite of that.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to proof that $\mathbb{R}$ and $\mathbb{R}^2$ are not homeomorphic?
So I'm asked to proof that $\mathbb{R}$ and $\mathbb{R}^2$ are not homeomorphic. So far, I've been able to prove that $\mathbb{R}\backslash\{a\}$ and $\mathbb{R}^2\backslash\{b\}$ are not homeomorphic, for $a\in \mathbb{R}$ and $b\in \mathbb{R}^2$. But I don't know how to go on from here. Can anyone give me a hint?
A:
Hint. If $f \colon \def\R{\mathbf R}\R \to \R^2$ were a homeomorphism, what does this imply for the restriction $f\colon \R \setminus \{a\} \to \R^2 \setminus\{f(a)\}$?
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I identify partial duplicates in an excel list?
I have a list of over 1000 company names, however some are duplicated but they aren't exact duplicates (ie: Nintendo, Nintendo Inc, Nintendo Video games, etc), is there a way to identify the duplicates so that I can group them together?
I was using the below code but it's not picking up some of them and I can't figure out why.
Sub TestForDups()
Dim LLoop As Integer
Dim LTestLoop As Integer
Dim LClearRange As String
Dim Lrows As Integer
Dim LRange As String
Dim LChangedValue As String
Dim LTestValue As String
'Test first 2000 rows in spreadsheet for uniqueness
Lrows = 2000
LLoop = 2
'Clear all flags
LClearRange = "A2:A" & Lrows
Range(LClearRange).Interior.ColorIndex = xlNone
'Check first 2000 rows in spreadsheet
While LLoop <= Lrows
LChangedValue = "A" & CStr(LLoop)
If Len(Range(LChangedValue).Value) > 0 Then
'Test each value for uniqueness
LTestLoop = 2
While LTestLoop <= Lrows
If LLoop <> LTestLoop Then
LTestValue = "A" & CStr(LTestLoop)
'Value has been duplicated in another cell
If InStr(Range(LTestValue).Value, Range(LChangedValue).Value) > 0 Then
'Set the background color to red
Range(LChangedValue).Interior.ColorIndex = 3
Range(LTestValue).Interior.ColorIndex = 3
End If
End If
LTestLoop = LTestLoop + 1
Wend
End If
LLoop = LLoop + 1
Wend
End Sub
A:
There are fuzzy lookup add-ins which can be hooked into Excel, as @Scott Craner mentions.
Download the Fuzzy Lookup plugin from Microsoft: https://www.microsoft.com/en-us/download/details.aspx?id=15011
Tutorial for setting up and using fuzzy lookups in Excel: http://www.k2e.com/tech-update/tips/431-tip-fuzzy-lookups-in-excel
Video tutorial showing how to use the tool: https://www.youtube.com/watch?v=3v-qxcjZbyo
There is some pretty complex matching algorithm stuff going on in the plugin, so it's not surprising that your script doesn't quite implement what you wanted perfectly with that much code. Good on you for trying though!
| {
"pile_set_name": "StackExchange"
} |
Q:
Validate Uniqueness Fields in Django Class Based View
I need to exclude the 'user' field in the form as 'user' is the loggedin user who will add the model. After reading through all Django forms documentation and referring to the answer here Django's ModelForm unique_together validation
My django views.py still reports error where 'user' is the loggined user
Request Method: POST
Request URL: http://localhost:8080/flavor/add_flavor/
Django Version: 1.8
Exception Type: KeyError
Exception Value: 'user'
Could anyone please point out the error in my code?
models.py
class Flavor(models.Model):
user = models.ForeignKey(UserProfile, related_name='flavors', verbose_name=_('user'))
# Attributes
name = models.CharField(max_length=100, verbose_name=_('name'), help_text=_('Enter the flavor name'))
date_created = models.DateField(_("date created"), default=datetime.date.today)
class Meta:
verbose_name = _('Flavor')
verbose_name_plural = _('Flavors')
ordering = ('name', 'user')
unique_together = ('user', 'name')
forms.py
class FlavorForm(forms.ModelForm):
class Meta:
model = Flavor
# Never use exclude keyword which involves Massive Assignment Risk
fields = ('name', 'date_created')
def __init__(self, *args, **kwargs):
# set the user as an attribute of the form which is more robust
# Always pop user from kwargs before calling super()
self.user = kwargs.pop('user')
super(FlavorForm, self).__init__(*args, **kwargs)
def clean(self):
'''
To verify the uniqueness by the unique_together fields
'''
cleaned_data = super(FlavorForm, self).clean()
if Flavor.objects.filter(name=cleaned_data.get('name',''), user=self.user).exists():
raise ValidationError(_('You have already added a flavor with this name'), code='invalid')
# Always return cleaned data
return cleaned_data
views.py
class FlavorCreateView(LoginRequiredMixin, CreateView):
model = Flavor
form_class = FlavorForm
template_name = 'flavor/add_flavor.html'
view_name = 'add_flavor'
success_url = reverse_lazy(view_name)
def get_form_kwargs(self):
'''
This injects form with keyword arguments.
'''
kwargs = super(FlavorCreateView, self).get_form_kwargs()
#Update the kwargs with the user_id
kwargs['user'] = self.request.user
return kwargs
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
# process cleaned data
return HttpResponseRedirect(success_url)
return render(request, self.template_name, {'form': form})
A:
You've carefully defined get_form_kwargs to provide the user kwarg. But then for some reason you've overridden post; your version instantiates the form directly, ignoring the helper methods.
There is rarely a reason to override post in CBVs, and certainly not in your case. Remove that whole method.
(Note, this has nothing to do with checking uniqueness.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Android notification not working as expected
I want to create notification WITH SOUND & VIBRATION that will appear every 3 days. I cannot make it happen
Tried almost every solution I found on the internet. You will see it from my code.
With my code, the sound is not working, vibration is not working, notification is showing more times in a row even when cancelled, it is not showing on the screen when locked even though I set priority to high. super weird
this is function that sets notification in MainActivity:
public void setNotification() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 45);
Intent myIntent = new Intent(this, NotifyService.class);
int ALARM1_ID = 10000;
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this, ALARM1_ID, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 3, pendingIntent);
}
this is BroadcastReceiver that triggers the notification:
public class NotifyService extends BroadcastReceiver {
@SuppressLint("ResourceAsColor")
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("my_channel_01ee",
"Channel human readable titlee",
NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{
0
});
channel.enableLights(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setLightColor(Color.GRAY);
channel.enableLights(true);
channel.setDescription("descrioptiom");
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(alarmSound, audioAttributes);
notificationManager.createNotificationChannel(channel);
}
Intent notificationIntent = new Intent(context, FoodInspectorActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(context, "my_channel_01ee");
int color = 0xfffffff;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notification.setSmallIcon(R.drawable.magnifier_final);
notification.setColor(color);
} else {
notification.setSmallIcon(R.drawable.magnifier_final);
}
notification.setContentTitle("FoodScan")
.setContentText("Scan some new products? Just click!")
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.launcher_icon))
.setSound(alarmSound)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS )
.setVibrate(new long[]{0, 500, 1000});
assert notificationManager != null;
notificationManager.notify(5, notification.build());
}
}
With this code, the sound is not working, vibration is not working, notification is showing more times in a row even when cancelled, it is not showing on the screen when locked even though I set priority to high. super weird
A:
Step 1: Create Method in your MainActivity and use AlarmManager to set alarm at specified time, and call the method in OnCreate
public void my(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,21);
calendar.set(Calendar.MINUTE,47);
if (calendar.getTime().compareTo(new Date()) < 0)
calendar.add(Calendar.DAY_OF_MONTH, 1);
Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
I'm setting my alarm every day at 09:47 PM
Step 2: Create BroadcastReceiver to listen when the alarm happens
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
notificationHelper.createNotification();
}
}
I'm creating this class named NotificationReceiver and extends BroadcastReceiver, in onReceive there is Class named NotificationHelper, don't confuse i will explain this Class for next steps.
Step 3: Create the Notification class
class NotificationHelper {
private Context mContext;
private static final String NOTIFICATION_CHANNEL_ID = "10001";
NotificationHelper(Context context) {
mContext = context;
}
void createNotification()
{
Intent intent = new Intent(mContext , NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("Title")
.setContentText("Content")
.setAutoCancel(false)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}
}
This class handles the notification
Step 4: Come back to Step 2: and call the Notification Class
NotificationHelper notificationHelper = new NotificationHelper(context);
notificationHelper.createNotification();
Finally go to your AndroidManifest.xml and register this
<receiver android:name=".NotificationReceiver"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding threads in C
I have a math function in C which computes lots of complicated math. The function has a header:
double doTheMath(struct example *e, const unsigned int a,
const unsigned int b, const unsigned int c)
{
/* ... lots of math */
}
I would like to call this function 100 times at the same time. I read about pthreads and think it could be a good solution for what I want to achieve. My idea is as follows:
pthread_t tid[100];
pthread_mutex_t lock;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}
for(i=0; i<100; i++) {
pthread_create(&(tid[i]), NULL, &doTheMath, NULL);
pthread_mutex_lock(&lock);
d += doTheMath(args);
pthread_mutex_unlock(&lock);
}
pthread_mutex_destroy(&lock);
My questions:
How to pass to the doTheMath all the arguments it needs?
Is there here really a point in using threads, will this even work as I want it to? I cant really understand it, when I lock my function call with the mutex, it won't let to call my function 100 times at the same time, right? So how can I do this?
EDIT:
So, summing up:
My function encrypts/decrypts some data using math - so I guess the order matters
When I do it like this:
pthread_t tid[100];
for(i=0; i<100; i++)
pthread_create(&(tid[i]), NULL, &doTheMath, NULL);
it will create my 100 threads (my machine is capable of running, for sure) and I dont need a mutex, so it will call my function 100 times at the same time?
How about cPU cores? When I do it like this, will all of my CPU cores be fully loaded?
Having just one, single function call will load only one core of my CPU, having 100 (or more) threads created and running and calling my function will load all my CPU cores - am I right here?
A:
Yes, you can do this with threads. Whether calling it 100 times actually speeds things up is a separate question, as once all your CPU cores are fully loaded, trying to run more things at once is likely to decrease speed rather than increase it as processor cache efficiency is lost. For CPU intensive tasks the optimum number of threads is likely to be the number of CPU cores (or a few more).
As to your specific questions:
Q1: When you use phtread_create the last parameter is void *arg, which is an opaque pointer passed to your thread. You would normally use that as a pointer to a struct containing the parameters you want to pass. This might also be used to return the calculated sum. Note that you will have to wrap do_the_maths in a suitable second function so its signature (return value and parameters) look like that expected by pthread_create.
Q2. See above for general warning re too many threads, but uses this a useful technique.
Specifically:
You do not want to use a mutex in the way you are doing. A mutex is only needed to protect parts of your code which are accessing common data (critical sections).
You both create a thread to call doTheMath, then also call doTheMath directly from the main thread. This is incorrect. You should instead merely create all the threads (in one loop), then run another loop to wait for each of the threads to complete, and sum the returned answers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento 2.1.1 Rest API Update price only
Trying to Change only the price of the products with PUT method.
HERE http://devdocs.magento.com/guides/m1x/api/rest/Resources/Products/products.html#RESTAPI-Resource-Products-HTTPMethod-PUT-products--id
is stated that this is possible! But When i make a call with only the price in the product array i get a response like
Array
(
[message] => Invalid product data: %1
[parameters] => Array
(
[0] => Invalid attribute set entity type
)
)
So i add attribute set adn then i get the response
Array
(
[message] => The value of attribute "name" must be set
)
On the magento link here http://devdocs.magento.com/guides/m1x/api/rest/Resources/Products/products.html#RESTAPI-Resource-Products-HTTPMethod-PUT-products--id
Says that this should be possible with no other params
Enter only those parameters which you want to update.
Any ideas why is this happening?
the call i am using
PUT /rest/V1/products/:sku
A:
You can use the following rest PUT call:
/rest/V1/products/{SKU}
Passing the following json:
{
"product": {
"price": 9.63,
"extension_attributes": {
"stock_item": {
"qty": 63
}
}
}
}
So you can update price and stock quantity with one single call. You can remove the extension_attributes value, if you only want to update the price.
EDIT
You will need a quotation mark for your price, like this below. I don't quite understand why because the price should be a double variable in the database.
{
"product":{
"price":"9.63",
"extension_attributes":{
"stock_item":{
"qty":63
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I find unique values for a specific key in a list of dictionaries?
I'm using Python 3.7. I have an array of dictionaries. All the dictionaries have the same keys, e.g.
a: 1
b: 2
c: 3
How do I find all the unique values for the key "a" for example? That is, if the array looked like
arr = [{"a": 1, "b": 5}, {"a": 1, "b": 3}, {"a": 2, "b": 1}]
I would want the result to be
(1, 2)
A:
You can use set() for this task:
arr = [{"a": 1, "b": 5}, {"a": 1, "b": 3}, {"a": 2, "b": 1}]
print( set(d['a'] for d in arr) )
Prints:
{1, 2}
Or in tuple form:
print( tuple(set(d['a'] for d in arr)) )
(1, 2)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add calculated columns to nested data frames (list columns) using purrr
I would like to perform calculations on a nested data frame (stored as a list-column), and add the calculated variable back to each dataframe using purrr functions. I'll use this result to join to other data, and keeping it compact helps me to organize and examine it better. I can do this in a couple of steps, but it seems like there may be a solution I haven't come across. If there is a solution out there, I haven't been able to find it easily.
Load libraries. example requires the following packages (available on CRAN):
library(dplyr)
library(purrr)
library(RcppRoll) # to calculate rolling mean
Example data with 3 subjects, and repeated measurements over time:
test <- data_frame(
id= rep(1:3, each=20),
time = rep(1:20, 3),
var1 = rnorm(60, mean=10, sd=3),
var2 = rnorm(60, mean=95, sd=5)
)
Store the data as nested dataframe:
t_nest <- test %>% nest(-id)
id data
<int> <list>
1 1 <tibble [20 x 3]>
2 2 <tibble [20 x 3]>
3 3 <tibble [20 x 3]>
Perform calculations. I will calculate multiple new variables based on the data, although a solution for just one could be expanded later. The result of each calculation will be a numeric vector, same length as the input (n=20):
t1 <- t_nest %>%
mutate(var1_rollmean4 = map(data, ~RcppRoll::roll_mean(.$var1, n=4, align="right", fill=NA)),
var2_delta4 = map(data, ~(.$var2 - lag(.$var2, 3))*0.095),
var3 = map2(var1_rollmean4, var2_delta4, ~.x -.y))
id data var1_rollmean4 var2_delta4 var3
<int> <list> <list> <list> <list>
1 1 <tibble [20 x 3]> <dbl [20]> <dbl [20]> <dbl [20]>
2 2 <tibble [20 x 3]> <dbl [20]> <dbl [20]> <dbl [20]>
3 3 <tibble [20 x 3]> <dbl [20]> <dbl [20]> <dbl [20]>
my solution is to unnest this data, and then nest again. There doesn't seem to be anything wrong with this, but seems like a better solution may exist.
t1 %>% unnest %>%
nest(-id)
id data
<int> <list>
1 1 <tibble [20 x 6]>
2 2 <tibble [20 x 6]>
3 3 <tibble [20 x 6]>
This other solution (from SO 42028710) is close, but not quite because it is a list rather than nested dataframes:
map_df(t_nest$data, ~ mutate(.x, var1calc = .$var1*100))
I've found quite a bit of helpful information using the purrr Cheatsheet but can't quite find the answer.
A:
You can wrap another mutate when mapping through the data column and add the columns in each nested tibble:
t11 <- t_nest %>%
mutate(data = map(data,
~ mutate(.x,
var1_rollmean4 = RcppRoll::roll_mean(var1, n=4, align="right", fill=NA),
var2_delta4 = (var2 - lag(var2, 3))*0.095,
var3 = var1_rollmean4 - var2_delta4
)
))
t11
# A tibble: 3 x 2
# id data
# <int> <list>
#1 1 <tibble [20 x 6]>
#2 2 <tibble [20 x 6]>
#3 3 <tibble [20 x 6]>
unnest-nest method, and then reorder the columns inside:
nest_unnest <- t1 %>%
unnest %>% nest(-id) %>%
mutate(data = map(data, ~ select(.x, time, var1, var2, var1_rollmean4, var2_delta4, var3)))
identical(nest_unnest, t11)
# [1] TRUE
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I restrict EditText to take emojis
I am developing an application where I want my edittext should take Name only. I have tried using android:inputType="textCapSentences" but it seems like its not working. My edittext is still taking the emojis.
So, Is there any way i can restrict any special character or emojis input in edit text in android.
If anyone have idea,Please reply.
Thanks in advance.
A:
you can use emoji filter as code below
mEditText.setFilters(new InputFilter[]{EMOJI_FILTER});
public static InputFilter EMOJI_FILTER = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int index = start; index < end; index++) {
int type = Character.getType(source.charAt(index));
if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
return "";
}
char c = source.charAt(index);
if (isCharAllowed(c))
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}
};
private static boolean isCharAllowed(char c) {
return Character.isLetterOrDigit(c) || Character.isSpaceChar(c);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to give space in text in pdf in iphone app
i have created a pdf in iphone app i want to give some space and then display text
like
Now text look like this
This is the first test
i want the above text should start from here like
This is the first test
so how to make this spce below is the code for text showing
CGRect renderingRectNext = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 70.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSizeNext.height);
[textToDrawTwo drawInRect:renderingRectNext
withFont:fontNext
lineBreakMode:UILineBreakModeWordWrap
alignment:UITextAlignmentLeft];
A:
Not quite sure I understand your question, from what I've gathered you want to skip lines in the rendered text. If you add \n to your string it will skip to the next line.
textToDrawTwo = @"\n\nThis is the first test";
The bove will produce a string with 2 skipped lines before the actual text.
Hope this helps.
EDIT: Additionally, If you wan't to recreate a tab like sentence, with spaces before the line of text you would do something like this.
textToDrawTwo = [NSString stringWithFormat:@" %@",textToDrawTwo];
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference among EditText android:numeric="decimal" and android:inputType="numberDecimal"
I was wondering, what is the difference among the 2?
<EditText
android:inputType="numberDecimal" />
<EditText
android:numeric="decimal" />
I realize both gives same behavior. They limit the user input to "0123456789."
So, is there any differences among the 2? Is there any preferable?
A:
All of these attributes are deprecated:
android:numeric
android:phoneNumber
android:inputMethod
android:capitalize
android:autoText
in favor of one attribute:
android:inputType
(Remember deprecated features will disappear someday in a future release, so it is always best to use the supported version.)
For whatever reason their deprecation is not marked in the TextView (or EditText) documentation... However they are properly annotated on the R.attr page and presumably you will see the warnings inside your IDE's XML compiler (at least in Android's Eclipse plug-in.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Origin and meaning of the American 1960s slang phrase, "bread is"
I am trying to answer a question from a library patron who remembers the entire phrase, "bread is" that she and her friends used in the 1960s. She accepts that "bread" was used for money or "dough," another slang word. However she remembers use of the entire phrase, "bread is."
A:
According to my uncle, who was a university student in the 1960s, "bread is" is a shortened form of the old proverb, "Bread is the staff of life."
According to the Facts On File Dictionary of Proverbs, this proverb was first recorded in 1638.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display multiple category posts on a page in wordpress
I want to display posts for multiple categories. I have created a MULTISELECT drop down of all categories using code below:
<form method="get" action="<?php bloginfo('home');?>" >
<select name="cat" multiple>
<option value=""><?php echo esc_attr(__('Please Select Your Choice')); ?></option>
<?php
$categories= get_categories('show_count=0&orderby=name&echo=0&hierarchical=true&depth=1&taxonomy=category&exclude=1');
foreach ($categories as $category) {
$option = "<option value=$category->term_id>";
$option .= ucfirst($category->cat_name);
$option .= '</option>';
echo $option;
}
?>
</select>
<input type="submit" id="searchsubmit" value="Search" name="submit"/>
</form>
Whenever i selects more than one category, I can see all cat ids in url like: http://abcd.com/?cat=7&cat=8&cat=9 But it displays only last category posts using archieve.php file. I want to display all selected category posts on the page.
Thanks in advance.
A:
<?php
$categoryids = array(3,6,8,19);
$args = array(
'numberposts' => 20,
'category__in' => $categoryids,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'photo',
'post_status' => 'publish' );
$posts_array = get_posts( $args );
?>
<!-- The carousel -->
<div class="scrolimageview">
<div class="prvdiv"><a href="javascript: void(0)" id="gallery-prev"><img src="<?php bloginfo( 'template_url' ); ?>/images/prev.png" width="40"/></a></div>
<div id="gallery-wrap">
<ul style="width: 2068px; left: -188px;" id="gallery">
<?php foreach ($posts_array as $postd): ?>
<?php
$customd = get_post_custom($postd->ID);
$attached_photo_filed = $customd["attached_photo"][0];
$attached_photod = str_replace($postd->ID . '_', $postd->ID . '_thumb_',$attached_photo_filed);
$imaged = $upload_dir['baseurl'] . '/photos/' . $attached_photod;
?>
<li><a href="<?php get_bloginfo('url')?>/photo-details?id=<?php echo $postd->ID; ?>"><img src="<?php echo $imaged; ?>" alt=""></a></li>
<?php endforeach; ?>
</ul>
</div>
<div class="prvdiv1" style="float:right"><a href="javascript: void(0)" id="gallery-next"><img src="<?php bloginfo( 'template_url' ); ?>/images/next.png"/></a></div>
</div>
This code is from one of my project running live. So it's 100% working, please let me know if you fall into any trouble with it.
A:
<?php
if(isset($_POST['submit']))
{
$categories = $_POST['category'];
print_r($categories);
}
?>
<form action="" method="post">
<select name="category[]" size="5" multiple="multiple">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
<option value="4">Yellow</option>
<option value="5">Orange</option>
<option value="6">Purple</option>
<option value="7">Megento</option>
<option value="8">Green</option>
<option value="9">White</option>
<option value="10">Black</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
Note use of [] in here -
| {
"pile_set_name": "StackExchange"
} |
Q:
I have a wrong gravatar
I've been having a fight with my login this days (my OpenID provider was broken), claimed my account with my email addres, had some problems, then finally logged in with my OpenID (when my provider came back) and now I have a gravatar that doesn't match the one registered with my email address, just a default...
What should I do?
A:
Looks like your profile is using the anonymous identicon. To switch to Gravatar, go to your profile's edit page and click "change picture".
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make a program auto-start every time I log in?
I frequently need to start several programs that I use every time I start my computer. How can I make it so that whenever I login the program is automatically launched?
A:
To make a program start with Ubuntu:
If you're using Unity, search
for the program Startup
Applications.
If you're using Ubuntu Classic,
it's under Start Menu >
Preferences > Startup Applications.
To make Ubuntu remember your running applications on shutdown:
Open a terminal, and run
gconf-editor.
Navigate to
/apps/gnome-session/options.
Enable the option:
auto_save_session.
(NOTE: this may slow system boot, and has not been throughly tested.)
A:
User defined sessions for applications to start after login
An alternative way to automatically start applications after login is to define a user defined session. This has the advantage to use different sessions for different task, each with different applications loaded.
For this purpose we create a custom.desktop file as root in /usr/share/xsessions with the following content (for GNOME/GDM):
[Desktop Entry]
Name=Marco's Crowded Session
Comment=Custom ~/.xsession script
Exec=/home/username/.xsession
X-Ubuntu-Gettext-Domain=gdm
Use any fancy name for your session and replace username by your name of course.
This will run the script .xsession in the HOME directory at login where we can put in any appplications we need to start after login.
The script needs to be named as defined in the .desktop file, that is ~/.xsession in the example given, needs to be made executable and may have a content similar to this:
#! /bin/bash
my-important-app [options] &
second-app [options] &
[...] # add other applications
gnome-session [options]
Options for gnome-session may be omitted to load the default session. Give e.g. --session=classic-gnome as option to run Classic GNOME Desktop in 11.04.
Next time we login we will have the choice to start a "Marco's Crowded Session" with all applications from the script running in addition to applications from the gnome-session (or any other desktop manager you chose to start here).
Starting other desktop managers
To start another installed desktop manager replace the last line from the ~/.xsession script with the following:
gnome-session --session=ubuntu for standard desktop (with Unity in 11.04).
gnome-session --session=classic-gnome for classic GNOME desktop.
startkde for KDE desktop manager.
startxfce4 for XFCE, or when running Xubuntu.
A:
12.04 (Unity)
We can add applications to the "Startup Applications" by opening the menu entry on the top panel right side:
14.04 (Unity) and later
We can search the Dash for "startup applications"
or we can run the startup preferences from a terminal with
gnome-session-properties
This will open a window where we can see all installed applications that will run on startup. Tick or untick the applications there or choose "Add" to add a new application:
If we know the command to run the application just enter it here in the "Command" line. We may also add an optional "Comment" here.
If we do not know the command we can choose to "Browse..." our file system for installed applications. Many default applications are found e.g. in /usr/share/application:
Select an application to add to autostart.
Command line or programmatical approach
Similar to what the GUI solution above does we can manually add a .desktop file to ~/.config/autostart. The content of this file may be as follows:
[Desktop Entry]
Type=Application
Exec=</path/to/binary or command to execute>
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=<Name_to_be_displayed>
Comment=<optional comment>
Note that in a vanilla installation the directory ~/.config/autostart may not yet exist. We need to create it before we can access it programmatically.
| {
"pile_set_name": "StackExchange"
} |
Q:
XslTransform class is deprecated after .NET conversion
I had XslTransform in an old program, and after converting the code the the .NET F 3.5, the compiler said that XslTransform is deprecated and replaced by XslCompiledTransform.
This is the old code :
XslTransform xslt = new XslTransform();
xslt.Load(xslTemplate);
xslt.Transform(xPathNav, null, fileStream, null);
I've changed the code to look like this :
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xslTemplate);
xslt.Transform(xPathNav, fileStream);
And now I get :
cannot convert from
'System.IO.FileStream' to
'System.Xml.XmlWriter'
I tried to correct that by adding doing this :
XPathDocument doc = new XPathDocument(fileStream);
XmlWriter writer = XmlWriter.Create(Console.Out, xslt.OutputSettings);
xslt.Transform(doc, writer);
I don't get errors anymore, but I the code is not doing XML transformation.
Any ideas ?
Thanks.
A:
I think
XslTransform xslt = new XslTransform();
xslt.Load(xslTemplate);
xslt.Transform(xPathNav, null, fileStream, null);
can be written as follows with XslCompiledTransform
XslTransform xslt = new XslCompiledTransform();
xslt.Load(xslTemplate);
xslt.Transform(xPathNav, null, fileStream);
| {
"pile_set_name": "StackExchange"
} |
Q:
What is webdev.webservice process?
I have an asp.net page which calls a webservice. I wanted to check the webservice request and response strings by using fiddler - HTTP Debugging Proxy tool.
When I see the sessions there is a process called: "webdev.webservice:2148"
What is webdev.websrvice?
A:
webdev.webserver.exe is the local webserver that's launched by Visual Studio when you're debugging or running a website locally. 2148 will be the port that the webserver is running on. If you want to debug the web service you can attach to that process, set your breakpoints and then run the code.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the proof that a hash output contains random binary numbers
I have heard quotes by many that a SHA-512 hash output is random.
Does anyone know what method was used to come to this conclusion? If it is not randomized, how could that be shown?
A:
Whilst the random oracle model(1) is the theoretical construct that should produce random 'looking' hash output, the scientific principle also requires that we test the hypothesis for proof.
So let us assume a simple set of inputs to the function. If the null hypothesis is that the output will appear random(2), the output will have certain testable properties:-
For a simple counter input, we expect that any output bit will all uniformly distributed with $P(X = 0, X = 1) = \frac{1}{2}$, and for multiple conditional bits, $P(X | Y) = \frac{1}{2}$. These formulae extend as $P(\dots)= \frac{1}{2^n}$ and $P(\dots|\dots)= \frac{1}{2^n}$ for $n$ bit tuples.
For randomly entered bits, we can count the numbers of set input and output bits and determine whether an avalanche effect is occurring. We expect that 50% of the bits will change per any random input. The actual probability mass function of the changes is expected to be Binomial, tending to a Normal probability distribution as the block width $(n)$ increases. We'd expect $\mu = 0.5n, \sigma = 0.5 \sqrt{n}$.
Standardised randomness testing (Diehard, NIST etc.) can also be used, and we expect SHA-512 to pass all of them whilst hashing simple inputs. There is also no specialised distinguisher and can separate the hash output from a pseudo random sequence (3).
This 'random' hypothesis has so far held in the laboratory. So in your parlance, the output is random, and no one has yet proved otherwise. Some of these experiments might have shown it up otherwise, depending on the degree of bias.
Notes.
(1) A very imperfect model, as explained here.
(2) By random output, I take it you mean independent and identically distributed bits, not easily related to the input, or each other.
(3) Just be aware that these lab tests cannot determine any form of security measure.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get a list of all pending security updates?
I need to list (not count or install) all pending security updates on an Ubuntu 14.04 system. I've read the post How to create a list of of only security updates with apt-get? and its accepted answer (apt-show-versions | grep upgradeable | grep security) does indeed give me a list.
However, that command lists 62 pending security updates. /usr/lib/update-notifier/apt-check tells me that I have 75 pending security updates, but doesn't seem to have a way to list them. How can I reconcile these two numbers? Is one of the two commands doing something other than what I want?
A:
If you are just looking to do this quickly once, instead of creating a separate repository and scripting up some automation and all that. Great if you aren't supposed to be making changes while auditing a system or whatever.
These two commands will spit out the list. Pipe to wc -l to see how many are behind. ;-)
grep security /etc/apt/sources.list > /tmp/security.list
sudo apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -oDir::Etc::SourceParts=/some/valid/dir/false -s
Still valid for older distros or if you have update repos off, but security on:
sudo apt-get upgrade -s| grep ^Inst |grep Security
A:
+---------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Command | Purpose |
+---------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| apt list --upgradable | List all updates available |
| apt list --upgradable | grep "\-security" | List all updates that are security. |
| apt list --upgradable 2>/dev/null | grep "\-security" | wc -l | Count number of security updates available. and redirects the stderr like "WARNING: apt does not have a stable CLI interface. Use with caution in scripts." to null |
+---------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| {
"pile_set_name": "StackExchange"
} |
Q:
how to assign json array of values to an array in angular
i have a json array of values ,
array1 = [{"type":"cc"},{"type":"vv"},{"type":3},{"type":4},{"type":5}];
i have another array array 2, i need to fill the second array by checking the condition ,that the value with the type =vv ,want to be the first element in the second array.
i use the format,
array1.forEach((pp)=>{
if(pp.type == 'cc'){
array2[1] = pp;
}
else if(pp.type == 'vv' ){
array2[0] = pp;
}
else if(pp.type == '4' ){
array2[3] = pp;
}
else if(pp.type == '3' ){
array2[2] = pp;
}
else if(pp.type == '5' ){
array2[4] = pp;
}
})
but after execution i got empty array as the result.
A:
Here is a very concise solution using Array.sort(), and this doesn't constrain having 2 elements only of course:
array1.sort((a,b) => a.type === 'vv'? -1: 1);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to format a date in PHP
I have a database with a table, and it has a field with datetime type. When I collect data from that field and show it in PHP, it shows "Oct 9 2012 2:06PM". I want to convert its format to "10/09/2012 14:06:00". Please note that before I convert it, it doesn't have "second" and I want it have "00" seconds after conversion.
How can I format this date in PHP?
A:
You should familiarize yourself with PHP's date() function.
A similar date format could be created with:
$formatted = date('m/d/Y H:i:s', strtotime($dateFromDb));
The strtotime() call on the date from the database will be required first in-order to convert the date into a Unix timestamp which can then be passed to the date() function (for formatting).
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - rolling functions for GroupBy object
I have a time series object grouped of the type <pandas.core.groupby.SeriesGroupBy object at 0x03F1A9F0>. grouped.sum() gives the desired result but I cannot get rolling_sum to work with the groupby object. Is there any way to apply rolling functions to groupby objects? For example:
x = range(0, 6)
id = ['a', 'a', 'a', 'b', 'b', 'b']
df = DataFrame(zip(id, x), columns = ['id', 'x'])
df.groupby('id').sum()
id x
a 3
b 12
However, I would like to have something like:
id x
0 a 0
1 a 1
2 a 3
3 b 3
4 b 7
5 b 12
A:
For the Googlers who come upon this old question:
Regarding @kekert's comment on @Garrett's answer to use the new
df.groupby('id')['x'].rolling(2).mean()
rather than the now-deprecated
df.groupby('id')['x'].apply(pd.rolling_mean, 2, min_periods=1)
curiously, it seems that the new .rolling().mean() approach returns a multi-indexed series, indexed by the group_by column first and then the index. Whereas, the old approach would simply return a series indexed singularly by the original df index, which perhaps makes less sense, but made it very convenient for adding that series as a new column into the original dataframe.
So I think I've figured out a solution that uses the new rolling() method and still works the same:
df.groupby('id')['x'].rolling(2).mean().reset_index(0,drop=True)
which should give you the series
0 0.0
1 0.5
2 1.5
3 3.0
4 3.5
5 4.5
which you can add as a column:
df['x'] = df.groupby('id')['x'].rolling(2).mean().reset_index(0,drop=True)
A:
Note: as identified by @kekert, the following pandas pattern has been deprecated. See current solutions in the answers below.
In [16]: df.groupby('id')['x'].apply(pd.rolling_mean, 2, min_periods=1)
Out[16]:
0 0.0
1 0.5
2 1.5
3 3.0
4 3.5
5 4.5
In [17]: df.groupby('id')['x'].cumsum()
Out[17]:
0 0
1 1
2 3
3 3
4 7
5 12
A:
Here is another way that generalizes well and uses pandas' expanding method.
It is very efficient and also works perfectly for rolling window calculations with fixed windows, such as for time series.
# Import pandas library
import pandas as pd
# Prepare columns
x = range(0, 6)
id = ['a', 'a', 'a', 'b', 'b', 'b']
# Create dataframe from columns above
df = pd.DataFrame({'id':id, 'x':x})
# Calculate rolling sum with infinite window size (i.e. all rows in group) using "expanding"
df['rolling_sum'] = df.groupby('id')['x'].transform(lambda x: x.expanding().sum())
# Output as desired by original poster
print(df)
id x rolling_sum
0 a 0 0
1 a 1 1
2 a 2 3
3 b 3 3
4 b 4 7
5 b 5 12
| {
"pile_set_name": "StackExchange"
} |
Q:
Can an observer on Earth only see half of the sky?
Is this the following statement true?
An observer on earth only may see half of sky from the northern or southern hemisphere, and even if the observer stands on the equator on top of a very high mountain, he will hardly be able to see all the stars in the sky in given period!
Do most globe-like objects in space have this property?
I'd appreciate any more remarks on the subject.
A:
At any given instant of time, in any place on Earth, if the sky is clear and the horizon is low and flat, you see half of the celestial sphere - at that very instant.
But as the Earth keeps turning, you may end up seeing more, depending on where you are.
If you're at the North or South Pole, you see exactly half of the sky no matter how long you wait. That's all you'll ever see from there.
If you move closer to the Equator, you'll end up seeing more than half, if you're willing to wait.
At the Equator, you see pretty much all the sky, if you wait as the Earth keeps spinning around, revealing all the sky to you eventually.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a Raining Effect(Particles) on Android?
I am developing a 2d android strategy game, it runs on SurfaceView, so I can't(or can I?) use LibGdx's particle system. And I would like to make a raining effect, I am aiming for something like this( http://ridingwiththeriver.files.wordpress.com/2010/09/rain-fall-animation.gif ), I don't need the splash effect in the end (although that would be superb, but probably would take up a lot of system resources).
How could I achieve that raining effect? Any ideas?
Thank You a lot in advance!
A:
Conserve your precious CPU/GPU cycles! You can inexpensively approximate rain (and rain splats) without using particles. The rain drops and splats don't even have to move or be aligned! Basically, randomly draw a bunch of the following sprites onto the screen:
Source: bulletproofoutlaws.com (There's also a video of the final effect)
A:
I made a rain shader for 3D without using any particles at all (Video) but instead using three layers of the same texture scrolling by at different speeds at different scales as described in the article Rendering Falling Rain and Snow.
For 2D you obviously would not want a double cone to project your rain textures on but can use a plane instead. You can however use the effects with twisting a little (I think, haven't tested it) to create a feeling for velocity left or right. For back or forward you could just scale a little along the y-axis.
| {
"pile_set_name": "StackExchange"
} |
Q:
a simple multivariable limit
$\lim_{(x,y)\to(0,0)}\frac{-x}{\sqrt{x^2+y^2}}$
I get confused finding this limit.
I approach with lines $y=mx$ and i get $\lim_{x\to 0}\frac{-x}{\sqrt{x^2+m^2x^2}}$. How can i ended that this limit does not exists.
A:
The limit does not exist, as your approach illustrated. Notice that
$$\lim_{x\to 0^+}\frac{-x}{\sqrt{x^2+m^2x^2}}=\lim_{x\to 0^+}\frac{1}{\sqrt{1+m^2}}=\frac{1}{\sqrt{1+m^2}},$$
whose value clearly depends on $m$. That is, the limit depends on how you tend to $(0,0)$, and hence by definition the limit does not exit.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to speed up the code computing 'per-pixel' contrast over an image (local contrast)?
I wrote a Matlab function to compute the per-pixel contrast (i.e., the difference between the center pixel of a window (3x3) and the mean of all the pixels in the window, and the difference over the standard deviation of all the pixels in the window).
The code runs very slow for an 1024x1024 gray scale image. Is there any method to speed up the code? Thanks!
function [ imContrast ] = LocalContrast( im )
% [ imContrast ] = LocalContrast( im )
% Compute the contrast between a center contrast and its neighbors.
%
% Equation: window_size = 3x3
% x_contrast = (x_center - mu) / std(pixels_in_window)
% mu: mean of the pixels' gray values in the window
%
% Input:
% im - original image in gray scale
%
% Output:
% imContrast - feature matrix of contrast, same size of im
[rows, cols] = size(im);
imContrast = double(zeros(size(im)));
% Boundary - keep the gray values of those in im
imContrast(1,:) = im(1,:) / 255;
imContrast(rows,:) = im(rows,:) / 255;
imContrast(:,1) = im(:,1) / 255;
imContrast(:,cols) = im(:,cols) / 255;
% Compute contrast for each pixel
for x = 2:(rows-1)
for y = 2:(cols-1)
winPixels = [ im(x-1,y-1), im(x-1,y), im(x-1,y+1),...
im(x,y-1), im(x,y), im(x,y+1),...
im(x+1,y-1), im(x+1,y), im(x+1,y+1)];
winPixels = double(winPixels);
mu = mean(winPixels);
stdWin = std(winPixels);
imContrast(x,y) = (double(im(x,y)) - mu) / stdWin;
end
end
end
A:
Here's a way around it that uses the image processing toolbox. Given your image is called im ,
the mean difference (MD):
MD = im - imfilter(im,fspecial('average',[3 3]),'same');
the standard deviation difference (SDD):
SDD = im - stdfilt(im, ones(3));
| {
"pile_set_name": "StackExchange"
} |
Q:
Page referencing itself in HTML iframe
I have a webpage (which I will refer to as foo.php) that has an iframe in it that should contain another page (bar.php). However, it instead of sourcing bar.php, it sources foo.php/bar.php. This creates another foo.php page that contains an iframe that contains another foo.php page that contains an iframe... you get the picture. Weirdly enough, I have other pages with iframes that are working just fine. This is the code:
<iframe style="width: 100%; height: 50px;" src="bar.php"></iframe>
What's going on?
A:
I figured it out; the page that linked to foo.php did so with the address "foo.php/". Removing the slash fixed the problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is Newton’s gravitation law able to explain the circular motion of the earth around the sun?
I have read in Forbes website that the orbit of the earth around the sun is expanding (by 1.5 cm in 2019).
I have also heard that big bang theory suggests that the universe would collapse into itself under gravitational force, unless it was expanding.
Is Newton gravitation model able to explain why the orbit of the earth around the sun does not follow an inward spiral path which eventually falls into the sun?
Does it mean that we require the big bang theory (an expanding universe) to explain why the earth orbit does not follow an inward spiral path?
A:
Newton's theory does imply that the earth will fall into the sun - if it never had any tangential velocity with regards to the sun. As it obviously does have such velocity, it follows an elliptical path, as described by Newton's laws.
As to why the earth does not follow a spiral path into the sun, that would indeed happen on condition that a) there is something to slow it down, e.g. interplanetary dust and b) there are no other planets or moons. The effect of Jupiter and other planets is by far the greater of the two effects.
Once you add other planets, a planet's orbit is chaotic: it's (very) long term motion is impossible to predict unless you know the starting position and velocity with impossible precision. Over the long term (many billions of years) the effect of Jupiter may be to fling us out of the solar system, to crash us into the sun, or any of many other possible scenarios.
While Newton's laws (as corrected by Einstein) may be exactly correct - the future will tell - we still cannot compute the earth's long term path. In fact, calculating the orbits of 3 or more bodies is not possible except in special cases. In general cases we can only use computers to approximate the result, as our current maths do not give us an exact solution.
As for the Big Bang, it only affects the overall expansion of the universe. It has no effect on the movement of stars and planets. It does not make the Milky Way expand and in fact, the Andromeda galaxy is travelling towards the Milky Way instead of away from it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set a Date in apex test class?
I have written a test class in which I just want to set one date field. How can I achieve this? I am not able to set the value using the following code:
Account acc=new Account();
acc.effectiveDate__c= '09.12.2016';
A:
You can do this using Apex' Date class:
acc.effectiveDate__c = Date.newInstance(2016, 12, 9);
For more information check out the documentation: Apex Developer Guide - Date Class
A:
Another option is using system.today() (or system.now() if it's datetime field):
acc.effectiveDate__c = System.today() + 5;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass value from cshtml file to the JS
Hello I need to pass one param to the my JS function after pressing button.
Here is my button:
<button type="button" class="btn btn-default" id="UserClick" onclick="foo(@HttpContext.Current.User.Identity.Name)">Click here to add me as a user</button>
as You can see I try to send @HttpContext.Current.User.Identity.Name to the function foo.
Here my Foo function:
function foo(value) {
alert(value);
};
I tried sollutions from those topics:
One
Two
But all I get get is this error:
Uncaught SyntaxError: Unexpected token ILLEGAL
How to bypass this?
@update
All files included:
<script src="/Scripts/CreateDevice.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/jquery-1.10.2.js"></script>
full JS file:
$(document).ready(function () {
function foo(value) {
alert(value);
};
})
I can access to the js file from page-source.
A:
First of all change you sequence of file to
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/CreateDevice.js"></script>
Declare your function outside document-ready handler. Like
$(document).ready(function () {
});
function foo(value) {
alert(value);
};
Pass your parameter in quotes
onclick="foo('@HttpContext.Current.User.Identity.Name');"
Additionally, You can bind event using .on() and pass parameter using attributes
JS
$(document).ready(function () {
//Bind Event
$(document).on('click', '#UserClick', function(){
alert($(this).data('user-name'))
});
});
HTML
<button type="button"
class="btn btn-default"
id="UserClick"
data-user-name="@HttpContext.Current.User.Identity.Name"
>Click here to add me as a user</button>
| {
"pile_set_name": "StackExchange"
} |
Q:
SRD-05VDC-SL-C 5V DC relay not working with XY-DJM-5V
I'm just a beginner and need some assistance. below is a diagram of a 4CH reciever which works fine with some leds and it reports 5V positive on Data0 when holding channel 0 on the transmitter. What's not working is when attempting to use a 5V DC relay as shown in diagram, the relay clicks and seems to work fine with a direct input.
I'm using USB Powered socket which is 5V DC 0.5A I believe. I'm really puzzled while its not working.
SUGGESTED
simulate this circuit – Schematic created using CircuitLab
A:
The relay draws more current than that module can supply. If you keep doing such tests you may damage the receiver!
If you read the SC2272-M4 datasheet, you'll see it can supply a maximum current of 3 mA. That relay needs 89 mA at a 55 ohms coil resistance. So the load current is 5 / 55 = 0.09 A = 90 mA. Now, the minimum hFE of the transistor should be (0.09 / 0.003) x 5 = 150. The resistor between receiver and transistor base should be 0.2 x 55 x 150 = 1650 ohms. Choose 1.8 k. Calculations made on http://pcbheaven.com/wikipages/Transistor_Circuits/
Due to the very low available current from receiver output pin, a high hFE transistor is required. 2N2222 should work (its maximum hFE is 300).
Use a (transistor) driver. Something like:
| {
"pile_set_name": "StackExchange"
} |
Q:
Retargetting solution has no effect
I have installed the latest Windows 10 SDK from here:
https://developer.microsoft.com/de-de/windows/downloads/windows-10-sdk
When I try to rebuild my solution, I get the error "MSB8036 The Windows SDK version 10.0.10069.0 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or by right-clicking the solution and selecting "Retarget solution".
That is what I did:
The IDE tells me: "Retargeting End: 2 completed, 0 failed, 0 skipped".
However, when I then try to rebuild the solution, I'm getting the same error again.
Does anybody have any hint how to solve this problem?
A:
Hmmm, I switched the "Platform Toolset" in the voice project from "Visual Studio 2015 (v140)" to "Visual Studio 2015 - Windows XP (v140_xp)" (which I wanted anyway), and now it works.
I guess that doesn't solve the problem for anybody who has the same problem, but in my case it solved the problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cómo diseño un algoritmo que contenga un subprograma de cálculo del factorial de un número y una llamada al mismo
entero función factorial(E entero:n)
var
entero: i,f
//advertencia, segun el resultado, f puede ser real
inicio
f ← 1
desde i ← 1 hasta n hacer
f ← f * i fin_desde
devolver (f)
fin_función
y el algoritmo que contiene un subprograma de cálculo del factorial de un número y una llamada al mismo:
algoritmo función_factorial
var entero: x, y, numero
inicio
escribir ('Deme un numero entero y positivo')
leer(numero)
x ← factorial(numero)
y ← factorial(5) escribir(x, y)
fin
A:
Lo que andas buscando es un algoritmo recursivo. Estos algoritmos, requieren una condición de salida, para no dejar pegado el computador. El algoritmo debiera ser algo así:
factorial (entero n):
si entero n==0
retornar 1
si no
retornar n*factorial(n-1)
| {
"pile_set_name": "StackExchange"
} |
Q:
How is sinning judged after accepting Christ?
How is sinning judged after accepting Christ?
Are there classifications?
Are we clear of every sin?
What about repetitive sin of the same type?
(All assumed after accepting Christ.)
A:
Generally speaking, a sin is a sin, is a sin, whether or not the individual is a believer. The difference is that believers are forgiven and are accepted by God because they have Christ's righteousness "imputed" to them by faith. (See "Sola Fide," "Salvation by Grace through Faith").
Romans 3:23 is one text often offered as proof that, from a biblical perspective, all people are guilty of sin. Many denominations also teach that Christians necessarily continue to sin, even after they are saved (see Mat 5:21-30). (A notable exception to this is found in the Methodist doctrines of "Christian Perfection," taught by the Wesley brothers in the eighteenth century). Romans 7:13-25 is another text often offered as proof that believers continue to sin -- it is frequently interpreted as teaching that Paul recognized sin in himself, post-conversion. See also Romans 6.
The basic notion of forgiveness in Christianity is that all human beings are guilty of sin, and there is no way that we can earn our way into heaven by doing good deeds; once we've committed one sin, we're as guilty as if we had broken every law in the book (see James 2:10). In order to glorify himself, God has chosen to have mercy on some sinners and save them, but since he is perfectly just, someone had to be punished for the sins that had been committed by the people he chose to save, and that person could only be one that had not first incurred his own debt of sin. So, God punished sinless Christ, and -- without getting into doctrines like election, free will, universalism, monergism vs synergism, etc. -- he applied that atonement to believers, who are then seen "in Christ" as sinless and so are accepted by God.
One common point of confusion is the notion that "all sins are equal." There is a wide consensus that such is not the case, though there are those who will argue the point. A simple Google search on "are all sins equal" will return a wealth of results, so I won't elaborate further here, except to clarify the basic idea. (BTW, remember to consult only credible, verifiable sources, whichever perspective they advocate). While some sins are, in God's sight, worse than others, as soon as a person has committed one sin of any sort, they have become "unclean," and are permanently barred from heaven. God takes sin so seriously that all sin must be punished, and the punishment associated with any one sin is such that it could only be paid by Christ. That being said, it is possible for one person to incur a greater "sin debt" compared with another, but in any case, all sin is forgiven when one receives Christ. (Note that there is reference in the NT to something called the "unforgivable sin," which is a weighty and contentious doctrinal issue in and of itself).
See the Westminster Larger Catechism, questions 150 - 153.
Some denominations teach that a saved person can "backslide" and become involved in sin, and that such a person needs to be "restored." Other denominations teach that the presence of "significant," or ongoing, repetitive sin in one's life is a potential indication that one was not truly saved in the first place, since regeneration places the love of God in one's heart, and sin both angers & grieves God. Some teach that once a person is truly saved, he can never become "unsaved" (see "Perseverance of the Saints," "T.U.L.I.P."); others believe that it is possible for a person to "fall away" and "be restored" many times.
It is also commonly taught that the rewards that individual believers receive in heaven will be commensurate with the righteousness of the life they lived on earth. The most commonly referenced reward that I have heard about relates to the "number of cities" that one will rule over in heaven. Some also teach that there are varying degrees of punishment in hell. Some examples of passages that are offered by those who support such teachings are the parables at Luke 19:11-27 and Luke 12:47-48.
Addendum: I thought about this topic some more, and it brought to mind something called the "Lordship Salvation Controversy." It's been some time since I looked into this area of soteriology, but one thing that hasn't changed in the intervening years is the caustic nature of most of the internet discussions on the topic. (Btw, for times like these, it can be useful to bear in mind Paul's exhortation to Timothy in 2 Timothy 2:22-26).
"Lordship salvation" refers to one doctrine that claims to describe specifically what God requires of his followers. The alternative doctrine is sometimes called "Non-Lordship Salvation," or, disparagingly, "easy believism." I don't feel qualified to attempt a concise summary of the issues, but here are some links that I've tried to vet for you. I encourage you to use caution in consulting the links that result from a "lordship salvation" internet search, as many of them seem to be filled with invective.
Some useful links:
I'm very familiar with the ministries of John Piper (Desiring God) and RC Sproul (Ligonier) . Both are well educated, compassionate men, with strong understandings of Reformed theology.
John Piper from Desiring God Ministries on Lordship Salvation. (Long list of scripture proofs).
Articles tagged "Lordship Salvation" in the Resources section of Ligonier Ministries' site.
Devotionals tagged "Lordship Salvation" in the Resources section of Ligonier Ministries' site.
More content from Ligonier.
Here's a site called "Monergism." Monergism is actually the name of a doctrine, and the site staunchly advocates in favor of their viewpoint, but does so in an intelligent way. In reviewing their extensive list of links on Lordship Salvation I recognized some credible names with historic significance.
Resources at Monergism.com.
I'm not particularly familiar with Theopedia. A quick look over their pages on Lordship Salvation and Non-Lordship Salvation throws up no immediate red flags. It looks like they link almost exclusively to contemporary teachers for their references, at least for this topic.
Theopedia entry for "Lordship Salvation."
Theopedia entry for "Non-Lordship Salvation."
And here's a link to a discussion from a few months ago (early 2012) that includes what looks like some intelligent comments on the issue:
PuritanBoard.com discussion on Lordship Salvation, Feb 2012.
Hope this doesn't seem overwhelming. There's probably enough resources in this post to get started on a dissertation! The teachings of RC Sproul and John Piper are normally very accessible, and a great place to start if you're new to a topic and like a Reformed perspective. Cheers.
A:
Salvation
"Accepting Christ" is not the end of the "salvation story", and does not protect a person from judgment. (I'll cover this more in my blog post later this month.)
After our conversion experience, there is an expectation that we will follow Jesus' example and follow God in loving communion and partnership with Him. This is what we were made for, this is what was broken when man departed from God's ways in the Garden, and this is what God has been calling us back into since that time.
Protection from Judgment
If a person is a follower of Christ, he is protected from God's judgment. This protection covers all sins "equally"; every sin, even repetitive sins. The blood of Jesus is powerful!
However, if a person chooses not to follow God, they will be judged. This includes people who have "accepted Christ" but later decide they don't want to follow Him anymore. If a person is in this state, it's almost irrelevant what sins have been committed, because they all end up resulting in eternal torment due to the biggest sin of all: rejecting God.
The Spirit is Willing, But the Flesh is Weak
Now, the big question for a lot of Christians is: "What if I stumble? What if I make a mistake? What if I am caught in a sinful habit that I have been unable to break free of?" This can be a heavy weight to bear. This can leave a Christian feeling like a disappointment to God; a man so weak in faith he is unable to "tap into" God's freeing power.
Let me assure you, you are not alone! Every follower of Christ experiences this feeling at some point. Why? Because we love God and want to follow Him! The struggle comes from our inability to live a perfect life as we would like.
If your deepest desire is to follow God in love, worry not. You are doing good. Your sins are forgiven by the blood of Jesus. Yes, even that one! Press on, repent, and do what God has desired all along: try.
| {
"pile_set_name": "StackExchange"
} |
Q:
Drupal autocomplete fails to pull out data as a subdomain
I managed to pull out data using autocomplete at my local (http://mysite.dev/swan/autocomplete). The json data is displayed.
But when I applied the same module at live (now a subdomain: http://test.mysite.com/swan/autocomplete with different drupal installs), this autocomplete fails to pull out data. No json data is displayed.
Do you have any idea if this is related to cross domain issue, or any possible cause I might not be aware of?
This is the callback:
/**
* Callback to allow autocomplete of organisation profile text fields.
*/
function swan_autocomplete($string) {
$matches = array();
$result = db_query("SELECT nid, title FROM {node} WHERE status = 1 AND type='organisation' AND title LIKE LOWER ('%s%%')", $string, 0, 40);
while ($obj = db_fetch_object($result)) {
$title = check_plain($obj->title);
//$matches[$obj->nid] = $title;
$matches[$title] = $title;
}
//drupal_json($matches); // fails at safari for first timers
print drupal_to_js($matches);
exit();
}
Any hint would be very much appreciated.
Thanks
A:
It's the conflict with password_policy.module. Other similar modules just do the same blocking. These modules stop any autocomplete query.
| {
"pile_set_name": "StackExchange"
} |
Q:
d3 opposing charts axis alignment issue
I have a chart which currently looks like
The bottom axis is supposed to look like the top, being placed right below the tip of the highest chart. I have tried to .orient the bottom axis to both "top" and "bottom" to little avail. Any ideas?
var width = 960,
fullHeight = 850,
height = 350;
var y = d3.scale.linear()
.domain([0, d3.max(data)])
.range([height, 0]);
var axisScale = d3.scale.ordinal()
.domain(data)
.rangeBands([0, width]);
var axisScale2 = d3.scale.ordinal()
.domain(data2)
.rangeBands([0, width]);
// .range([0, 960]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", fullHeight);
var chart1 = chart.append("g")
.attr("class", "chart-one")
.attr("height", height)
.attr("width", width);
var chart2 = chart.append("g")
.attr("class", "chart-two")
.attr("transform", function() { return "translate(0," + (height + 70) + ")"; })
.attr("height", height)
.attr("width", width);
var barWidth = width / data.length;
var bar = d3.select(".chart-one")
.selectAll("g")
.data(data)
.enter().append("g")
.attr("class", "one")
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });
bar.append("rect")
.attr("y", function(d) { console.log(d, y(d)); return y(d) + 60; })
.attr("height", function(d) { return height - y(d); })
.attr("width", barWidth - 1);
var bar2 = d3.select(".chart-two")
.selectAll("g")
.data(data2)
.enter().append("g")
.attr("class", "two")
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });
bar2.append("rect")
.attr("height", function(d) { return height - y(d) })
.attr("width", barWidth - 1);
var xAxis = d3.svg.axis()
.scale(axisScale)
.tickValues(data);
// .tickPadding([-10]);
// .orient("top");
var xAxis2 = d3.svg.axis()
.scale(axisScale2)
.tickValues(data2)
.tickPadding([15]);
var xAxis3 = d3.svg.axis()
.scale(axisScale)
.tickValues(data)
.tickPadding(27);
var xBotAxis = d3.svg.axis()
.scale(axisScale)
.orient("top")
.tickValues(data);
d3.select(".chart-one").append("g").attr("class", "axis").call(xAxis);
d3.select(".chart-one").append("g").attr("class", "axis").call(xAxis2);
d3.select(".chart-one").append("g").attr("class", "axis").call(xAxis3);
d3.select(".chart-two").append("g").attr("class", "axis").call(xBotAxis);
A:
The orientation of the axis only affects where the labels are with respect to the line, not the overall position. If you want it to appear at the bottom, you need to move the element it's appended to there, i.e.
d3.select(".chart-two").append("g")
.attr("transform", "translate(0," + (height-10) + ")")
.attr("class", "axis")
.call(xBotAxis);
You may want to tweak the offset from the total height (10 above) and/or the height of the chart and bars to your liking.
| {
"pile_set_name": "StackExchange"
} |
Q:
Eventos de datetimepicker de jquery
estoy usando datetimepicker de jquery, me gustaria poder ejecutar una función al cambiar la fecha, si lo hago al cambiar el div, cuando este pierde el foco, me dispara también la funcion. Necesito que ejecute la funcion solo cuando cambie la fecha y no al perder el foco.
$(document).ready(function(){
datepicker();
})
function datepicker() {
$(".datepicker").datetimepicker({
format: "d-m-Y",
language: 'es',
timepicker: false,
});
$.datetimepicker.setLocale('es');
}
$("#idCalendario").on( "change", function() {
alert();
});
<input type="text" id="idCalendario" value="" class="form-control datepicker input-sm " >
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="idCalendario" value="" class="form-control datepicker input-sm " >
A:
Para responder a tu pregunta, vamos a hacer una pequeña investigación basada en tu código.
Paso 1: Leer la API
Para ello vamos a https://xdsoft.net/jqplugins/datetimepicker/. La verdad es que la documentación es mejorable, pero encontramos una serie de eventos interesantes:
onChangeDateTime: Evento desencadenado cuando la fecha del control es modificada.
onClose: Evento desencadenado al ocultar el calendario del control.
onShow: Evento desencadenado al mostrar el mensaje del control.
Paso 2: Probar la API en tiempo de ejecución
Ahora construimos un pequeño ejemplo e investigamos qué ocurre al seleccionar una fecha:
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script>
<script>
$(document).ready(function() {
$('#idCalendario').datetimepicker({
onChangeDateTime: function(ct, $input) {
console.log('onChange: ' + $input.val());
},
onClose: function(ct, $input) {
console.log('close.');
},
onShow: function(ct, $input) {
console.log('show.');
},
});
});
</script>
<input type="text" id="idCalendario" value="" class="form-control datepicker input-sm " >
Paso 3: Establecer una solución
Una sorpresa desagradable es que se desencadena varias veces el evento onChangeDateTime. Sin embargo, solo te interesa controlar el evento una vez, así que optaré por lo siguiente:
Controlar cuándo se muestra el control. A partir de ahí, almacenamos todos los cambios en un array. Cuando se oculte el control, llamamos a la función facilitándole el conjunto de cambios. Probablemente solo te interese el último valor (el de la fecha final), pero pasaré todos los cambios por si acaso:
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script>
<script>
function miFuncion(cambios) {
// Ésta es la función que se encarga de lo que tú quieras hacer.
console.log('¡Solo me ejecuto una vez por cambio!');
console.log('He recibido ' + cambios.length + ' cambios de fechas.');
console.log('El último cambio recibido ha sido: ' + cambios[cambios.length - 1] + '.');
}
$(document).ready(function() {
var cambios = new Array();
var registrando = false;
$('#idCalendario').datetimepicker({
onChangeDateTime: function(ct, $input) {
if (registrando) {
cambios[cambios.length] = $input.val();
}
},
onClose: function(ct, $input) {
if (registrando) {
miFuncion(cambios);
registrando = false;
}
},
onShow: function(ct, $input) {
registrando = true;
},
});
});
</script>
<input type="text" id="idCalendario" value="" class="form-control datepicker input-sm " >
Y eso sería todo. Espero que te sirva.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error with using get on an API (Vue.js, express.js)
That's my first question on this website.
I have created my own API for a school project with few routes:
The few routes
app.get('/AREA/', (req, res) => res.status(200).send({
message: 'Welcome to the AREA API'
}));
app.get('/AREA/Users', User.list);
app.post('/AREA/User', AuthPolicies.register, User.create);
app.get('/AREA/User', User.recup);
This is how I call the last get and post call:
Client:
How I call in the component client part1
RecupUser: function () {
this.error = ''
const User = {
email: this.email,
password: this.password
}
AuthServices.login(User)
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}
Part 2
register (credentials) {
return Api.post('/AREA/User', credentials)
},
login (credentials) {
return Api.get('/AREA/User', credentials)
}
API:
Server
create(req, res) {
return User
.create({
'email': req.body.email,
'password': req.body.password
})
.then(response => res.status(200).send(response))
.catch(res.status(400).send({
error: 'This email account is already in use.'
}));
},
recup(req, res) {
return User
.findOne({where: {email: req.body.email},})
.then(user => res.status(200).send({
user: user.toJSON()
}))
.catch(err => res.status(400).send({
error: err
}));
}
Error Recup:
Error: "Request failed with status code 400"
createError createError.js:16
settle settle.js:17
handleLoad xhr.js:59
Login.vue:62
All work except the app.get('/AREA/User', User.recup) and I really want to try to find the reason why (I also tried with asyc await and had the same problem).
Does someone has an idea, I thought it was because it didn't pass by my route but i don't see why.
Thanks for the help :)
A:
You are using a GET request here:
login (credentials) {
return Api.get('/AREA/User', credentials)
}
A GET request cannot have a body.
If you want to pass a body you must use a POST request, or one of the other request types.
For a GET request the alternative to a body is to use query parameters. These are just appended to the end of the URL in the form ?param=value. I don't know how Api.get is implemented so I can't give specific advice about how to pass query parameters to it.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the role of these capacitors?
I was reading about op-amps and found this schematic.
What is the role of those capacitors?
Lets call them:
10uF - Cap A
250uF - Cap B
0.05uF - Cap C
As of now, capacitor positioning and capacitance values choice seem so random to me. What am I missing?
Thanks!
A:
This is not an op-amp, not even an approximation to one, it's a fixed gain power amplifier. That image is figure 16 from the TI datasheet for LM386. Unfortunately it only explains the function of cap A, which is peculiar to the detailed circuit of the 386.
Cap A short circuits a gain setting resistor to change the amplifier gain. It has to be large enough to couple the internal resistor, in the order of 1k, down to bass frequencies.
Cap B is an AC coupling (aka DC blocking) capacitor always found on the output of a power amplifier that has a DC bias on its output. It has to be large enough to couple the speaker's impedance, typically 8 ohms, down to bass frequencies.
Cap C is part of a so called Zobel network frequently found across the loudspeaker terminals of power amplifiers, designed to compensate for the inductance of the speaker, to keep the amplifier stable. It is sized assuming a typical low power speaker that would be appropriate for that size of amplifier.
A:
Cap A does whatever the datasheet says about why you need to put it there. Or, if you don't always need it, the datasheet tells you what the purpose of pins 1 and 8 are.
Cap B is for AC coupling the output of the amp to the speaker. The output of the amp has some DC bias. That's not good for the speaker, and would cause extra current in both the amp and the speaker.
Cap C along with the 10 Ω resistor are most likely to keep the amp stable, which again the datasheet should explain.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way of determining that two file paths are referring to the same file object?
I want to write a unit test that checks that two file paths are equivalent, but I don't want to assume that the string representation is the same.
For example, on Linux there could be symlinks in the path in one case and not in the other. On Windows, there could be drive notation on one (X:\foo) and network notation on the other (//serverX/foo). And most complicated, the file may have been written on Linux on an NFS share (in /path/to/file syntax) and verified on Windows using DOS syntax (X:\to\file) where X: is a NFS mount to /path.
Some ideas (found here on Stack Overflow, but not unified):
On Linux, compare the inode from stat
Use realpath (Is this Platform independent?)
On Windows, compare strings on GetFullPathName
On Windows, compare serial numbers and file index from GetFileInformationByHandle
What would be the cross-platform best solution? I'm writing this in C++, but I can drop down to C obviously.
A:
You could check out the Boost.Filesystem library. Specifically, there is a method equivalent that seems to do exactly what you are looking for:
using namespace boost::filesystem;
path p("/path/to/file/one");
path q("/sym_link/to/one");
assert(equivalent(p, q));
| {
"pile_set_name": "StackExchange"
} |
Q:
Utilize xml-rpc from T-SQL code
Currently I have nice solutions for REST (via clr/assembly) and SOAP (via sp_OA based stored procedure) but XML-RPC is still a question to access directly from SQL Server T-SQL code.
Please advise which variants exist for this purpose.
I need to avoid application layer because all logic is already in a stored procedure inside the database, and just recordset is needed to be supplied.
A:
I have consumed XML from an HTTP call within t-sql using the xmlhttp COM object, which looks something like:
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open',
NULL, 'get',
'http://www.webservicex.com /stockquote.asmx?symbol=MSFT', 'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ResponseText
Exec sp_OADestroy @Object
The xml in @ResponseText can then be shredded via traditional tsql methods.
This isn't a particularly robust method; Using an SSIS package or CLR integration would most likely yield a better solution, but this is one way to keep it all within t-sql.
See: http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/eac9c027-db71-48ae-872d-381359d7fb51/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find a list in docx using python?
I'm trying to pull apart a word document that looks like this:
1.0 List item
1.1 List item
1.2 List item
2.0 List item
It is stored in docx, and I'm using python-docx to try to parse it. Unfortunately, it loses all the numbering at the start. I'm trying to identify the start of each ordered list item.
The python-docx library also allows me to access styles, but I cannot figure out how to determine whether the style is a list style or not.
So far I've been messing around with a function and checking output, but the standard format is something like:
for p in doc.paragraphs:
s = p.style
while s.base_style is not None:
print s.name
s = s.base_style
print s.name
Which I've been using to try to search up through the custom styles, but the all end at "Normal," as opposed to the "ListNumber."
I've tried searching styles under the document, the paragraphs, and the runs without luck. I've also tried searching p.text, but as previously mentioned the numbering does not persist.
A:
List items can be implemented in the XML in a variety of ways. Unfortunately the most common way, adding list items using the toolbar (as opposed to using styles) is also probably the most complex.
Best bet is to start using opc-diag to have a look at the XML that's being used inside the document.xml and then formulating a strategy from there.
The list-handling API for python-docx hasn't really been implemented yet, so you'll need to operate at the lxml level if you want to get this done with today's version.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I replace the word "hello" with "goodbye" in every file in this directory, and also recursively?
Suppose I have many files in this directory. I want to replace "hello" with "goodbye" everywhere, also recursively
A:
find . -type f -exec sed -i 's/hello/goodbye/g' {} +
| {
"pile_set_name": "StackExchange"
} |
Q:
How to customize nautilus files view in Ubuntu 17.04?
I want all Nautilus windows/folders to show file listings the same customized way.
On Windows I'd simply configure a single folder like I want, open options, click "set all folders like this one" (or something on those lines, don't remember the exact button label)
On Nautilus (Ubuntu file manager) I can configure a single folder at a time. And this site has dozen of answered questions on how to reset all folders to default, but I can't find anything on how to set all folders to my custom style.
Which is as shown bellow.
This would be my simple preferred view, with size before name.
Edit for clarity: I do Not want to set this on thousands of folders. I want my way to be the default everywhere.
A:
There's no solution using ubuntu's default file manager.
per folder settings is now mandatory per design apparently. I couldn't find any commit explicitly mentioning that change, but didn't look too hard.
Easy solution is to install the Cinamon desktop file manager: Nemo.
apt-get install nemo-fileroller
(install this so it draws all few dependencies, including nemo, and you already can have 'extract here' features)
After installing nemo and replacing your shortcuts in the launcher, there is a setting to "ignore per folder view preferences"
| {
"pile_set_name": "StackExchange"
} |
Q:
Аналог таймера из Handle
Можно ли с помощью класса Handler сделать аналог таймера (периодический запуск задачи по интервалу времени). Мой код:
class MyTask implements Runnable
{
public void run()
{
// здесь меняем UI потока, создавшего Handler
}
}
Handler handler = new Handler();
handler.post(new MyTask());
Необходимо, чтобы задача запускалась интервально.
A:
final Handler handler = new Handler();
final Runnable runnable = new Runnable()
{
public void run()
{
//Что то делаем
handler.postDelayed(runnable , 1000);
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't connect to PPTP VPN, even though it used to work and I didn't change anything
I am pretty new to Ubuntu and Linux, so forgive me if this is obvious.
I set up a PPTP VPN connection the other day. It worked perfectly fine, but one day to the other, it didn't anymore. I used it on 12.04, and it stopped working there. I then upgraded to 13.04 and it still wont work. The only thing I changed was adding a second monitor (I'm now running dual monitors), but I doubt that that has anything to do with it. I also installed the recommended updates.
The syslog gave me this:
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> Starting VPN service 'pptp'...
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> VPN service 'pptp' started (org.freedesktop.NetworkManager.pptp), PID 4958
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> VPN service 'pptp' appeared; activating connections
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> VPN plugin state changed: init (1)
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> VPN plugin state changed: starting (3)
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> VPN connection 'us vpn' (Connect) reply received.
Sep 11 13:59:18 Veith-Ubuntu pppd[4962]: Plugin /usr/lib/pppd/2.4.5/nm-pptp-pppd-plugin.so loaded.
Sep 11 13:59:18 Veith-Ubuntu pppd[4962]: pppd 2.4.5 started by root, uid 0
Sep 11 13:59:18 Veith-Ubuntu pppd[4962]: Using interface ppp0
Sep 11 13:59:18 Veith-Ubuntu pppd[4962]: Connect: ppp0 <--> /dev/pts/1
Sep 11 13:59:18 Veith-Ubuntu pptp[4965]: nm-pptp-service-4958 log[main:pptp.c:314]: The synchronous pptp option is NOT activated
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/ppp0, iface: ppp0)
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/ppp0, iface: ppp0): no ifupdown configuration found.
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <warn> /sys/devices/virtual/net/ppp0: couldn't determine device driver; ignoring...
Sep 11 13:59:18 Veith-Ubuntu pptp[4966]: nm-pptp-service-4958 warn[open_inetsock:pptp_callmgr.c:329]: connect: Connection refused
Sep 11 13:59:18 Veith-Ubuntu pptp[4966]: nm-pptp-service-4958 fatal[callmgr_main:pptp_callmgr.c:127]: Could not open control connection to 67.212.175.124
Sep 11 13:59:18 Veith-Ubuntu pptp[4965]: nm-pptp-service-4958 fatal[open_callmgr:pptp.c:487]: Call manager exited with error 256
Sep 11 13:59:18 Veith-Ubuntu pppd[4962]: Modem hangup
Sep 11 13:59:18 Veith-Ubuntu pppd[4962]: Connection terminated.
Sep 11 13:59:18 Veith-Ubuntu avahi-daemon[865]: Withdrawing workstation service for ppp0.
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: SCPlugin-Ifupdown: devices removed (path: /sys/devices/virtual/net/ppp0, iface: ppp0)
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <warn> VPN plugin failed: 1
Sep 11 13:59:18 Veith-Ubuntu pppd[4962]: Exit.
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <warn> VPN plugin failed: 1
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <warn> VPN plugin failed: 1
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> VPN plugin state changed: stopped (6)
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> VPN plugin state change reason: 0
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <info> Policy set 'Kabelnetzwerkverbindung 1' (eth0) as default for IPv4 routing and DNS.
Sep 11 13:59:18 Veith-Ubuntu NetworkManager[885]: <warn> error disconnecting VPN: Could not process the request because no VPN connection was active.
Sep 11 13:59:23 Veith-Ubuntu NetworkManager[885]: <info> VPN service 'pptp' disappeared
I googled a bit and uninstalled pptp-linux and network-manager-pptp. Then I reinstalled them.
I still can't connect and I get the same code.
I definitely configuered everything right in the network manager, otherwise it wouldn't have worked in the first place. I MPPE activated, and checked all the settings 100 times.
Another strange thing: When I tried it yesterday, it would give me the message that it connected for about half a second, only to be replaced by the "can't connect" Message right after. It doesn't do that today though.
I also tried forbidding all the compression types.
I searched, but couldn't find anything (at least nothing I understood).
Any help is greatly appreachiated!
Greetings
A:
From the logs, is not possible to diagnose what really happened, but the PPTP protocol has known difficulty passing through firewalls, so that could be the case here.
For the PPTP VPN protocol, you need to have open port 1723. Different VPN protocols have different needs, see this summary:
PPTP:
IP Protocol=TCP, TCP Port number=1723 <- Used by PPTP control path
IP Protocol=GRE (value 47) <- Used by PPTP data path
L2TP:
IP Protocol Type=UDP, UDP Port Number=500 <- Used by IKEv1 (IPSec control path)
IP Protocol Type=UDP, UDP Port Number=4500 <- Used by IKEv1 (IPSec control path)
IP Protocol Type=UDP, UDP Port Number=1701 <- Used by L2TP control/data path
IP Protocol Type=50 <- Used by data path (ESP)
SSTP:
IP Protocol=TCP, TCP Port number=443 <- Used by SSTP control and data path
IKEv2:
IP Protocol Type=UDP, UDP Port Number=500 <- Used by IKEv2 (IPSec control path)
IP Protocol Type=UDP, UDP Port Number=4500 <- Used by IKEv2 (IPSec control path)
IP Protocol Type=UDP, UDP Port Number=1701 <- Used by L2TP control/data path
IP Protocol Type=50 <- Used by data path (ESP)
(Source)
To check if your ports are open or not, you can simply telnet to the VPN address.
> telnet ipaddress 1723
If the connection is okay, the VPN will respond.
If connection is not okay, you will get the connection timeout response after some delay. Try a different connection (mobile for example) to confirm the case.
If possible, contact your ISP to correct this.
Update: The command in your question fails with
Connection refused, Could not open control connection to
xxx.xxx.xxx.xxx, and Call manager exited with error 256
so most likely, telnet will fail with connection refused (by host) as well and this could be different problem. Contact the VPN administrator to check the VPN logs from your IP address and the reason for refusal.
Update 2: You can follow the advice to fix the 256 error from this help page. It is basically these four steps:
Check ping to host
Check traceroute to host
Check telnet to host
Check supported protocols
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do dĵ (ĝ) and tŝ (ĉ) have special characters, but ks does not?
There is a thing about Esperanto's special characters (with accents) that I do not understand.
On the one side we have the characters ĝ and ĵ.
As far as I understand, ĝ and ĉ are pronounced as follows [1]:
ĝ -> dĵ
ĉ -> tŝ
So, technically, we wouldn't need the characters ĝ and ĉ, we could just write them in the long form 'dĵ' and 'tŝ'.
On the other side we have expressions that do not have a separate character, but are composed by two characters.
For example: 'ks' seems to be used in replacement of 'x' like in teksto (text) or ekster (external).
Is there a reason, why 'ĝ/dĵ' and 'ĉ/tŝ' do have separate characters, but 'ks' does not?
[1] http://www.fact-index.com/e/es/esperanto_orthography.html
A:
In short: ĝ and ĉ are not the same as dĵ and tŝ, but it does not really matter.
Long version: There is a a class of consonants called affricates: they consist of a plosive (e.g. t) and a sibilant (e.g. s) with same place of articulation and same voicing. In Esperanto the affricates are c, ĉ, ĝ, German for instance has pf. ks is not an affricate, but two different consonants. It is by chance of tradition that for ks there is a letter x in the Latin alphabet.
There are languages where affricates are significantly different from accidental combinations of their components. One of them - and this is important here, as it is one of the languages influencing Esperanto quite a lot - is Polish:
czy 'whether' (Esp. ĉu) [ʧɨ]
trzy 'three' [tʃɨ]
Other languages like German do not distinguish phonetically between real affricate /ʧ/ and accidental /t/+/ʃ/.
Happily for speakers of such languages and in contrast to e.g. Polish, in Esperanto there are hardly any non-affricate combinations, in fact only in compound words (e.g. tut-simple), where such a distinction would be necessary. So at the end it doesn't matter whether you can distinguish e.g. ĉ and t+ŝ in hearing or articulating.
See also the relevant section in PMEG, if you can read Esperanto.
A:
Short answer: 'ks' is not a single sound, 'ĝ' and 'ĉ' are.
'ks' is two different sounds, 'k' and 's'. They might even go to separate syllables, like in ik-so-do.
'dĵ' is only an approximation of 'ĝ'. Here I disagree with your source, in that 'ĝ' is not pronounced as 'dĵ', even though English tends to merge the two. Go to google translate and translate "adjunct" from English to Portuguese. You have on the page the option to listen to both pronunciations; the English uses the same sound as in 'age', whereas the Portuguese clearly has two different sounds, 'd' and 'ĵ'.
Same goes for 'tŝ' and 'ĉ', 'tŝ' is two sounds, 'ĉ' is a single sound. Trivia: the Serbian language has two different variants of the sound: 'Č' and 'Ć' Examples here: https://www.youtube.com/watch?v=b6WRxxqi96Y - I can't hear any 't' sound in the pronunciation.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Schönes Wochenende" versus "Schönen Wochenende"
Is there any preference to using "Schönes Wochenende" or "Schönen Wochenende" as a parting statement? Are they both allowed, or is there a preference for one over the other? Different people have told me that one or the other is OK, but that the other is wrong. This leaves me highly confused, and I often find myself going back and forth between the two.
A:
Yes, they are both grammatically allowed in the right context, and there is a difference between them regarding the use of the neuter "[das] Wochenende".
"Schönes Wochenende" is singular Nominative or Accusative, like "[ein] schönes Wochenende".
"Schönen Wochenende" is singular Dative or Genitive, and you'd probably attach a definite article or prepositional phrase to it like "dem/des/am schönen Wochenende".
If, for example, you want to wish a friend a nice weekend, you would say, "Schönes Wochenende!" as if to say "Ich wünsche dir ein schönes Wochenende!"
Here's a link I found that gives some different examples and translations of this phrase.
A:
While being German my Grammar is a bit rusty if put to real test, however, in a parting statement you never say "schönen Wochenende".
You would only use "schönen Wochenende" in a descriptive context, like - on a nice weekened we could go for a picknick - "An einem schönen Wochenende könnten wir...".
Generally accepted on parting, casual "Schönes Wochenende!" or more formal "Ich wünsche Dir/Ihnen ein schönes Wochenende".
A:
As "Kevin" wrote in his answer it depends on the case (dative or accussative).
as a parting statement? Are they both allowed ... ?
Used as parting or greeting statement ...
... "Schönes Wochendene!" is correct and ...
... "Schönen Wochendene!" is wrong.
The reason is the following one:
Greeting statements (such as "Good morning") are a short form of a sentence containing the verb "to wish" ("I wish you a good morning.").
The German language has the speciality that parts in a sentence may be exchanged (with some limitations) without changing the meaning of the sentence. This is not possible in English:
The boss wishes the employee a nice weekend.
The employee wishes the boss a nice weekend.
A nice weekend wishes the boss the employee.
The three examples do not have the same meaning and the third one even does not makes any sense. In German language however the three sentence do have the same meaning.
To be able to see who is doing what there are so-called "cases". "Cases" are more or less "just" endings of words that indicate what is the subject ("the boss"), what is the first object ("the employee") and what is the second object ("a nice weekend") in a sentence.
So in German language it is not the position in a sentence which decides what is the subject and what is the object but the ending of the word.
In conjunction with the word "wünschen" (to wish) the "second object" has the "accusative" case which means that the word ending is "ein schönes Wochenende" and not "einem schönen Wochenende" (which would be the correct ending for the "first object" - "the emoployee").
Of course there are other sentences using another verb than "to wish" where "a nice weekend" is the so-called "dative object". In such sentences "einem schönen Wochenende" would be correct:
Wir verdanken den Besucheransturm einem schönen Wochenende.
EDIT
Unfortunately in German language all nouns are either male, female or neuter. (Similar to Spanish or French where all nouns are either male or female.) For all three genders the word endings differ!
For a male word the accusative ending would be "einen schönen Tag".
For this reason the parting statement ...
"Schönen Tag!" would be correct while ...
"Schönen Wochenende!" would be wrong.
For a female word like holidays it would be:
"Schöne Ferien!"
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL: Seeking an advise for tables structure etc
First what are conditions. I have people belonging to "small" group. (which in other words means every one has "small_group_id". Then "small" groups form "big" groups (which in other words means "small_groups" may or not have "big_group_id" depending if small group belongs to bigger ot not).
I want to create a table structure (that would be used by PHP) for keeping and displaying two following things:
Public messages (means whoever is regestered or even not will be able to see it). Only author of the message can edit/delete. This is easy part :)
Private messages WITH defining how private is it. That means privat emessage should have property a) what small groups can see it b) what big groups can see it (that assumes that all members of big groups will have rights to see it).
Basically the challenge for me is how to design and later work with visibility of those private messages.
My first though was table like: msgID, msgBody, small_groups_list, big_group_list, authorID So I store e.g. in 'small_groups_id' something like 'id_1; id_4; id_10', etc and similar for big groups. But then I'm not sure how do I do search through such stored lists when e.g. person belonging to small_group_id = 10 supposed to see that mesage. Also what should be the columns small_groups_list and big_group_list defenitions/types.
Perhaps there is better way to store such things and using them as well?
That is why I'm here. What would be better practices for such requirements?
(it is going to be implemented on mySQL)
Thank you in advance.
[edit]
I'm pretty unexperienced in SQL and DB things. Please take that into account when answering.
A:
First: Don't denormalize your data with "array" columns. That makes it a horror to query, and even worse to update.
Instead, you need two separate tables: small_group_visibility and big_group_visibility. Each of these two tables will consist of msgID and groupID. Basically, it's a many-to-many relationship that's pointing out to both the group and the message it is concerned with.
This is a pretty common database pattern.
To query for messages to be displayed, imagine that we have a user whose small groups are (1, 2, 3) and whose large groups are (10, 20).
SELECT DISTINCT msgID, msgSubject, msgBody -- and so on
FROM messages m
LEFT JOIN small_group_visibility sg
ON sg.msg_id = m.msg_id
LEFT JOIN big_group_visibility bg
ON bg.msg_id = m.msg_id
WHERE
sg.group_id IN (1, 2, 3) OR
bg.group_id IN (10, 20);
| {
"pile_set_name": "StackExchange"
} |
Q:
Can group cohomology be interpreted as an obstruction to lifts?
The standard way to view the first and second group cohomologies is this:
The Standard Story
Let $G$ be a group, and let $M$ be a commutative group with a $G$-action. Then the first cohomology has the following interpretation: $H^1(G,M)$ is bijective with sections (modulo conjugation by $M$) of the short exact sequence $$1\rightarrow M\rightarrow M\rtimes G\rightarrow G\rightarrow 1.$$
Furthermore, the group of $1$-cocycles, $Z^1(G,M)$ is bijective with the sections of this short exact sequence. (Not modulo anything.) In fact, this holds even if $M$ is non-abelian.
The second cohomology $H^2(G,M)$ is bijective with the set of isomorphism classes of group extensions
$$1\rightarrow M\rightarrow H\rightarrow G\rightarrow 1$$
for which there exists a (or equivalently for every) set theoretic section $s:G\rightarrow H$ such that $g\cdot m=s(g)m(s(g))^{-1}$. (Here $g\cdot m$ denotes the action of $g$ on $m$ coming from the $G$-module structure of $M$.)
Liftings
In a paper I have been reading, they have given an entirely different interpretation to the first cohomology. Namely:
Let $A$ and $B$ be groups, and let $C$ be a normal abelian subgroup of $B$. Let $\bar \phi:A\rightarrow B/C$ be a homomorphism. Assume $\phi$ has a lift $\alpha:A\rightarrow B$. Then $Z^1(A,C)$ is bijective with the set of lifts of $\phi$ to homomorphisms from $A$ to $B$.
The bijection goes like this: $\theta\in Z^1(A,C)$ goes to $\alpha\theta$.
My question is: can one give an interpretation in terms of lifts to the second cohomology, or to the group of $2$-cocycles?
More precisely:
Question
Let $A$ and $B$ be groups, and let $C$ be a normal abelian subgroup of $B$. Let $\bar \phi:A\rightarrow B/C$ be a homomorphism.
Is it true that there exists a lift of $\bar \phi$ to a homomorphism from $A$ to $B$ if and only if $H^2(A,C)$ is trivial? Or is there a $2$-cocycle one can define (how would one define it?) such that there exists a lift of $\bar \phi$ if and only if it is trivial in $H^2(A,C)$? Or perhaps the right group to look at is the group of $2$-cocycles $Z^2(A,C)$ rather than the cohomology group?
I don't know if such an interpretation exists, so this is just wishful thinking. Since this is the first time I've seen the interpretation of $Z^1(A,C)$ in terms of lifts, I was curious whether such an interpretation extends to the second cohomology.
A:
In your setup, the extension
$$
C \to B \to B/C
$$
represents a cohomology class $u\in H^2(B/C;C)$. The homomorphism $\phi: A\to B/C$ admits a lift $\bar\phi : A\to B$ if and only if $\phi^\ast(u)\in H^2(A;C)$ is zero.
To see this, note that the induced map on second cohomology is given by pullback of extensions, so $\phi^\ast(u)$ is represented by the bottom row in the diagram
$$
\begin{array}{ccccc}
C & \to & B & \to & B/C \newline
\| & & \uparrow & & \uparrow \newline
C & \to & E & \to & A.
\end{array}
$$
Now splittings of the bottom row correspond to liftings of $\phi$.
This gives plenty of examples where $\phi$ lifts but $H^2(A;C)\neq 0$. In fact, you could take any non-split extension $C\to B\to B/C$ such that $H^2(B;C)\neq 0$ and let $\phi: B\to B/C$ be the quotient map.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run gradle task after another task, even the last task has dependecies which are failed
The problem is:
There is an android application. I want to execute android instrumentation tests (The gradle task is connectedCheck).
I want to open generated report in browser independently of whether were tests successfull or not.
Here the code of my task:
task showReportInBrowser << {
String resultsPath = projectDir.toString().replaceAll("\\\\", '/')
resultsPath = resultsPath + '/build/reports/androidTests/connected/index.html'
java.awt.Desktop.desktop.browse resultsPath.toURI()
}
I have tried this:
connectedCheck.finalizedBy showReportInBrowser
If the connectedCheck executes normally I get what I want.
But if the connectedCheck fail, my showReportInBrowser doesn't execute.
I think this is because the connectedCheck task depends on the connectedDebugAndroidTest task, which is failed while execution, therefore the connectedCheck even doesn't start, and my showReportInBrowser does't start too.
So I tried this:
connectedDebugAndroidTest.finalizedBy showReportInBrowser
But gradle said: Error:(75, 0) Could not find property 'connectedDebugAndroidTest' on project ':app'.
Open File
I don't understant: why the connectedCheck and connectedDebugAndroidTest are shown both in gradle verification group, but I can use in my buildscript only connectedCheck?
How can I reach my goal?
A:
In my case the fail was in connectedDebugAndroidTest task. So, to ignore all fails in particular subtask just use something similar:
connectedDebugAndroidTest {
ignoreFailures = true
}
But in this case it causes
Error:(66, 0) Gradle DSL method not found: 'connectedDebugAndroidTest()'
As shown here you can use the following bypass:
project.gradle.taskGraph.whenReady {
connectedDebugAndroidTest {
ignoreFailures = true
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to visualise GIST features of an image
I am currently working on a image classification application using deep learning algorithms (either by using GIST features or CNN). I need help in understanding the below queries.
I have extracted the GIST features of an image (Reference Link). These extracted features will be given as input to deep learning algorithm to classify the images.
Is there a way to visualize the extracted features on top of the image?
CNN or GIST, Which is better for image classification? Is GIST outdated when compared to CNN?
Thank you,
KK
A:
Given that code is trivial for both (GIST + Network and Raw Pixel + Network), you can try three approaches for a given project.
GIST + Dense layers (GIST is not space-distributed)
Raw Pixels + CNN + Dense Layers
Raw pixels + CNN + Dense + input layer 2 (GIST) + Dense
For some projects, GIST can help since it is an abstract feature that CNN might or might not learn.
EDIT: This paper compares GIST and CNN
Regarding:
Is there a way to visualize the extracted features on top of the image?
This can be done with an attention layer in approach 3 (CNN + GIST).
CNN provides spacial distribution (Required for visualization) and dense layer that merges CNN's output with GIST can be used with an attention layer.
Paper for visualization
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to sort data using react redux?
I am trying to sort the data and display it is sorted form after user clicks on dropdown button. I want to sort it based on funds i.e integer value. So I have added onClick on <a> tag but it is not working why so ?
home.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { sortByFunded } from '../../store/actions/sortAction';
class Home extends Component {
render() {
const { searchTermChanged, sortByFunded } = this.props;
return (
<div>
<div className="buttonContainer">
<div>
<button className="btn btn-primary mycustom dropdown-toggle mr-4" type="button" data-toggle="dropdown" aria-haspopup="true"
aria-expanded="false">Sort by </button>
<div className="dropdown-menu">
<a className="dropdown-item" href="#">End time</a>
<a className="dropdown-item" href="#" onClick={sortByFunded}>Percentage fund</a>
<a className="dropdown-item" href="#">Number of backers</a>
</div>
</div>
</div>
</div>
)
}
}
const mapStateToProps = state => ({
projects: state.search.projects,
sort: state.sort.projects
})
export default connect(mapStateToProps, { searchTermChanged, sortByFunded })(Home);
sortAction.js:
import { SORT_BY_FUNDED } from './types';
export const sortByFunded = () => ({
type: SORT_BY_FUNDED
});
sortReducer.js:
import { SORT_BY_FUNDED } from '../actions/types';
import Projects from '../../data/projects';
const initialState = {
projects: Projects
}
export default function (state = initialState, action) {
switch (action.type) {
case SORT_BY_FUNDED:
return {
...state,
projects: Projects ? Projects.sort((a, b) => a.funded - b.funded) : Projects
};
default:
return state;
}
}
projects.js:
export default [
{
"s.no":0,
"amt.pledged":15823,
"blurb":"'Catalysts, Explorers & Secret Keepers: Women of Science Fiction' is a take-home exhibit & anthology by the Museum of Science Fiction.",
"by":"Museum of Science Fiction",
"country":"US",
"currency":"usd",
"endTime":"2016-11-01T23:59:00-04:00",
"location":"Washington, DC",
"funded":186,
"backers":"219382",
"state":"DC",
"title":"Catalysts, Explorers & Secret Keepers: Women of SF",
"type":"Town",
"url":"/projects/1608905146/catalysts-explorers-and-secret-keepers-women-of-sf?ref=discovery"
},
{
"s.no":1,
"amt.pledged":6859,
"blurb":"A unique handmade picture book for kids & art lovers about a nervous monster who finds his courage with the help of a brave little girl",
"by":"Tyrone Wells & Broken Eagle, LLC",
"country":"US",
"currency":"usd",
"endTime":"2016-11-25T01:13:33-05:00",
"location":"Portland, OR",
"funded":8,
"backers":"154926",
"state":"OR",
"title":"The Whatamagump (a hand-crafted story picture book)",
"type":"Town",
"url":"/projects/thewhatamagump/the-whatamagump-a-hand-crafted-story-picture-book?ref=discovery"
}, ..... ]
A:
In my current implementation I was not actually storing Projects in your reducer, but always pulling it from the source when sorting. Also mutating it.
Working code:
reducer.js:
import { SORT_BY_FUNDED } from '../actions/types';
import Projects from '../../data/projects';
const initialState = {
projects: Projects
}
export default function (state = initialState, action) {
switch (action.type) {
case SORT_BY_FUNDED:
return {
...state,
projects: state.projects.length > 0 ? [...state.projects.sort((a,b) => a.funded - b.funded)] : state.projects
};
default:
return state;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
W3 Validation error, nested tags in an anchor tag
I have the following html code in my page:
<a class="fancybox" href="best-price.php">
<div id="bestprice">
</div><!--visitorinfo-->
</a>
At the validator I have the following message:
<div id="bestprice">
The mentioned element is not allowed to appear in the context in which
you've placed it; the other mentioned elements are the only ones that
are both allowed there and can contain the element mentioned. This
might mean that you need a containing element, or possibly that you've
forgotten to close a previous element.
One possible cause for this message is that you have attempted to put
a block-level element (such as "<p>" or "<table>") inside an inline
element (such as "<a>", "<span>", or "<font>").
Any ideas?
A:
You can't put a <div> tag inside of an <a> tag for doctypes prior to HTML5. But you could do something like this.
<a class="fancybox" href="best-price.php">
<span id="bestprice">
</span>
</a>
4.01 transitional: http://validator.w3.org/#validate_by_input
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->
<head>
<title>test</title>
</head>
<body>
<a class="fancybox" href="best-price.php">
<span id="bestprice">
</span>
</a>
</body>
</html>
HTML5: http://validator.w3.org/#validate_by_input
<!DOCTYPE html>
<head>
<title>test</title>
</head>
<body>
<a class="fancybox" href="best-price.php">
<span id="bestprice">
</span>
</a>
</body>
</html>
Note: As Rob mentioned in the comments. This,
<a class="fancybox" href="best-price.php">
<div id="bestprice">
</div>
</a>
Will validate in HTML5, but not in the older doctypes.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to treat blood-shot eyes if I don't have eye-drops? Water good or bad idea?
How to treat blood-shot eyes if I don't have Visine eye-drops? Water good or bad idea?
A:
Bad idea. Tears are not water, so water will simply wash them away and cause increased irritation. There are various folk remedies you can try such as placing teabags on your eyes, but in general if you don't have eye drops, removing the source of the irritation that caused them is the only option.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passar variavel do PHP para função do JS para que esse devolva a outro PHP
Olá,provavelmente o titulo ficou confuso,mas vou me explicar ao máximo:tenho um projeto em que em minha página está sendo listado dados de uma tabela que possuo em meu banco,esses Dados indicam um Grupo(ex.:id do grupo=14,nome do grupo=grupo,admin do grupo=fulano),e preciso criar uma maneira de "acessar" esse grupo que contem outras informações nele.
meu problema é: fiz um select que listou os grupos,que estão na conta do admin,e preciso selecionar um,pegar seu id e repassar a outro php,para que eu possa fazer select da outra tabela que se relaciona com o id do grup.
pagina do select:
<header>
<a href="group.php">grupos</a> //pagina atual
<a href="../php/unset.php">sair</a>
<a href="home.php">home</a>
</header>
<hr>
<table class="table">
<thead>
<tr>
<th scope="col">ID do Grupo</th>
<th scope="col">Nome do Grupo</th>
<th scope="col">Nome do líder</th>
<th scope="col"><a href="create_group.php"><button type="button" class="btn btn-success">Criar</button></a></th>
</tr>
</thead>
<tbody>
<?php include '../php/groups.php'?> //aqui é o php que faz o select e lista
</tbody>
</table>
arquivo php do select(a conexão com o banco está feita tudo corretamente,e o $id esta setado em uma variavel global $_SESSION['id'],cortei algumas partes aqui pos o codigo é muito grande,mas essa variavel $id esta setada certinho):
include "conexao.php";
$sth=$pdo->prepare("SELECT team_id,team_name,user_name FROM teams JOIN users ON team_admin_id = user_id WHERE user_id = :user_id");
$sth->bindValue(":user_id",$id);
$sth->execute();
foreach ($sth as $res){
extract($res);
echo '<tr>';
echo '<td><span id="id">'.$team_id.'</span></td>';
echo '<td><a href="#">'.$team_name.'</a><button id="botao" onclick="getgroupINFO('.$team_id.',"'.$team_name.'")//essa é a função do js que estou querendo executar\\">Entrar</button></td>';
echo '<td>'.$user_name.'</td>';
echo '<td></td>'; //aqui viria alguns icones,retirei eles por enquanto
echo '</tr>';
}
as "\" só coloquei aqui para fazer observações, o que eu quero é que o php passe o $team_id e o $team_name para a função do JS,pegando o id que estiver escrito na linha da tabela que eu clicar,(ex.: cliquei no botão cujo id escrito na linha da tabela é 12 e o nome "grupo1",entao a função getgroupINFO receberia (12,"grupo1"),então começa a linguagem que sei pouco:JS(JQuery incluso).
a função getgroupINFO() precisaria pegar os dados (citando o exemplo:getgroupINFO(12,'grupo1')) e enviá-los a outro php(chamado de group_select.php);
JS(ele foi chamado no final da pagina,logo depois do JQUERY):
function getgroupINFO(id,groupname) {
var dados = new XMLHttpRequest();
dados.open("POST", "../php/group_select.php",true);
dados.send(id)
dados.open("POST",".../php/group_select.php",true);
dados.send(groupname);
}
lembrando que o código está "cru",não tem CSS praticamente.
me digam no que eu estou errando(uma parte de mim diz que é o JS,pois é uma linguagem que ainda estou aprendendo e tenho muito pouco conhecimento) e caso seja necessário alguma informação à mais pode pedir
Atenciosamente,
Matheus Henrique.
A:
Eu indicaria você instanciar o jquery no seu projeto e fazer um arquivo php retornando um json para o ajax da seguinte forma
<script>
window.dados = "<?=$dados?>"; //Uma forma de passar uma variável do php pro JS
</script>
var dados = $('#id/.class').val(); // caso seja um form
$.ajax({
url: 'arquivo.php',
type: 'post',
data: {dados: dados}
}).done(function(e) {
console.log(e) // retorno da consulta
});
Espero ter ajudado um pouco se tiver alguma dúvida justifique!
| {
"pile_set_name": "StackExchange"
} |
Q:
Augmented Reality - Distance between marker image and Camera in ArKit?
I want to calculate the distance between any marker image saved in the iOS project which is used for detecting in Augmented Reality and your current position i.e. camera position using ARKIT ?
A:
As Apple’s documentation and sample code note:
A detected image is reported to your app as an ARImageAnchor object.
ARImageAnchor is a subclass of ARAnchor.
ARAnchor has a transform property, which indicates its position and orientation in 3D space.
ARKit also provides you an ARCamera on every frame (or you can get it from the session’s currentFrame).
ARCamera also has a transform property, indicating the camera’s position and orientation in 3D space.
You can get the translation vector (position) from a 4x4 transform matrix by extracting the last column vector.
That should be enough for you to connect the dots...
| {
"pile_set_name": "StackExchange"
} |
Q:
STL-like graph implementation
I have implemented an STL-like graph class. Could someone review it and tell me things that I could add to it?
File graph.hpp
#include <vector>
#include <list>
using std::vector;
using std::list;
#ifndef GRAPH_IMPL
#define GRAPH_IMPL
namespace graph {
struct node
{
int v,w;
};
template<class T, bool digraph>
class graph;
template<class T>
class vertex_impl
{
friend class graph<T,true>;
friend class graph<T,false>;
private:
list<node> adj;
int index;
T masking;
public:
vertex_impl(int index = -1, const T& masking = T()) : index(index), masking(masking){}
vertex_impl(const vertex_impl& other) : index(other.index), masking(other.masking){}
typedef typename list<node>::iterator iterator;
typedef typename list<node>::const_iterator const_iterator;
typedef typename list<node>::reverse_iterator reverse_iterator;
typedef typename list<node>::const_reverse_iterator const_reverse_iterator;
typedef typename list<node>::size_type size_type;
iterator begin() { return adj.begin(); }
const_iterator begin() const { return adj.begin(); }
iterator end() { return adj.end(); }
const_iterator end() const { return adj.end(); }
reverse_iterator rbegin() { return adj.rbegin(); }
const_reverse_iterator rbegin() const { return adj.begin(); }
reverse_iterator rend() { return adj.rend(); }
const_reverse_iterator rend() const { return adj.rend(); }
size_type degree() const { return adj.size(); }
int name() const { return index; }
const T& mask() const { return masking; }
void set_mask(const T& msk) { masking = msk; }
};
template<class T, bool digraph>
class graph
{
private:
vector<vertex_impl<T> > adj;
typename vector<vertex_impl<T> >::size_type V,E;
public:
typedef vertex_impl<T> vertex;
typedef typename vector<vertex>::iterator iterator;
typedef typename vector<vertex>::const_iterator const_iterator;
typedef typename vector<vertex>::reverse_iterator reverse_iterator;
typedef typename vector<vertex>::const_reverse_iterator const_reverse_iterator;
typedef typename vector<vertex>::size_type size_type;
graph(size_type v) : adj(v), V(v), E(0)
{
for(size_type i = 0; i < v; ++i) {
adj[i].index = i;
}
}
iterator begin() { return adj.begin(); }
const_iterator begin() const { return adj.begin(); }
iterator end() { return adj.end(); }
const_iterator end() const { return adj.end(); }
reverse_iterator rbegin() { return adj.rbegin(); }
const_reverse_iterator rbegin() const { return adj.rbegin(); }
reverse_iterator rend() { return adj.rend(); }
const_reverse_iterator rend() const { return adj.rend(); }
void insert(int from, int to, int weight = 1)
{
adj[from].adj.push_back((node){to,weight});
E++;
if(!digraph)
adj[to].adj.push_back((node){from,weight});
}
void erase(int from, int to)
{
for(typename vertex::iterator i = adj[from].begin(); i != adj[from].end();) {
if(i->v == to) {
i = adj[from].adj.erase(i);
E--;
} else {
++i;
}
}
if(!digraph) {
for(typename vertex::iterator i = adj[to].begin(); i != adj[to].end();) {
if(i->v == from) {
i = adj[to].adj.erase(i);
} else {
++i;
}
}
}
}
size_type vertices() const { return V; }
size_type edges() const { return E; }
vertex& operator[](int i) { return adj[i]; }
const vertex& operator[](int i) const { return adj[i]; }
};
}
#endif
File main.cpp
#include <stdio.h>
#include "graph.hpp"
int main()
{
graph::graph<char*,false> gr(5);
int m;
scanf("%d", &m);
for(int i=0; i<m; ++i) {
int a,b;
scanf("%d %d", &a, &b);
gr.insert(a,b);
}
for(graph::graph<char*,false>::size_type i = 0; i < 5; ++i) {
printf("%d: ", gr[i].name());
for(graph::graph<char*,false>::vertex::iterator j = gr[i].begin(); j != gr[i].end(); ++j) {
printf(" %d", j->v);
}
printf("\n");
}
return 0;
}
A:
your node type doesn't seem to be a node, but an edge (or an adjacency relationship, or something). Unless this implementation is based on some literature which describes entries in the adjacency list as nodes, I'd consider renaming it
I have no idea what mask and masking are supposed to mean. They may be meaningful names in the context where you're using this graph, but it isn't clear that they are in a generic graph. It's just where the user attaches their arbitrary data to each vertex, right? Is it even used?
the number of vertices is fixed at creation time, and you can only add edges. Is that sensible?
graph::insert doesn't check whether from and to are valid indices
what does digraph mean here - directed graph? Because there is another meaning which is totally unrelated. Why not just say "directed"?
it looks like graph::V is always identical to adj.size() (and is anyway never used), so you can remove it
vertex_impl is an internal implementation detail, yet you're exposing it. STL containers hide these details (list & tree nodes for example) inside the iterator, and only expose the user data. Is there a useful way of iterating transparently over the graph without exposing this?
A:
The point of the include guards is to prevent multiple inclusion of anything.
So always put them at the top of the file:
#include <vector>
#include <list>
#ifndef GRAPH_IMPL
#define GRAPH_IMPL
Because these are not at the top you include vector/list every time. This is just more work that does not need to be done.
Never put using statements in a header file (in global context).
using std::vector;
using std::list;
Anybody that uses your header file now implicitly pulls vector/list into the global namespace. This can have undesirable effects with name resolution. Don't do this in a header file. If you must be lazy then use scope so you are not forcing your requirements onto others. There is always a typedef to make things easier.
Comments (or well named members) would be an idea.
struct node
{
int v,w;
};
No idea what that will be used for.
If the user of your code library should not be seeing this then it should also be contained inside the private part of a classs so that they don't accidentally use it.
vertex_impl
Not sure what vertex_impl is for?
Is it exposed externally?
What is it implementing (its name contains impl)?
Why can it have more than two nodes (To me a vertex is an edge that connects two nodes)?
Why does the constructor not fully initialize the object (index is set externally).
What is masking for?
What is index for?
When I build objects that contain containers I abstract the container used:
list<node> adj;
Here I would have gone:
typedef std::list<node> Container;
Container adj;
Then I would derive the other iterator types from Container. This means if the code changes there is only one location where the code needs to change.
Having an explicit rbegin() and rend() implies that there is some ordering to the nodes. personally I would leave them out as their does not seem to be any way to logically define the order of traversal of a graph. If the user wants to iterate in the reverse order then can use std::reverse_iterator.
graph
Basically the same comments as vertex_impl
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add commas after every letter of random list of letters in database
How can i add comma, after every letter if my all records have random letters?
What i have:
1. AHGJTOSIYGJ
2. OTPDBSKGY
3. HFRYEC
4. OPFKWIFS
// etc
What i need:
1. A, H, G, J, T, O, S, I, Y, G, J,
2. O, T, P, D, B, S, K, G, Y,
3. H, F, R, Y, E, C,
4. O, P, F, K, W, I, F, S,
// etc
A:
These operations should be done via the application level not by DB. However you really want to do this from DB level you can easily do so using the user defined function. Here is a function to do this
delimiter //
create function myFunction(myString varchar(255))
returns varchar(255)
begin
declare strLen int ;
declare lookupChar char(1);
declare finalString varchar(255);
declare x int;
set strLen = length(myString);
set x = 1 ;
set finalString = '';
while x <= strLen do
set lookupChar = substring(myString,x,1);
if finalString = '' then
set finalString = lookupChar;
else
set finalString = concat(finalString,',',lookupChar);
end if;
set x = x+1;
end while;
return finalString;
end//
delimiter;
Lets run this on mysql
mysql> create table mytable (id int, value varchar(100));
Query OK, 0 rows affected (0.19 sec)
mysql> insert into mytable values (1,'AHGJTOSIYGJ'),(2,'OTPDBSKGY'),(3,'HFRYEC'),(4,'OPFKWIFS');
Query OK, 4 rows affected (0.02 sec)
mysql> select * from mytable ;
+------+-------------+
| id | value |
+------+-------------+
| 1 | AHGJTOSIYGJ |
| 2 | OTPDBSKGY |
| 3 | HFRYEC |
| 4 | OPFKWIFS |
+------+-------------+
4 rows in set (0.00 sec)
Lets now create the function
mysql> delimiter //
mysql> create function myFunction(myString varchar(255))
-> returns varchar(255)
-> begin
-> declare strLen int ;
-> declare lookupChar char(1);
-> declare finalString varchar(255);
-> declare x int;
->
-> set strLen = length(myString);
-> set x = 1 ;
-> set finalString = '';
-> while x <= strLen do
-> set lookupChar = substring(myString,x,1);
-> if finalString = '' then
-> set finalString = lookupChar;
-> else
-> set finalString = concat(finalString,',',lookupChar);
-> end if;
-> set x = x+1;
-> end while;
-> return finalString;
-> end//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
So far so good, now lets select the values using the function
mysql> select id,myFunction(value) as value from mytable ;
+------+-----------------------+
| id | value |
+------+-----------------------+
| 1 | A,H,G,J,T,O,S,I,Y,G,J |
| 2 | O,T,P,D,B,S,K,G,Y |
| 3 | H,F,R,Y,E,C |
| 4 | O,P,F,K,W,I,F,S |
+------+-----------------------+
You can do this for entire table and also you can do the update easily if needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
sort list using property variable
Suppose I have this list of process or any other object
List<Process> listProcess = new List<Process>();
I can sort it using this line listProcess.OrderBy(p => p.Id);
But what if I have only string name of property obtained in runtime. I assume, I should use reflection to get the property object. Can I use orderby method or I should use Sort and then pass own comparer?
A:
You can have a look at the post referred in the comment. Or, you can achieve that using simple reflection like this
var sortedList = list.OrderBy(o => o.GetType().GetProperty(propName).GetValue(o));
Where
List<object> list; //a list of any object(s)
string propName; //name of the property to be used in OrderBy
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrive encryption passpharase?
When installing Ubuntu I chose to encrypt my home drive and after installation update information window came up:
Where I had to write down encryption passphrase. Well I closed it and it doesn't pop up any more. So the question is where can I find it to write down the passphrase?
A:
Follow these steps:
Hit Ctrl+Alt+T to open terminal and run following command:
ecryptfs-unwrap-passphrase ~/.ecryptfs/wrapped-passphrase
It will ask for a Passphrase:, enter your login password and you'll get the key.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prononcer « ent » à la fin d'un mot
Il est très difficile pour moi de comprendre quelles sont les lettres que je dois prononcer et celles que je dois ignorer dans les mots suivants : se prononcent, s'élident, devient, etc.
A:
-ent à la fin d'un mot peut avoir plusieurs prononciations, et comme dans plusieurs langues, il est difficile de savoir laquelle retenir (il existe des poèmes basés sur ce principe en anglais, mais je digresse).
La seule règle : les verbes au pluriel
Ainsi qu'expliqué dans plusieurs réponses, s'il s'agit de la terminaison d'un verbe conjugué à la troisième personne du pluriel (ils/elles), -ent est muet et ne modifie pas la prononciation du verbe.
Dans le cas d'« ils prononcent », on dira /il prononce/1. « Elles devaient » se dira /elle devait/.
Comme rappelé par Fabrice, la présence du T final permet toutefois de faire une liaison qui ne serait pas possible autrement : « ils prononcent au moins ce mot correctement » peut s'énoncer /il prononce-t-au moins…/ (ou /il prononce au moins…/, l'art des liaisons ayant tendance à se perdre).
Autres cas des verbes
Devenir est un verbe du troisième groupe. Parmi les verbes ayant la même prononciation pour -ent, on peut noter :
venir, devenir… et tous ceux ayant le même radical ;
tenir et ses dérivés (retenir)2 ;
je n'ai pas d'autre exemple me venant et personne n'en a proposé en commentaire.
Pour « il devient », -ent prend la même prononciation que -ain dans pain (\ɛ̃\).
À noter que ceci n'est valable qu'à la troisième personne du singulier. Au pluriel, le -ent devient à nouveau muet : « ils deviennent » se prononce /il devienne/.
Noms, adverbes et adjectifs
Comme précisé plus haut, j'ignore s'il s'agit d'une règle, mais plutôt d'un constat : dans les noms, adverbes et adjectifs (p.ex. pertinent, couvent, souvent, pénitent, ...), -ent se prononce comme dans vent (\ɑ̃\).
1. Je dois toujours apprendre les notations phonétiques, mais celle-ci a l'avantage d'être lisible par ceux qui ont la même lacune que moi.
2. Merci à Circeus pour le complément.
A:
The famous "Les poules couvent souvent au couvent" in Amélie Poulain :-)
I wouldn't bet on a 100% reliable rule, but at least the grammar plural form is mute ("e") and the other form are most often prononcent "en", or "ent'" in case of liaison).
Same for ils dévient [dévier] vs il devient [devenir].
| {
"pile_set_name": "StackExchange"
} |
Q:
minimum number of repetitions in a string
I have a string of length $n$ from an alphabet $A$ with $s$ symbols.
What is the probability of having at least $k$ equal characters?
It does not seem a binomial, nor a $1-$... form, nor a bar and star.
A:
The event of some character occurring at least $k$ times is the complement of the event of each of the $s$ characters occurring at most $k-1$ times. We can count the number of such strings of length $n$, and divide by $s^n$, the number of all strings of length $n$.
The number of words with each of the $s$ characters occurring at most $k-1$ times is $n!$ times the coefficient of $z^n$ in
$$\left(1 + z + \frac{z^2}{2!} + \dots + \frac{z^{k-1}}{(k-1)!}\right)^s$$
As a sanity check, note that if we dropped the "at most $k-1$ times" restriction (let $k \to \infty$), we'd get the count to be $n^s = s^n$, as expected.
So the answer (probability) is
$$1 - \frac{n![z^n]\left(1 + z + \frac{z^2}{2!} + \dots + \frac{z^{k-1}}{(k-1)!}\right)^s}{s^n} = 1 - n![z^n]\left(1 + (z/s) + \frac{(z/s)^2}{2!} + \dots + \frac{(z/s)^{k-1}}{(k-1)!}\right)^s$$
which doesn't seem to lend itself to much simplification.
| {
"pile_set_name": "StackExchange"
} |
Q:
Marketing Cloud export and import to Salesforce
We're exporting a csv file from marketing cloud using a data extract activity. The delimiter is ,
The export contains salesforceID and another field. It's csv so the values are in one column but , separated.
We're having problems importing using dataloader and workbench developerforce. Data loader isn't activating the object and csv when the csv is selected.
Workbench developerforce gives an error that the final row contains 3 columns instead of 2.
Here's some example data:
contact_no_intg,person_salesforce_id,GDPR Status
12345678,000000000000000000,Opt in
12345679,000000000000000001,Opt in
12345670,000000000000000002,Opt in
I think it has something to do with the file type. Even though the file extension is .csv when I open the file it looks like it thinks it's a .txt, and when I save as a .csv I can upload.
I'd like to avoid having to open and save as. Is there a way to export the file from MC so I can upload to SF without changing anything? Or is there a way of automating the saving of the file type as?
A:
Thanks Stephan, you're right. We had to ask Marketing Cloud support to enable an UTF16 to UTF8 data extract type.
| {
"pile_set_name": "StackExchange"
} |
Q:
magento site temporally unavailable
I put my magento site on maiatenance mode whislt I did a back up.
after the back i deleted all the file in the server because i wanted to start afresh because of a database issue.
but to my surprise I am getting an error when i visit the domain even when there are no files on the server.
what could be the problem?
I even deleted the cpanel account from WHM and created from the scratch but anytime i visit the domain, I get that error.
Very strange!!
please see attached.
A:
There might be a file called maintenance.flag on your root of Magento. Delete that file and it should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
What parameters should be used for AbstractDeclarativeValidator.warning and error?
I have a working grammar on xtext, and am starting the validation of the code.
For this, I added a method in the validator xtext created for me.
Of course, when an expression isn't valid, I want to be able to give a warning on the given AST node.
I attempted the obvious:
@Check
public void testCheck(Expression_Multiplication m){
if(!(m.getLeft() instanceof Expression_Number)){
warning("Multiplication should be on numbers.",m.getLeft());
}
if(!(m.getRight() instanceof Expression_Number)){
warning("Multiplication should be on numbers.",m.getRight());
}
}
Without success, as Expression_Number extends EObject, but is not an EStructuralFeature.
warning(String message, EStructuralFeature feature)
There are many other prototypes for warning, but none that takes just a String and a Eobject. Using null or various values extracted from eContainingFeature logs an error, and sometimes shows the warning at the correct place anyway. Searching for examples, I found that the values were often coming from the statics fields of a class called Literals or ***Package, the one generated in the project contains EStructuralFeatures, but I have no idea of which one to use, or why I would need one of these.
So the question is:
How can I place a warning on a given AST element ?
A:
The EStructuralFeature is the property of your AST. You'll find a generated EPackage class, which contains constants.
I guess in your case it is something like:
MyDslPackage.Literals.EXPRESSION_MULTIPLICATION__LEFT
and
MyDslPackage.Literals.EXPRESSION_MULTIPLICATION__RIGHT
A:
I ended up using
private void warning(String text, EObject badAstNode){
// The -1 seems to come from a static member somewhere. Probably cleaner to
// name it, but I couldn't find it again.
warning(text,badAstNode,null,-1);
}
I have no idea about whether this is supposed to be the right way, but it seemed to work in the various cases I used it, and requires a minimal amount of state to be kept.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the smallest value of the function $F:\alpha\in\mathbb R\rightarrow \int_0^2 f(x)f(a+x)dx$
Let $f -$ fixed continuous on the whole real axis function which is periodic with period $T = 2$, and it is known that the function $f$ decreases monotonically on the segment $[0, 1]$ increases monotonically on the segment $[1, 2]$ and for all $ x \in \mathbb R $ satisfies the equality $f(x)=f(2-x)$. Find the smallest value of the function
$$F:\alpha\in\mathbb R\rightarrow \int_0^2 f(x)f(\alpha+x)dx$$
I have no clue how to start. Any kind of help will be appreciated.
A:
We intend to prove that the smallest value of the function $F$ defined by
\begin{equation*}
F({\alpha}) = \int_0^2f(x)f(x+{\alpha})\, dx\tag{1}
\end{equation*}
is $F(1)$.
At first we give $f$ the additional property to be differentiable with a continuous derivative. At the end we will fill that gap.
The function $F$ will be continuous and have the period $T = 2$. Thus there exists a smallest value of $F(\alpha).$
If $f$ is differentiable then $F$ will also be differentiable.
We intend to prove that
\begin{equation*}
F'(\alpha) \le 0 \text{ for } 0 \le \alpha \le 1. \tag{2}
\end{equation*}
Since
\begin{equation*}
f(x) = f(2-x) = f(-x)\tag{3}
\end{equation*}
then $F(\alpha) = F(2-\alpha)$. Then (2) implies that
\begin{equation*}
F'(\alpha) \ge 0 \text{ for } 1 \le \alpha \le 2.
\end{equation*}
Then we know that $F(1)$ is the smallest value.
We start by studying (1). If we change $x$ to $x+1$ and then $x$ to $1-x$ we get
\begin{gather*}
\int_1^2f(x)f(x+\alpha)\, dx = \int_0^1f(x+1)f(x+1+\alpha)\, dx = [(3)]\\ = \int_0^1f(1-x)f(1-x -\alpha)\, dx = \int_0^1f(x)f(x-\alpha)\, dx.
\end{gather*}
Now we can rewrite $F(\alpha)$ as
\begin{equation*}
F(\alpha) = \int_0^1f(x)(f(x+\alpha)+f(x-\alpha))\, dx.
\end{equation*}
Via differentiation under the integral sign (we now use that $f$ is differentiable) followed by integration by parts we get
\begin{gather*}
F'({\alpha}) = \int_0^1f(x)(f'(x+{\alpha})-f'(x-{\alpha}))\, dx = \left[f(x)(f(x+{\alpha})-f(x-{\alpha}))\right]_0^1 \\- \int_0^1f'(x)(f(x+{\alpha})-f(x-{\alpha}))\, dx = f(1)\underbrace{(f(1+{\alpha})-f(1-{\alpha}))}_{= 0}-f(0) \underbrace{(f({\alpha})-f(-{\alpha}))}_{= 0} \\- \int_0^1f'(x)(f(x+{\alpha})-f(x-{\alpha}))\, dx = - \int_0^1f'(x)(f(x+{\alpha})-f(x-{\alpha}))\, dx.
\end{gather*}
Since $f$ is decreasing and differentiable on $[0,1]$ then $f'(x) \le 0$ in the integral above. It remains to prove that
\begin{equation*}
g(x,\alpha) = f(x+{\alpha})-f(x-{\alpha}) \le 0
\end{equation*}
on the square $0 \le x \le 1, \, 0 \le \alpha \le 1.$ But \begin{equation*}
g(\alpha,x) = f(\alpha +x) - f(\alpha-x) = [(3)] = f(x+{\alpha})-f(x-{\alpha}) = g(x,\alpha).
\end{equation*}
Consequently it is sufficient to examine $g$ on the triangle $0 \le \alpha \le x \le 1.$ To do that we study $g$ on that part of the straight line $\alpha = x-k$, that runs inside the triangle. Here $k$ is constant in $[0,1]$.
To be more precise look at
\begin{equation*}
g(x,x-k) = f(2x-k)-f(k), \quad 0 \le k \le 1, \: k \le x \le 1.
\end{equation*}
We split the $x$-interval into two. If $k \le x \le \dfrac{k+1}{2}$ then $k \le 2x - k \le 1$. Thus $2x-k \in[0,1]$ and $k\in[0,1]$. But on $[0,1]$ the function $f$ is decreasing. Since $2x-k \ge k$ then $f(2x-k) \le f(k)$ and $g(x,2x-k) \le 0.$
The second part of the $x$-interval is $\dfrac{k+1}{2} \le x \le 1$. Then $1 \le 2x-k \le 2-k \le 2$. Furthermore $f(k) = f(2-k)$ and $1 \le 2-k \le 2.$ But on the interval $[1,2]$ the function $f$ is increasing. Since $2x-k \le 2-k$ then $f(2x-k ) \le f(2-k)$ and $g(x,2x-k) \le 0.$
We have proved that $F(1)$ is the smallest value under the additional assumption that $f$ is differentiable with a continuous derivative.
Now we will prove that the same is true if $f$ only is continuous. Define a smooth substitute $\tilde{f}$ for $f$ via
\begin{equation*}
\tilde{f}(x) = \dfrac{1}{2h}\int_{x-h}^{x+h}f(t)\, dt = \dfrac{1}{2h}\int_{-h}^{h}f(x+t)\, dt.\tag{4}
\end{equation*}
Then $\tilde{f}$ will be differentiable with the continuous derivative $\dfrac{f(x+h)-f(x-h)}{2h}$. Furthermore it inherits a lot of properties from $f$. It is obvious that $\tilde{f}$ will be periodic with $T=2$. It will also fulfil the condition $\tilde{f}(x) = \tilde{f}(2-x) = \tilde{f}(-x).$ It will also be decreasing on $[0,1]$. To realize that we need a little argument. Assume that $0 < x_1 < x_2 <1$. If $h$ in (4) is small enough then $|t|$ will be so small that
\begin{equation*}
0 <x_1+t<x_2+t <1.
\end{equation*}
From (4) we then get that $\tilde{f}(x_1) \ge \tilde{f}(x_2)$. We have proved that $\tilde{f}$ is decreasing on the open interval $0 < x < 1$. But since $\tilde{f}$ is differentiable it will also be decreasing on the closed interval $0 \le x \le 1$ (use the intermediate value theorem).
Analogously we prove that $\tilde{f}$ is increasing on $1\le x\le 2.$
Since $f$ is continuous and since we work on a compact interval $f$ will be uniformly continuous. Thus to a given $\varepsilon $ there exists a $\delta $ such that
\begin{equation*}
|f(x_1)-f(x_2)| < \varepsilon \text{ if } |x_1-x_2|< \delta .
\end{equation*}
With these $\varepsilon$ and $\delta$ and with $0<h<\delta$ we get
\begin{equation*}
|f(x)-\tilde{f}(x)| \le \dfrac{1}{2h}\int_{-h}^{h}|f(x)-f(x+t)|\, dt \le \dfrac{1}{2h}\int_{-h}^{h}\varepsilon\, dt = \varepsilon .\tag{5}
\end{equation*}
We are now prepared to study the function
\begin{equation*}
\tilde{F}(\alpha) = \int_0^2\tilde{f}(x)\tilde{f}(x+\alpha)\, dx.
\end{equation*}
According to what we have done above we know that
\begin{equation*}
\tilde{F}(\alpha) \ge \tilde{F}(1)
\end{equation*}
and that $\tilde{F}(1)$ is the smallest value.
From (5) we get
\begin{gather*}
|F(\alpha) - \tilde{F}(\alpha)| \le \int_0^2|f(x)f(x+\alpha)-\tilde{f}(x)\tilde{f}(x+\alpha)|\, dx \\= \int_0^1|(f(x)-\tilde{f}(x)) f(x+{\alpha})+\tilde{f}(x)(f(x+{\alpha})-\tilde{f}(x+{\alpha}))|\, dx \\
\le \int_0^2(\epsilon C + C\varepsilon)\, dx = 2C\varepsilon
\end{gather*}
where $\displaystyle C = \max_{0 \le x\le 2}|f(x)|$.
Consequently
\begin{equation*}
F({\alpha}) = F({\alpha}) -\tilde{F}({\alpha}) +\tilde{F}({\alpha}) \ge -2C\varepsilon +\tilde{F}(1).
\end{equation*}
But $\varepsilon$ can be arbitrarily small.
In the limit we have that
\begin{equation*}
F({\alpha})\ge F(1)
\end{equation*}
i.e. $F(1)$ is the smallest value of $F(\alpha).$
I welcome shorter solutions.
A:
To make reflection symmetry more obvious let us define a shifted function $g: \mathbb{R} \to \mathbb{R}$ as $$g(x)~:=~f(x\!+\!1)+k,\tag{1}$$ where $k\in\mathbb{R}$ is a constant, introduced for later convenience. Hence we have an even continuous & periodic function $g$ with period 2, $$g(-x)~=~g(x)~=~g(x+2),\tag{2}$$
which is monotonically weakly increasing in the interval $[0,1]$.
Define a function $G: \mathbb{R} \to \mathbb{R}$ as
$$ G(x)~:=~\int_{-1}^1 \!dy ~g(y)g(y\!+\!x)~=~\int_{-1}^1\!dy ~g(y\!-\!x)g(y)~=~G(-x).\tag{3} $$
Clearly the function $G$ is also an even continuous & periodic function with period 2.
Moreover the function $G$ has an additional reflection symmetry around the $x=1$ axis: $$ G(2\!-\!x)~=~\int_{-1}^1 \!dy ~g(y)g(y\!+\!2\!-\!x)~=~\int_{-1}^1 \!dy ~g(y)g(y\!-\!x)~=~G(x).\tag{4} $$
Hence it is enough to study the function $G$ in the interval $[0,1]$.
Note that the constant $k\in\mathbb{R}$ only shifts the function $G$ up and down in a trivial manner
$$ G(x) ~=~F(x) + 2k^2 + 2 k\int_0^2 \!dy ~f(y) . \tag{5} $$
It is easy to see that $x=0$ is a global maximum point:
$$G(0)~=~\frac{1}{2}\int_{-1}^1 \!dy \left[g(y)^2+g(y\!+\!x)^2\right]~\geq~\int_{-1}^1 \!dy ~g(y)g(y\!+\!x)~=~G(x).\tag{6} $$
We next prove that the function $G$ is weakly decreasing in the interval $\left[0,\frac{1}{2}\right]$. Choose a point $x_0\in \left[0,\frac{1}{2}\right]$. Choose the constant $k$ such that $g(x_0)=0$. Then for $h\in[0,1]$, we calculate
$$ G(x_0\!+\!h)-G(x_0\!-\!h)
~=~ \int_{-1}^1 \!dy \left[g(y\!-\!h)-g(y\!+\!h)\right]g(y\!+\!x_0)$$
$$~=~ \int_{-1}^{-2x_0} \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\geq 0}~\underbrace{g(y\!+\!x_0)}_{\geq 0}
+\int_{-2x_0}^0 \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\geq 0}~\underbrace{g(y\!+\!x_0)}_{\leq 0}$$
$$+\int_0^{2x_0} \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\leq 0}~\underbrace{g(y\!+\!x_0)}_{\geq 0}
+\int_{2x_0}^1 \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\leq 0}~\underbrace{g(y\!+\!x_0)}_{\geq g(y\!-\!x_0)\geq 0}$$
$$~\leq~\int_{-1}^{-2x_0} \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\geq 0}~\underbrace{g(y\!+\!x_0)}_{\geq 0}
+\int_{2x_0}^1 \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\leq 0}~\underbrace{g(y\!-\!x_0)}_{\geq 0}$$
$$~=~0. \tag{7} $$
The last equality follows via changing the sign of the integration variable $y$ in one of the two integrals. Hence the function $G$ is weakly decreasing in the interval $\left[0,\frac{1}{2}\right]$.
We finally prove that the function $G$ is weakly decreasing in the interval $\left[\frac{1}{2},1\right]$. Choose a point $x_0\in \left[\frac{1}{2},1\right]$. Choose the constant $k$ such that $g(x_0)=0$. Then for $h\in[0,1]$, we calculate
$$ G(x_0\!+\!h)-G(x_0\!-\!h)
~=~ \int_{-1}^1 \!dy \left[g(y\!-\!h)-g(y\!+\!h)\right]g(y\!+\!x_0)$$
$$~=~ \int_{-1}^{2x_0-2} \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\geq 0}~\underbrace{g(y\!+\!x_0)}_{\leq g(y\!-\!x_0)\leq 0}
+\int_{2x_0-2}^0 \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\geq 0}~\underbrace{g(y\!+\!x_0)}_{\leq 0}$$
$$+\int_0^{2-2x_0} \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\leq 0}~\underbrace{g(y\!+\!x_0)}_{\geq 0}
+\int_{2-2x_0}^1 \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\leq 0}~\underbrace{g(y\!+\!x_0)}_{\leq 0}$$
$$~\leq~\int_{-1}^{2x_0-2} \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\geq 0}~\underbrace{g(y\!-\!x_0)}_{\leq 0}
+\int_{2-2x_0}^1 \!dy \underbrace{\left[g(y\!-\!h)-g(y\!+\!h)\right]}_{\leq 0}~\underbrace{g(y\!+\!x_0)}_{\leq 0}$$
$$~=~0. \tag{8} $$
The last equality follows via changing the sign of the integration variable $y$ in one of the two integrals. Hence the function $G$ is also weakly decreasing in the interval $\left[\frac{1}{2},1\right]$.
Altogether, it follows from the above that $x=1$ is a global minimum point, which in turn answers OP's question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Edittext imeOptions actionDone not working with digits attribute?
I have an Editext . It contains attribute digits and imeOptions (actionDone) together.
<android.support.v7.widget.AppCompatEditText
android:id="@+id/edit_text_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="1234567890abcdefghijklmnopqrstuvwxyz....."
android:hint="@string/item_name"
android:imeOptions="actionDone"
android:maxLines="1" />
The actionDone (Done button in Softkeyword) not found while using digit && imeOptions attributes together . We can only find enter button which doesn't make any focus change. I have tried it by skipping digit attribute , then imeOptions working correctly.
Thanks in advance
A:
Just add singleLine="true" to your edittext
android:singleLine = "true"
A:
view.setRawInputType(view.getInputType & ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)
It is important to call setRawInputType() and not setInputType(), since the latter will set the keylistener based on the inputmethod and your android:digits attribute will be discarded. setRawInputType() will only change the inputmethod and it won't touch the KeyListener, furthermore & ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE will disable the multi line mode, so no return key will be visible, instead your chosen imeOption should be visible.
Basically, there is a different behaviour of singleLine and maxLines.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSDate Conversion
I'm attempting to convert a date from MMM dd, YYYY to YYYY-MM-dd.
NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init];
[importDateFormat setDateFormat:@"MMM dd, YYYY"];
NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd"];
NSString *dateImported = [dateFormat stringFromDate:importedDate];
The date brought in from the expiresOn.text (label) is:
Oct 08, 2012
The date contained in dateImported after conversion is:
2011-12-25
Am I missing something? Is there something wrong with my date formatter?
A:
Well there are two things wrong, first is yyyy not YYYYY and since you are parsing the month as a word you need to tell the date formatter which language to expect.
NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init];
[importDateFormat setDateFormat:@"MMM dd, yyyy"];
importDateFormat.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en"] autorelease];
NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSString *dateImported = [dateFormat stringFromDate:importedDate];
If you are using ARC, then remove the autorelease part in the NSLocale; if you are not using ARC, you need to release the NSDateFormatter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Good approach for determining visible subviews in a UIScrollView
I'm trying to find the best approach for determining the visible subviews in a UIScrollView, I already found a good approach and it is: When the UIScrollView is scrolled I iterate over the array of subviews in my UISCrollView then find out whether each subview is visible or not by checking if the subview's frame intersects with the scrollview boundaries, I also cache the max offset that the scrollview has reached so the scrollViewDidScroll: method doesn't get called more than once at the same offset. I use this code for this approach:
CGFloat currentXOfsset = scrollView.contentOffset.x;
if (currentXOfsset > maxScrolledXOffset) {
for (UIView *subview in scrollView.subviews) {
if ([subview isKindOfClass:[UIButtonWithImageURL class]] && CGRectIntersectsRect(scrollView.bounds, subview.frame)) {
//Do whatever you want with the visible subviews.
}
}
}
maxScrolledXOffset = currentXOfsset>maxScrolledXOffset?currentXOfsset:maxScrolledXOffset;
This works properly, but the only problem here is that I have to loop through all the subviews when the UIScrollView scrolls, and that makes the scroll quite unsmooth, because I load images in these subviews.
What are the other approaches that I can use for determining visible subviews but with keeping a smooth scroll?
A:
This is the correct approach. How many subviews do you have in this scrollView? On which device is it slow? You may be doing another heavy operation somewhere (post more code so we can figure that out).
If you had a lot of subviews, a faster way would be to use an algorithm that reduce the number of views to test, like a quad tree or a static grid. I'm positive that this will be definitely overkill for you. CGRectIntersectsRect only does up to 4 float comparisons.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating 2D bins in R
I have coordinate data in R, and I would like to determine a distribution of where my points lie. The entire space of points is a square of side length 100.
I'd like to assign points to different segments on the square, for example rounded to the nearest 5. I've seen examples using cut and findinterval but i'm not sure how to use this when creating a 2d bin.
Actually, what I want to be able to do is smooth the distribution so there are not huge jumps in between neighboring regions of the grid.
For example (this is just meant to illustrate the problem):
set.seed(1)
x <- runif(2000, 0, 100)
y <- runif(2000, 0, 100)
plot(y~x)
points( x = 21, y = 70, col = 'red', cex = 2, bg = 'red')
the red point is clearly in a region that by chance hasn't had many other points, so the density here would be a jump from the density of the neighbouring regions, I'd like to be able to smooth this out
A:
You can get the binned data using the bin2 function in the ash library.
Regarding the problem of the sparsity of data in the region around the red point, one possible solution is with the average shifted histogram. It bins your data after shifting the histogram several times and averaging the bin counts. This alleviates the problem of the bin origin. e.g., imagine how the number of points in the bin containing the red point changes if the red point is the topleft of the bin or the bottom right of the bin.
library(ash)
bins <- bin2(cbind(x,y))
f <- ash2(bins, m = c(10,10))
image(f$x,f$y,f$z)
contour(f$x,f$y,f$z,add=TRUE)
If you would like smoother bins, you could try increasing the argument m, which is a vector of length 2 controlling the smoothing parameters along each variable.
f2 <- ash2(bins, m = c(10,10))
image(f2$x, f2$y, f2$z)
contour(f2$x,f2$y,f2$z,add=TRUE)
Compare f and f2
The binning algorithm is implemented in fortran and is very fast.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adobe Air - Paste image via context menu
Is there a way to copy an image into an Air app through the context menu (right-click menu) or at least to detect if there is an image within the clipboard?
Thanks
Uli
A:
One strategy would be to check the clipboard on the ACTIVATE event and do something like enable/disable a context menu item based on the result:
private function checkForImageData(e:Event):void {
myContextMenu.clipboardItems.paste = Clipboard.generalClipboard.hasFormat(ClipboardFormats.BITMAP_FORMAT);
}
addEventListener(Event.ACTIVATE, checkForImageData);
| {
"pile_set_name": "StackExchange"
} |
Q:
Performance difference between gcc and g++ for C program
Lets say i have written a program in C and compiled it with both gcc and g++, which compilation will run faster? gcc or g++? I think g++ compilation will make it slow, but not sure about it.
Let me clarify my question again because of confutation about gcc.
Let say i compile program a.c like this on console.
gcc a.c
g++ a.c
which a.out will run faster?
A:
Firstly: the question (and some of the other answers) seem to be based on the faulty premise that C is a strict subset of C++, which is not in fact the case. Compiling C as C++ is not the same as compiling it as C: it can change the meaning of your program!
C will mostly compile as C++, and will mostly give the same results, but there are some things that are explicitly defined to give different behaviour.
Here's a simple example - if this is your a.c:
#include <stdio.h>
int main(void)
{
printf("%d\n", sizeof('x'));
return 0;
}
then compiling as C will give one result:
$ gcc a.c
$ ./a.out
4
and compiling as C++ will give a different result (unless you're using an unusual platform where int and char are the same size):
$ g++ a.c
$ ./a.out
1
because the C specification defines a character literal to have type int, and the C++ specification defines it to have type char.
Secondly: gcc and g++ are not "the same compiler". The same back end code is used, but the C and C++ front ends are different pieces of code (gcc/c-*.c and gcc/cp/*.c in the gcc source).
Even if you stick to the parts of the language that are defined to do the same thing, there is no guarantee that the C++ front end will parse the code in exactly the same way as the C front end (i.e. giving exactly the same input to the back end), and hence no guarantee that the generated code will be identical. So it is certainly possible that one might happen to generate faster code than the other in some cases - although I would imagine that you'd need complex code to have any chance of finding a difference, as most of the optimisation and code generation magic happens in the common back end of the compiler; and the difference could be either way round.
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery validator regex using array or variable
I'm using jquery validator plugin with regex to test match input fields that only accept numbers and decimals from eg: 1.0 to 1.984375(1/64 increments) and it works but the regex is long and I need to reuse it multiple times but with some slight changes to the numbers preceding the decimal point.
I was wondering if there's a way to use an array for the decimal part of the regex, something like this...
var decimals = (\.015625|\.03125|\.046875...)?$
or
var decimals = (\.015625, \.03125, \.046875...)
and then in validator have something like...
regex=/^4+decimal+/
Is something like that possible?
EDIT: I added fractions to plalx code with fraction.js, which can be found here... http://hypervolu.me/~erik/fraction.js/.
var fractionsAll=range(1/64, 63/64, 1/64).map(convertToFraction).join('|');
function convertToFraction(num){
return new Fraction(num)
};
example: 1-10
regexp: new RegExp('^([1-9]|10$)(\\.('+decimalsAll+')|\\s('+fractionsAll+'))?$')
A:
What about something like this? The RegExp constructor allows to construct dynamic regular expressions from a string.
var decimals = range(.015625, 0.984375, 1/64).map(removeDotAndBefore).join('|');
var regex = new RegExp('^4(\\.(' + decimals + '))?$');
function range(from, to, increment) {
var values = [];
for (; from <= to; from += increment) values.push(from);
return values;
}
function removeDotAndBefore(num) {
return num.toString().replace(/^\d+\./, '');
}
Note that you should be able to use the modulo operator to know if a number is dividable by 1/64.
function isOne64Increment(num) { return !(num % (1/64)); }
range(.015625, 0.984375, 1/64).every(isOne64Increment); //true
| {
"pile_set_name": "StackExchange"
} |
Q:
chrome.app.window Alternative
so currently I have a packaged Chrome app, which uses chrome.app.window.create() to create frameless Notifications. Since Chrome Apps will be discontinued in the near future I am currently looking for alternatives.
I am trying now to emulate the same behavior in a Chrome Extension, but I have only found chrome.windows.create() where I can open popups, but they can't be made frameless apparently.
I have also tried chrome.notifications but they are not customizable enough for my needs.
Do any of you guys know a way to do this?
A:
No, that's about it. You can't emulate this behavior with extensions.
Add to that list a possibility to inject DOM in the currently opened page, which you can style, but it's complicated, requires very heavy permissions to do at will at any page, will be confined to the browser viewport and still won't work in some edge cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is Kafka removing the relevant ACL entries automatically when deleting a topic?
When deleting a topic, is Kafka removing related ACL bindings automatically or do I have to manually tidy up?
A:
Kafka does not automatically delete ACLs associated with a resource (Topic, Group, etc) when it is deleted.
If you want the ACLs to be deleted, you have to do it explicitly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way to generate "fake" rows in MySQL result set?
I need this for charting purposes. Basically i have to:
Select all sent SMS by date without time part, getting an array with dates/counts pairs day-by-day;
Add "fake" rows for days without any record in my table, that is filling all dates "gaps" with zeroes.
An example result and corresponding table (here simplified) would be:
array(
'2012-05-26 00:00:00' => 1,
'2012-05-27 00:00:00' => 0, // Fake added row
'2012-05-28 00:00:00' => 2,
)
+----------------+----------------------+
| Table SMS | id | sent_at |
+----------------+----------------------+
| | 1 | 2012-05-26 21:58:41 |
+----------------+----------------------+
| | 2 | 2012-05-28 22:19:21 |
+----------------+----------------------+
| | 3 | 2012-05-28 02:19:21 |
+----------------+----------------------+
Is there any SQL command for doing this or should i do manually playing with PHP arrays?
A:
You can use a UNION Statement
SELECT
sent_at,
Count(*)
FROM (Select
id,
DATE(sent_at) as sent_at
FROM TableName
Group by Date(sent_at)
UNION ALL
Select
'0' as id,
DATE('2012-05-27') as sent_at) derived_table
Group By sent_at
Edited
I suggested creating a special table to join against.
Creation of a datetable for querying
CREATE TABLE DateTable (
DateValue DateTime,
Year Int,
Month Int,
Day Int)
Now populate this table with all date values within the ranges you are querying. You can easily join to this table with any valid date. Allowing you to aggregate for Dates that do and do not exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get all the Parent documents base on child reference Id Mongo and Nodejs
Thank you for your help.
I am scratching my head all day, I don't know I am in the right direction or not.
Problem :
I have a document [Doctor] which contains the reference [doctorSpecialities].
I have to GET ALL DOCTORS who have this id in there doctorSpecialities reference Array
Id : 5ef58dd048cdd203a0c07ba8
JSON Structure
{
"doctorSpecialities": [
"5f00cebc8bcdcd0660c12ce2",
"5ef58dd048cdd203a0c07ba8"
]
"_id": "5ef31ae80399ac05eb23e555",
"email": "[email protected]",
"username": "[email protected]",
"DOB": null,
"zip": null,
"phone": "12657334566",
"PMDC": "7658493",
"isVerified": false,
"aboutMe": "About Me",
"achievements": "Achievements",
"address": "padasdad",
"city": "Lahore",
"gender": "Male",
"managePractice": "Manage Practice",
"practiceGrowth": "Practice Growth",
"qualiflication": "Qualifcation",
"state": "eeeeeeee",
"workExperince": "Work Experince",
"doctorAvailability": [],
"doctorReviews": [],
"degreeCompletionYear": "2019-10-10",
"institute": "institute",
"practiceDate": "2020-10-10",
"services": "Dental"
},
Query tried
await Doctor.find({ doctorSpecialities : req.params.id})
await Doctor.find({ doctorSpecialities :{$in [ req.params.id}})
Specialty Collection
doctorCollection = Doctor.find();
doctorCollection.find({"doctorSpecialities": specialty.id})
This is how I did is it wrong?
I tried to user $Lookup but I don't know how to use it in this requirement
Please let me know if you need more information.
Thank you
A:
If you have to get doctors details then you can use
db.collection.find({"doctorSpecialities":"5ef58dd048cdd203a0c07ba8"})
play
It returns all documents where doctorSpecialities field contains 5ef58dd048cdd203a0c07ba8
| {
"pile_set_name": "StackExchange"
} |
Q:
How invoke method of the object created from C++ in QML?
I need dynamically run JavaScript to operate some C++ object from the simulation.
Example:
class CppToQML : public QObject{
Q_INVOKABLE CppClass* getObj(int i);
QList<CppClass*> mList;
}
First, i have a CppToQML class which is registed into QML.
qmlRegisterType<CppToQML>("CppToQML", 1, 0, "CppToQML");
The CppClass is created in C++ side and stored in CppToQML mList
class CppClass : public QObject {
Q_INVOKABLE void sayHello();
}
I am trying to do this in QML javascript:
CppToQML {
id: cppToQML
}
//javascript
cppToQML.getObj(0).sayHello();
Problem is QML can not recognize CppClass pointer as a data type.
A:
For QML to recognize the class you must register it:
qmlRegisterType<CppClass>("CppToQML", 1, 0, "CppClass");
or:
qmlRegisterType<CppClass>();
| {
"pile_set_name": "StackExchange"
} |
Q:
Regular Expression for TimeSpan in format "hh.mm"
I want to create RegularExpressionValidator for validation TextBox format hh.mm.
This expression works:
^([0-9]|0[0-9]|1[0-9]|2[0-3]).[0-5][0-9]$
But if I insert 5454 in the TextBox it also passes, but it shouldn't.
A:
. is a meta character in regular expressions that matches any character. If you want to match literally just a period, then you need to escape it:
^([0-9]|0[0-9]|1[0-9]|2[0-3])\.[0-5][0-9]$
A:
you forgot to escape .
try
^([0-9]|0[0-9]|1[0-9]|2[0-3])\.[0-5][0-9]$
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.