text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: azure api gateway integration with AKS 502 - Web server received an invalid response while acting as a gateway or proxy server I am in process to integrate Azure API gateway with AKS.
in order to achieve this.
i had
*
*created AKS cluster with advance networking. consider it is in
aks-vnet
*created different vnet for API gateway.
*peer both vnet i.e. vnet for aks and for api gateway.
*created internal load balancer. by
running azure voting app yaml file also added annotation for using
internal load balancer
metadata:
name: azure-vote-front
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal: "true"
*added kubernates internal load balancer public ip in address probe of api gateway.
when i navigate in browser with public ip address of api gateway or dns name associated with api gateway i am getting following error
502 - Web server received an invalid response while acting as a gateway or proxy server.
There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.
A: First, there is something wrong described in your case: You should provide add the kubernetes internal load balancer private IP to the application gateway backend pool.
Then I did the test as the steps in Integrate Application Gateway with AKS cluster. As the error shows that you should make the check if the application in the AKS works fine, in your case the application is azure voting app.
If you follow the Azure Kubernetes Service tutorial and push the image to Azure Container Registry, you must grant the AKS permission to access your ACR. See Authenticate with Azure Container Registry from Azure Kubernetes Service.
And on my side, I can access the azure voting app from the public IP of the application gateway. Hope this will help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54044517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you monitor small changes to an XHR response? I'd like to be alerted to small changes in the responses of a website, which is not my own.. Any suggestions are welcome, thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48969773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not able to set text in a Text Area I was unable to set text into the text area with browser.text_field(:id,"area").set "1=1". When i typed manually i noticed that the text("1=1") i typed is stored across spans as given below.
<pre>
<span class="number">1</span> # the text 1 is stored here and followed by "=1" in next spans
<span class="operator">=</span>
<span class="number">1</span>
</pre>
Is there any other way that i can set text into the text area?
A: This worked for me:
require "watir-webdriver"
browser = Watir::Browser.new
browser.goto "ideone.com"
browser.div(:id => "file_div").textarea.set "1=1"
Are you sure you need to set text in textarea? If you are dealing with wysiwyg editor, you probably need to use send_keys:
browser.pre.send_keys "1=1"
More information: http://watirwebdriver.com/wysiwyg-editors/
A: It is important to send keys on proper element. In my case, after some experimentations, that was:
<div class="redactor_text redactor_optional redactor_redactor redactor_editor" contenteditable="true" dir="ltr" style="min-height: 120px;"></div>
Editor was defined with this html:
<div class="redactor_box"><ul class="redactor_toolbar" id="redactor_toolbar_0"><li><a href="javascript:;" title="Bold" tabindex="-1" class="re-icon re-bold"></a></li><li><a href="javascript:;" title="Italic" tabindex="-1" class="re-icon re-italic"></a></li><li><a href="javascript:;" title="Underline" tabindex="-1" class="re-icon re-underline"></a></li><li><a href="javascript:;" title="Link" tabindex="-1" class="re-icon re-link"></a></li><li><a href="javascript:;" title="Superscript" tabindex="-1" class="re-icon re-superscript fa-redactor-btn"><i class="fa icon-superscript"></i></a></li><li><a href="javascript:;" title="Subscript" tabindex="-1" class="re-icon re-subscript fa-redactor-btn"><i class="fa icon-subscript"></i></a></li></ul><div class="redactor_text redactor_optional redactor_redactor redactor_editor" contenteditable="true" dir="ltr" style="min-height: 120px;"></div><textarea class="text optional redactor" data-limit="450" data-persist="garlic" data-min-height="120" name="lesson[intro]" id="lesson_intro" dir="ltr" style="display: none;"></textarea></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15356852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Efficient Dictionary change value or add (key,value) if not in dictionary Suppose I have a Dictionary<TKey, TValue>, where TValue is a reference type.
I want to assign TValue myNewValue to the element with TKey myKey. If there is no element with myKey, I want to add it.
I want to do this efficiently with a minimal GetHashCode():
private void AddOrReplace(TKey key, TValue value)
{
Dictionary<TKey, TValue> myDictionary = GetMyDictionary(...);
TValue existingValue;
if (myDictionary.TryGetValue(key, out existingValue))
{ // key already in dictionary
existingValue = value;
}
else
{ // key not in dictionary yet
myDictionary.Add(key, value);
}
}
This way, TKey.GetHashCode() is called once if the key already exist, but it is called twice if the key must be added.
However this wouldn't work if TValue is a value type
existingValue = value; // wrong! won't change the value in the dictionary
Code ought to be something like:
private void AddOrReplace(TKey key, int value)
{
Dictionary<TKey, int> myDictionary = GetMyDictionary(...);
if (myDictionary.ContainsKey(key)
{ // key already in dictionary
myDictionary.key = value;
}
else
{ // key not in dictionary yet
myDictionary.Add(key, value);
}
}
This way TKey.GetHashCode() is always called twice.
Isn't there a more efficient method, where TKey.GetHashCode is only called once?
A: Dennis_E and Panagiotis Kanavos provided the answer. Thanks both of you.
I just add it here, in case someone thinks he has the same problem.
System.Collections.Generic.Dictionary.Item property (TKey) Describes it as follows:
Property Value
Type: TValue
The value associated with the specified key.
*
*get If the specified key is not found, a get operation throws a KeyNotFoundException,
*set a set operation creates a new element with the specified key.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33343543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Showing xdebug with firefox 29.0 Since the latest update with firefox i can't seem to find my Xdebug.
I have tried going to Show->tools
but they changed the way you add the developer line.
Has anyone experianced the same and know how to show the bottom line where you enable / disable xdebug?
A: Update:
With the last update it disappeared almost everything :-)
Now there is an add-on toolbar hidden by default.
If not over there you can search in the upper right corner where there is a button with the tooltext "Open Menu" (3 horizontal lines). When you press the button it appears a panel, if you select customize on the bottom it will open a page with Additional tools and features. I find over there some of the add-on that I installed.
Original:
Did you refer to the bar that appear with Shift + F2 ?
Under Tools-->Web Developer there is the list of tools directly available.
with Crtl + Shift + S you enable the debugger
with Ctrl + Shift + I you toggle the tools panel
A: this is a working add on for xdebug -- firefox 29..
https://addons.mozilla.org/en-US/firefox/addon/easy-xdebug-with-moveable-/?src=api
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23456654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: In Ruby on Rails, is there a way to check the order of the rows in a table using RSpec/Capybara for views testing? I have a table with numerous rows. These rows are ordered specific to the data within them. I am looking to write tests for the order of the rows in the table. Is there a way to do this using RSpec/Capybara?
A: You can try use xpath selectors, for example
within(:xpath, "//table/tr[1]/td") do
page.should have_content('First row content')
end
within(:xpath, "//table/tr[2]/td") do
page.should have_content('Second row content')
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11029646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Codeigniter Insert Multiple Fields Using Foreach Loop I have a problem when I want to insert multiple fields which are using foreach loop (to get the value form database), here is my form:
<form class="stdform" action="<?php echo $action_url; ?>" method="post">
<label>Check Date</label> <input class="span3" type="text"
id="datepicker" name="check_date" value="" required="required"
placeholder="Tanggal cek" />
<table class="table table-condensed table-hover table-bordered"
style="font-size: 12;">
<thead>
<tr>
<th class="head0">#</th>
<th class="head0">Device</th>
<th class="head0">IP Address</th>
<th class="head0">NAT IP Address</th>
<th class="head0">Check OS</th>
<th class="head0">Application/Server</th>
<th class="head0">Shift A</th>
<th class="head0">Shift B</th>
<th class="head0">Remark</th>
<th class="head0">Report</th>
</tr>
</thead>
<tbody>
<!-- Row Template -->
<?php
$num=1;
foreach( $get_server_assets as $row ) {
?>
<tr>
<td>
<?php echo $num; ?>
</td>
<td><input class="span12" type="text" name="device[]"
value="<?php echo $row->s_device; ?>" /></td>
<td><input class="span9" type="text" name="ip_address[]"
value="<?php echo $row->s_ip; ?>" /></td>
<td><input class="span9" type="text" name="nat_ip[]"
value="<?php echo $row->s_nat_ip; ?>" /></td>
<td><select class="span12" name="check_os[]">
<option value=""></option>
<option value="Good">Good</option>
<option value="Not Good">Not Good</option>
</select></td>
<td><input class="span10" type="text" name="app_name[]"
value="<?php echo $row->app_server; ?>" /></td>
<td><select class="span12" name="check_app_a[]">
<option value=""></option>
<option value="Good">Good</option>
<option value="Not Good">Not Good</option>
</select></td>
<td><select class="span12" name="check_app_b[]">
<option value=""></option>
<option value="Good">Good</option>
<option value="Not Good">Not Good</option>
</select></td>
<td><input class="span12" type="text" name="remark[]" value="" /></td>
<td><input class="span12" type="text" name="report[]" value="" /></td>
</tr>
<?php $num++; } ?>
</tbody>
</table>
<p class="stdformbutton">
<button class="btn btn-primary btn-large" type="submit" name="submit"
value="true">Submit</button>
<a class="btn btn-large" onclick="window.history.back()">Cancel</a>
</p>
</form>
And here is my controller:
$data = array();
$count = count($this->input->post('device'));
for($i=0; $i<$count; $i++) {
$data[] = array(
'check_date'=>$this->input->post('check_date'),
'device'=>$this->input->post('device' . $i),
'ip_address'=>$this->input->post('ip_address' . $i),
'nat_ip'=>$this->input->post('nat_ip' . $i),
'check_os'=>$this->input->post('check_os' . $i),
'app_name'=>$this->input->post('app_name' . $i),
'check_app_a'=>$this->input->post('check_app_a' . $i),
'check_app_b'=>$this->input->post('check_app_b' . $i),
'remark'=>$this->input->post('remark' . $i),
'report'=>$this->input->post('report' . $i),
);
}
$this->db->insert_batch('server_checklist',$data);
/*foreach($_POST['data'] as $d) {
$this->db->insert('server_checklist',$d);
} */
redirect('admin/viewServerChecklist');
When I submit there is no data insert, only check_date stored. And the rest give value 0.
Click here for image
Can someone help me??
A: try this, instead of appending, try to access the index of the array.
$data[] = array(
'check_date'=>$this->input->post('check_date'),
'device'=>$this->input->post('device')[$i],
'ip_address'=>$this->input->post('ip_address')[$i],
'nat_ip'=>$this->input->post('nat_ip')[$i],
'check_os'=>$this->input->post('check_os')[$i],
'app_name'=>$this->input->post('app_name')[$i],
'check_app_a'=>$this->input->post('check_app_a')[$i],
'check_app_b'=>$this->input->post('check_app_b')[$i],
'remark'=>$this->input->post('remark' )[$i],
'report'=>$this->input->post('report')[$i],
);
A: Try This:
$data_table = $this->input->post(NULL, TRUE);
if (empty($data_table['device']))
{
redirect('admin/viewServerChecklist?message=error');
}
$required = array('device', 'ip_address', 'nat_ip', 'check_os', 'app_name', 'check_app_a', 'check_app_b', 'remark', 'report');
$data = array();
foreach ($data_table['device'] as $key => $value)
{
// check list table. if value required not exist. continue to next index
$row = array();
foreach ($required as $key2 => $value2)
{
if (!isset($data_table[$value2][$key])) continue;
$row[$value2] = $data_table[$value2][$key];
}
// since check_date is not array. we need to parse to row data
$row['check_date'] = $data_table['check_date'];
$data[] = $row;
}
$this->db->insert_batch('server_checklist', $data);
/*foreach($_POST['data'] as $d) {
$this->db->insert('server_checklist',$d);
} */
redirect('admin/viewServerChecklist');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33034933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will #if __IPHONE_4_0 work on iPad? Will this check work on the iPad as well as iPhone? I guess I am just confused about using the term "iPhone" on an iPad. Is there something else I need to check for iPad OS version or does the macro refer to the general iOS version.
#if __IPHONE_4_0
// Do stuff
#elif __IPHONE_3_0
// Do 3.0 stuff
#endif
A: The problem with __IPHONE_3_0 and the like is that they are defined even if targeting other iOS versions; they are version identification constants, not constants that identify the target iOS version. Use __IPHONE_OS_VERSION_MIN_REQUIRED
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
#elif __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_0
#else
#endif
or even:
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
#elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000
#else
#endif
to get around the bug mentioned in the comments for "How to target a specific iPhone version?" __IPHONE_OS_VERSION_MAX_ALLOWED might also be of use, in limited circumstances.
And, yes, it doesn't matter what device the app will run on. These constants are defined by the compiler and don't exist on the devices. Once the pre-processor runs, no macros are left. Though there are differences in the devices themselves, the iPhone and iPad both run iOS, and that's what you're really targetting.
A: The code you posted is a compiler directive. This means that it will not run on iPad or iPhone. It is handled when you build your app binary. Incidentally, if you're building for iPad, then you are building for 3.2, not 3.0 or 4.0.
If you use 3_2 or 4_2 instead of 3_0 or 4_0 it should work.
Good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3955331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Acces denied error when I use firewall.dll propertry . (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) I have code that use firewall.dll to add a rule to windows firewall but i get this exception"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
this is my code:
using NetFwTypeLib;
namespace Tserver
{
class Program
{
static void Main(string[] args)
{
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Used to block all internet access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "Block Internet";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
}
A: You need to have admin rights to do what you're doing.
I've had the same problem a client machine, but as soon as I tried to do the same thing on a machine with administrator rights (Windows 7), everything worked perfectly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22954548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Gauge/chart that "fills" an image rather than a plain circle I am trying to create a donut chart/gauge, that illustrates a % amount of something. This value will increase over time, until at somepoint its full/complete
However, the complexity is that instead of just a plain circle/donut shape, I want to illustrate a circle pattern being filled up as the value increases.
Below is an example of a highcharts gauge filled to 25%.
Fiddle Example
See Fiddle Example
And below is a picture (based on a random design from Shutterstock), of the effect I am attempting to achieve.
Would drawing this with SVG be the best way to do it, or is there a better way?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42485273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Plot both multi-index labels on x-axis in pandas plot I have a multi-index dataframe and would like to both index as x-axis labels. Where each of the "forecasts" index1 is listed as below, but want "year" index[0] to be shown instead of the x-axis label "forecast", so each panel would show the year index: 2020, 2050, 2099 below the forecast names. I am also trying to place labels above each bar with the values from the "most important observation" column.
def plot_function(x, ax):
ax = graph[x]
ax.set_xlabel(x, weight='bold')
return df_par_trans.xs(x).plot(kind='bar', stacked='False', ax=ax, legend=False)
n_subplots = len(df_par_trans.index.levels[0])
fig, axes = plt.subplots(nrows=1, ncols=n_subplots, sharey=True, figsize=(14, 8))
graph = dict(zip(df_par_trans.index.levels[0], axes))
plots = list(map(lambda x: plot_function(x, graph[x]), graph))
ax.tick_params(axis='both', which='both', length=0)
fig.subplots_adjust(wspace=0)
plt.legend()
plt.show()
my dataframe looks like this:
year forecast most important observation percent increase when left out
2020 PV6SM Harkins 17.371021
2050 PV6SM Harkins 10.569719
2099 PV6SM Harkins 12.343476
2020 PV3S PV3S 34.095863
2050 PV3S PV3S 32.565513
2099 PV3S PV3S 26.110555
A: You need to rename the index with the year:
groups = df.groupby("year")
fig, axes = plt.subplots(1, len(groups), sharey=True, figsize=(14,8))
for ax, (year, group) in zip(axes, groups):
# The rename_axis function makes the difference
group.set_index("forecast").rename_axis(year)["percent increase when left out"].plot(kind="bar", ax=ax)
ax.tick_params(axis='both', which='both', length=0)
ax.legend()
fig.subplots_adjust(wspace=0)
Output:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74062380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Facebook sharing not scraping url correctly in Codeigniter I am trying to share on facebook but didn't get meta data. Also i have try in facebook debug tool but didn't get meta data.
facebook debug tool url https://developers.facebook.com/tools/debug/
I have already added meta data. Bellow meta data and url.
<meta property="og:title" content="Afrocamgist" />
<meta property="og:type" content="article" />
<meta property="og:image" content="https://www.afrocamgist.com/public/campus_post/Screenshot_20180815-132503.png" />
<meta property="og:description" content="Good morning famz!" />
<meta property="og:url" content="https://www.afrocamgist.com/" />
<meta property="og:site_name" content="Afrocamgist" />
<meta property="fb:app_id" content="300434940539027" />
URL : https://www.afrocamgist.com/post/single/434
Please help me. Thanks.
A: Solve issue, Actually problem with protected page. My page is open after user login.
I have a remove permission and publish to solve my issue.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52071257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery increase data attribute value for each items I'm trying to make a jQuery program that increases the data attribute value for each list item.
var current = 0;
$(".kunde-logo-listing").each(function() {
$(this).attr("data-wow-delay", current);
current++;
});
I tried to use the above and the output is as follows:
data-wow-delay="0"
data-wow-delay="1"
data-wow-delay="2"
data-wow-delay="3"
data-wow-delay="4"
But the output I'm trying to get should be:
data-wow-delay="000ms"
data-wow-delay="100ms"
data-wow-delay="200ms"
data-wow-delay="300ms"
data-wow-delay="400ms"
Anyone got an idea how to make this work? Is it something with concatenating the value to a string of "ms" ?
Cheers!
A: var current = 0;
$(".kunde-logo-listing").each(function() {
$(this).data("wow-delay", current+"00ms");
current++;
});
A: You can use this as follows:
var current = 0;
$(".kunde-logo-listing").each(function () {
$(this).data("wow-delay", current++ * 100 + "ms");
// ^^^^^^^^^^^^^^^^^^^^^^^
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30166619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TableView not updating after button action I'm relatively new to swift, and I'm trying to have a view that when it loads it will display some info on my tableView, then in the same view I have a textfield and a button
I want that the button performes an action that fetchs data from my server and updates my tableView
The problem is that the table is not being updated. How can I get the table to be updated?
CODE:
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 80;
tableView.tableFooterView = UIView();
self.url = URL(string: "http://xxxxxxxx.com/xxxxx/api/produtos/listagem/favoritos/\(userID)");
downloadJson(_url: url!);
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return produtos.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProdutoCell1") as? ProdutoCell else{
return UITableViewCell()
}
cell.lbl_nome_json.text = produtos[indexPath.row].nome;
cell.lbl_categoria_json.text = produtos[indexPath.row].categoria;
cell.lbl_loja_json.text = produtos[indexPath.row].loja
//= produtos[indexPath.row].categoria;
// cell.lbl_loja.text = produtos[indexPath.row].loja;
if let imageURL = URL(string: "http://xxxxxxxxxx.com/myslim/api/"+produtos[indexPath.row].url){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL);
if let data = data{
let image = UIImage(data: data);
DispatchQueue.main.async {
cell.imgView_json.image = image;
}
}
}
}
return cell;
}
ACTION:
@IBAction func btn_search(_ sender: Any) {
if self.txt_search.text == "" {
let alert = UIAlertController(title:"Alert",message: "Insira algo para pesquisar",preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: nil))
self.present(alert,animated: true,completion: nil)
}else{
var pesquisa = String();
pesquisa = self.txt_search.text!;
let url2 = URL(string: "http://xxxxxxxx.com/xxxxxx/api/produtos/listagem/favoritos/\(pesquisa)/\(self.userID)");
downloadJson(_url: url2!);
}
func downloadJson(_url: URL){
guard let downloadURL = url else {return}
URLSession.shared.dataTask(with: downloadURL){data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else{
print("algo está mal");
return;
}
do{
let decoder = JSONDecoder();
let downloadedProdutos = try decoder.decode([ProdutoModel].self, from: data);
self.produtos = downloadedProdutos
print(downloadedProdutos);
DispatchQueue.main.async {
self.tableView.reloadData();
print("reload");
}
}catch{
print("algo mal depois do download")
}
}.resume();
}
EDIT
I added some print to see how many object were being returned on my downloadedProdutos variable, on the downloadJson() function.
And at the viewdidload I get 2 object, its normal because I only have 2 Products, but when the action is done I still get 2 object although I should get only 1 object
A: You need to set tableView.dataSource = self in viewWillAppear and it looks you missed func numberOfSections() -> Int method.
Add UITableViewDataSource like this
class YourViewController: UIViewController, UITableViewDataSource and it will recommend you required methods
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56516965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I am writing a program to find number of 3's in factorial of a given number. The input from the user is the number I am using this logic. Suppose I have to find number of 3's in 10!. Thenenter image description here
import java.util.*;
import java.io.*;
class testing
{
public static void main(String args[])
{
int temp=0,a;
Scanner obj = new Scanner(System.in);
System.out.print("Enter the number ");
int n = obj.nextInt();
int i=1;
while(n<(Math.pow(3,i)))
{
a= n/(int)(Math.pow(3,i));
temp=temp+a;
i++;
}
System.out.println("Answer: " +temp);
}
}
A: *
*change < to > in if condition as
n >(Math.pow(3,i))
*or use below code which calculates pow only once
int temp = 0, a;
Scanner obj = new Scanner(System.in);
System.out.print("Enter the number ");
int n = obj.nextInt();
int i = 1;
while (true) {
int pow = (int) Math.pow(3, i);
if (pow > n) {
break;
} else {
temp = temp + n / pow;
}
i++;
}
System.out.println("Answer: " + temp);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33316690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Migration 6i to 10g Oracle reports I have problems with reports when migrating from 6i to 10g. Everything works fine except when a report is opened from another report. I am getting an error-
REP-56107: Invalid environment id myenv for Job Type report in the command line
I only get this error when I try to open a report from another report. My Oracle version is Oracle 10.2.0.4.
A: I think the defaultEnvId attribute for the environment is set incorrectly in your server_name.conf file. Typically the defaultEnvId would look something like below-
<engine id="rwEng" initEngine="1" minEngine="0" maxEngine="10" engLife="50" maxIdle="30" defaultEnvId="JP"/>
And consecutively the definition as-
<environment id="JP">
<envVariable name="NLS_LANG" value="Japanese_Japan.JA16SJIS"/>
<envVariable name="NLS_CURRENCY" value="¥"/>
<envVariable name="DISPLAY" value="MyServer.MyCompany.com:0.0"/>
</environment>
I am assuming that your file has the defaultEnvID="myenv" and <environment id="myenv">. Check this to make sure it points to the right environment. Make sure that the defaultEnvId in enginedefinition matches the environment definition. Also, keep in mind that this is an optional setting so you may or may not need this. See this for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12565634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Tensorflow / keras issue when optimizing with optuna I'm pretty new to machine learning, I've been trying to teach myself neural networks from following sentdex tutorials. I followed his tutorial on using recurrent neural networks for predicting the price of various crypto-currencies and succeeded after changing NumPy arrays and some of the syntax. Now I've been trying to add optimization to it since I've noticed just how drastically overfitting can change with tweaking the learning rate and layers of the network.
The code of the one that works with no errors is this one
https://colab.research.google.com/drive/1VNeRLeGBByEIdMVwXcbsOR8xjWwsHHoQ?usp=sharing
It looks like I just copied and pasted the code but this is just because I was troubleshooting the code and I just referencing this one with the one I followed from the tutorial and then continued with this one after I got it working.
I've been trying to follow the tutorials for optuna and code I found for optimizing networks online so I'm trying to add it from these sources
https://github.com/optuna/optuna/blob/master/examples/tensorflow/tensorflow_eager_simple.py
https://github.com/optuna/optuna/blob/master/examples/keras/keras_integration.py
https://colab.research.google.com/drive/1-tANR7FopTX_ipAUCJmfZ2h_-iu3ljD_?usp=sharing
and what I'm trying to make is this
https://colab.research.google.com/drive/1cgnz7XUwnhfBvsA9whCXKQ3PrRs_sddh?usp=sharing
this is where I'm getting errors. At first, when I was making this post I was stuck on
ValueError: Shapes (None, 1) and (None, 50, 2) are incompatible
but then I remembered that in the one I followed the tutorial on I needed one recurrent layer without
return_sequences=True before I continued with Dense layers
so I tried to add another recurrent layer without returning sequences and now I'm getting this
ValueError: Input 0 of layer lstm_20 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 2)
I'm not entirely certain where to go from here. I feel like I'm just doing something stupid, I was stuck on trying to figure out how to use a convolutional neural network from a tutorial on my own images for a year because I was reshaping instead of resizing the pictures. I hope it's something simple like that.
Thanks for all your guy's help, you guys have been very helpful since I've started my programming journey.
A: I believe the issue was in building the model using optuna. After several errors and fixing a lot of issues, I got it all working. If anyone's interested here's the section relevant to the errors I was getting.
def create_model(trial):
# We optimize the numbers of layers, their units and weight decay parameter.
n_layers = trial.suggest_int("n_layers", 3, 20)
weight_decay = trial.suggest_float("weight_decay", 1e-100, 1e-1, log=True)
lr = trial.suggest_float("lr", 1e-12, 1e-1, log=True)
momentum = trial.suggest_float("momentum", 0.0, 1.0)
model = tf.keras.Sequential()
#model.add(Dropout(0.1))
for i in range(n_layers):
dropout = trial.suggest_float("dropout_l{}".format(i), 0.05, 0.5)
num_hidden = trial.suggest_int("n_units_l{}".format(i), 32, 256, log=True)
model = Sequential()
model.add(LSTM(num_hidden, input_shape=(train_x.shape[1:]), return_sequences=True))
model.add(Dropout(rate=dropout))
model.add(LSTM(num_hidden))
model.add(Dropout(rate=dropout))
model.add(Dense(num_hidden, activation='relu'))
model.add(Dropout(rate=dropout))
model.add(tf.keras.layers.Flatten())
model.add(Dense(
num_hidden,
activation="relu",
kernel_regularizer=tf.keras.regularizers.l2(weight_decay)
)
)
model.add(Dense(2, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2(weight_decay)))
#tf.keras.layers.Dense(2, kernel_regularizer=tf.keras.regularizers.l2(weight_decay)))
# Compile model.
model.compile(
optimizer=tf.keras.optimizers.SGD(lr=lr, momentum=momentum, nesterov=True),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
and if you want to see all of the code for it here's what I have so far, needs a lot of tidying up but it works. Any advice is greatly appreciated.
https://colab.research.google.com/drive/1cgnz7XUwnhfBvsA9whCXKQ3PrRs_sddh?usp=sharing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66604036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: PHP: Unable to decrypt AES 128 CBC I have a string encrypted in AES 128 + Zero Padding + IV and CBC mode.
*
*About zero padding, if the length is not 128bit, the encryption will
fill the remaining part 0x00 and reach 128 bit.
*An IV value can be specified successfully only if both IV value and IV value confirm are set to the same value
*The default value is all 0x00
*So The Password exampl= ** bit + ** zeros
I've tried too many things to decrypt this, like
function decrypt($data, $key)
{
$encryption_key = base64_decode($key);
list($encrypted_data, $iv) = array_pad(explode('::', base64_decode($data), 2), 2, null);
return openssl_decrypt($encrypted_data, 'aes-128-cbc', $encryption_key, 0, $iv);
}
I tried too many other things, nothing works, what am I doing wrong? I am using "exampl", as the key.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66108947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CommandButton action: use value of inputText as parameter in dynamic URL I need to make a small form where user types a number into the inputField, and clicks on a button, then is sent to a page, using that number as a parameter to the page.
So far I got into this:
<p:inputText id="myText" style="width:75px;" />
<p:commandButton id="myButton" value="Ir"
action="/site/page.xhtml?id=${param['form:myButton']}"
title="Ir" ajax="false" proces="@this,myText" />
tried with ${param['form:myButton']} and #{param['form:myButton']}, error is the same.
Problem is, JSF thinks its a method expression...
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/intranet] threw exception [/myPage action="/site/page.xhtml?id=${param['form:myButton']}".xhtml @95,41 action="/site/page.xhtml?id=${param['form:myButton']}" Not a Valid Method Expression: action="/site/page.xhtml?id=${param['form:myButton']}" with root cause
javax.el.ELException: Not a Valid Method Expression: action="/site/page.xhtml?id=${param['form:myButton']}"
at org.apache.el.lang.ExpressionBuilder.createMethodExpression(ExpressionBuilder.java:236)
at org.apache.el.ExpressionFactoryImpl.createMethodExpression(ExpressionFactoryImpl.java:55)
at org.jboss.weld.util.el.ForwardingExpressionFactory.createMethodExpression(ForwardingExpressionFactory.java:43)
at org.jboss.weld.el.WeldExpressionFactory.createMethodExpression(WeldExpressionFactory.java:64)
at com.sun.faces.facelets.tag.TagAttributeImpl.getMethodExpression(TagAttributeImpl.java:222)
at com.sun.faces.facelets.tag.jsf.ActionSourceRule$ActionMapper2.applyMetadata(ActionSourceRule.java:104)
at com.sun.faces.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:81)
at javax.faces.view.facelets.MetaTagHandler.setAttributes(MetaTagHandler.java:129)
at javax.faces.view.facelets.DelegatingMetaTagHandler.setAttributes(DelegatingMetaTagHandler.java:102)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.doNewComponentActions(ComponentTagHandlerDelegateImpl.java:402)
and this is the bottom-most exception trace.
Question: how can I pass the value typed into of the input-field into the action of the Button when the button is clicked, so the browser navigates to the desired page passing the value in the input as a parameter, without resorting to a backing bean.
I don't need to communicate with the server, just forward the page.
any solution using jQuery or plain javascript in tandem with JSF is acceptable too.
using mojarra, primefaces 3.3.1
A: use <f:param> It's explained in this article from BalusC http://balusc.blogspot.in/2011/09/communication-in-jsf-20.html#ProcessingGETRequestParameters
A: I do not need a bazooka to kill a mouse. The answer is very simple.
bind a javascript function to the onclick of the button, and in that function, retrieve the value of the input field by its id, then assemble URL with the parameters and navigate away from within the javascript function.
JSF code (assume they are inside a form with myForm as its id):
<p:inputText id="myInput" style="width:75px;" />
<p:commandButton id="myButton" value="Ir" onclick="navega();" title="Ir" ajax="false" proces="@none" />
Javascript script, declared on a separate file or later on in the xhtml document:
function navega() {
var submittedInputValue = $('#myForm\\:myInput').val();
window.location.href = "/site/mypage.xhtml?param1=whatever&id=" + submittedInputValue ;
}
Take note of the prepend id (myForm:myInput), of using \\ to escape the : in jQuery, and using & instead of & in the xhtml so its not treated as an entity.
Note: probably not all of those commandButton attributes are required, feel free to edit this answer and remove the useless ones.
EDIT: removed the submit and changed process to @none on the command button.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15093790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: same session use in zf1 , zf2 project I have two application in zf1 and zf2 on save server, I have created login system in zf2, when i login zf2 it working fine.
Now i want to access zf2 session in zf1, it showing
[zf2_auth] => __PHP_Incomplete_Class Object
(
[__PHP_Incomplete_Class_Name] => Zend\Stdlib\ArrayObject
)
How can resolve this i want to run both zf1 & zf2 application run on same session.
Here is directory structure for my project
project
--project/zf1_project
--project/zf2_project
Some times i manually create session in zf1 than run zf2, i have unable to get session as i want in zf2.
Any way by which i can use same login/Auth for both zf1 & zf2 application
Thanks in Advance...
A: ZF use object for store session. When start session, php try unserialize $_SESSION variable and if not found object's class PHP create __PHP_Incomplete_Class Object.
You should start session after classes autoload
Set session.auto_start=0 for fix it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43039503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Chrome notifications API img I'm trying to fire a chrome notification ( in a chrome extension ) with the following code:
var opt = {
type: "basic",
title: "Deploy",
message: "It worked!",
iconUrl: "test.png"
};
chrome.notifications.create("", opt, function(id) {
//console.error(chrome.runtime.lastError);
});
But it shows me the following message :
"Unchecked runtime.lastError while running notifications.create: Unable to successfully use the provided image. "
My image "test.png" is in the root folder of my app( with the manifest.json file ), but I've tried to put the picture also in other folder of my app, it never worked!
I've correctly added the permission for notifications, so I really don't know where the problem is !
Any ideas ?
Thank you,
EDIT: I found the solution ! The image needed to be 80*80 !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24146038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Redis NOAUTH authentication required error kubernatives We are getting error NOAUTH Authentication required when deploying in kubernatives cluster.
we need to remove the password which has set automatically. but we don't know from where to change as no config file is there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74150185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TestNG - can't get @Factory to work Trying to learn how to use @Factory, but when I execute it in one of two ways, i get either an error or no tests get executed at all. I am invoking the XML file in Eclipse, by right-clicking on it, and selecting "Run As TestNG Suite".
With this XML file, the suite executes, but zero tests are picked up/executed:
<suite name="suite1" verbose="5">
<test name="test1">
<classes>
<class name="qa.tests.MyFactory"/>
</classes>
</test>
</suite>
With this XML file, i get a test failure with an exception:
<suite name="suite1" verbose="5">
<test name="test1">
<packages>
<package name="qa.tests" />
</packages>
</test>
</suite>
Error:
Can't invoke public void qa.tests.MyTest.testSample1(): either make it static or add a no-args constructor to your class
MyFactory.java class:
package qa.tests;
import org.testng.annotations.Factory;
public class MyFactory {
@Factory
public Object[][] dp() {
Object[][] data = new Object[][] {
{ "1", "TestCase1", "Sample test 1" },
{ "2", "TestCase2", "Sample test 2" },
{ "3", "TestCase3", "Sample test 3" }
};
return data;
}
}
MyTest.java class:
package qa.tests;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class MyTest {
private String num;
private String name;
private String desc;
public MyTest(String num, String name, String desc) {
this.num = num;
this.name = name;
this.desc = desc;
}
@Test()
public void testSample1() {
System.out.println(num + ", " + name + ", " + desc);
assertTrue( true );
}
}
What in the world am I doing incorrectly?
A: First of all ,a Factory should return a one dimension Object array.
And that factory method should return instances of the test class that you are trying to execute.
So the factory will run your tests, if you change to this
public class MyFactory {
@Factory
public Object[] dp() {
Object[] data = new Object[] {
new MyTest("1", "TestCase1", "Sample test 1"), new Mytest("1", "TestCase1", "Sample test 1"), new MyTest("1", "TestCase1", "Sample test 1")
};
return data;
}
}
A: As per this error : either make it static or add a no-args constructor to your class,
Your MyTest class need to have public no-args contructor, Java will not add the default constructor as you already have parametrized constructor, i.e public MyTest(String num, String name, String desc)
UPDATE
change your factory class
public class MyFactory {
@DataProvider(name = "MyData")
public static Object[][] dp(ITestContext context, Method m) throws Exception {
return new Object[][] { new Object[] { "1", "TestCase1", "Sample test 1" }};
}
@Factory(dataProvider = "MyData")
public Object[] createInstances(String num, String name, String desc) {
return new Object[] { new MyTest(num, name, desc) };
}
}
A: //Factory class supplying data to test
public class DataFactory {
@Factory
public Object[] DataSupplier(){
Object[] testData = new Object[3];
testData[0] = new FactoryTest(1);
testData[1] = new FactoryTest(2);
testData[2] = new FactoryTest(3);
return testData;
}
}
//Test class
public class FactoryTest {
int i;
public FactoryTest(int i) {
this.i = i;
}
@Test
public void f() {
System.out.println(i);
}
}
Testng.xml
<suite name="Suite">
<test name="Test">
<classes>
<class name="factorydata.DataFactory"/>
</classes>
</test> <!-- Test -->
</suite>
Datafactory class supplies the test data by creating instances of the test class and passing parameters to FactoryTest class constructor.
FactoryTest class consumes the data from the datafactory.
In the testng.xml refer the class which has factory , in this case it is DataFactory.
This explains a simple working TestNg Factory annotation usage.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30580484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cypress: Using cy.intercept() to check if a call hasnt been made yet? Using cy.intercept() to intercept (and stub) a couple of network requests (to google tag manager), but would like to test at an early point in my test before I expect them to be called.
How would I test that the 2 routes I'm intercepting haven't been called yet?
Thanks!
A: You could take advantage of the cy.spy command:
cy.intercept('/my-route', cy.spy().as('myRequest'));
// later in the test
cy.get('@myRequest').should('not.have.been.called'); // not yet intercepted
// something triggers the API call
cy.get('@myRequest').should('have.been.calledOnce'); // now is intercepted
See: https://docs.cypress.io/api/commands/spy
Credits to: https://glebbahmutov.com/blog/cypress-tips-and-tricks/#check-if-the-network-call-has-not-been-made
A: Intercept has a routeHandler section which can be a function
cy.intercept(routeMatcher, routeHandler?)
routeHandler (string | object | Function | StaticResponse)
The function receives the request, and inside that another function can receive the response,
see Intercepting a response
cy.intercept('/integrations', (req) => {
// req.continue() with a callback will send the request to the destination server
req.continue((res) => {
// 'res' represents the real destination response
// you can manipulate 'res' before it's sent to the browser
})
})
so either on the receipt of req or the inner function on receipt of res, set an external flag and test it at one or more places in the test,
// top of the test
let interceptFlag = false;
cy.intercept('/my-route', (req) => {
interceptFlag = true;
req.continue((res) => {
// or here
interceptFlag = true;
})
})
// later in the test
cy.wrap(interceptFlag).should('eq', false); // not yet intercepted
// something triggers the API call
cy.wrap(interceptFlag).should('eq', true); // now is intercepted
This is very generalized, if you post some details can be more specific.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67276632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to use google calendar API for personnel project (Without verification) I'am using google calendar API on my personal project for creating events through python.But the problem is its asking to verify app by giving privacy policy details (Otherwise the token would expire after 7 days),which i think is overkill for a personnel project .Here iam using my own account and accessing my own data.So is there any way that i can use google calendar API without verification,like for my own account.Or is it not possible to do so without verification.Or is there any other libraries to do the same thing,I just need to set events on my calendar Programmatically.Please help me!
A: What you want to do is create a "service account". Then you want create a new calendar for your (not the service account) calendar. Next, you share your new calendar with the service account by adding it under the "Share with specific people" section. Take note of the "Calendar ID" for this new calendar.
Now when you use the api you should add events from your service account to the new calendar by passing the calendar id as the calendarId.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70912001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: While loop condition in calculating square root using Newton-Raphson method I'm currently taking a course where the instructor used the following code to implement the square root functionality in Java -
public class Sqrt {
public static void main(String[] args) {
// read in the command-line argument
double c = Double.parseDouble(args[0]);
double epsilon = 1.0e-15; // relative error tolerance
double t = c; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision is achieved
while (Math.abs(t - c/t) > epsilon*t) {
t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
}
}
However, if I slightly change the while loop condition to while (Math.abs(t - (c / t)) >= epsilon) instead of while (Math.abs(t - (c / t)) >= t * epsilon), the program gets stuck on an infinite loop for some inputs like 234.0.
I used the Eclipse debugger and found that my code after a certain point returns a value of t that is close to the square root of 234, but still greater than EPSILON. And using the update formula, yields the same value of t after every iteration, hence the loop gets stuck there forever.
Can someone explain as to why the program fails when using >= EPSILON but works perfectly fine when using >= t * EPSILON? As per my understanding, given the extremely small value of EPSILON, t * EPSILON shouldn't eventually be too different than EPSILON, yet the difference is huge when implemented in the program.
A: You can actually use a debugger to see how the numbers progress and why for example the square root of 234 causes an unending loop when epsilon is not multiplied by t.
I have used IntelliJ with a logging breakpoint to see how the numbers progress and why the unending loop happens:
First I have used this expression in the logging breakpoint:
" " + Math.abs(t - c/t) + " " + epsilon
for this code:
private static void calcRoot(String arg) {
// read in the command-line argument
double c = Double.parseDouble(arg);
double epsilon = 1.0e-15; // relative error tolerance
double t = c; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision is achieved
while (Math.abs(t - c/t) > epsilon ) {
t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
}
and this is the result proving that actually epsilon is smaller than Math.abs(t - c/t) and this Math.abs(t - c/t) stops in its progression:
233.0 1.0E-15
115.50851063829788 1.0E-15
55.82914775415816 1.0E-15
24.47988606961853 1.0E-15
7.647106514310517 1.0E-15
0.927185521197492 1.0E-15
0.014043197832668497 1.0E-15
3.2230278765865705E-6 1.0E-15
1.723066134218243E-13 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
1.7763568394002505E-15 1.0E-15
...
If I then use epsilon * t I and update the logging expression to " " + Math.abs(t - c/t) + " " + epsilon * t I can see a totally different console output:
233.0 2.34E-13
115.50851063829788 1.175E-13
55.82914775415816 5.974574468085106E-14
24.47988606961853 3.1831170803771985E-14
7.647106514310517 1.959122776896272E-14
0.927185521197492 1.5767674511807463E-14
0.014043197832668497 1.5304081751208715E-14
3.2230278765865705E-6 1.529706015229238E-14
1.723066134218243E-13 1.5297058540778443E-14
Update
If you try the same thing with the BigDecimal class, you will be able to calculate the square root of 234 in case you choose enough rounding digits (see the scale variable below):
private static void calcRootBig(String arg) {
// read in the command-line argument
BigDecimal c = new BigDecimal(arg);
BigDecimal epsilon = new BigDecimal(1.0e-15); // relative error tolerance
BigDecimal t = new BigDecimal(c.toString()); // estimate of the square root of c
BigDecimal two = new BigDecimal("2.0");
// repeatedly apply Newton update step until desired precision is achieved
int scale = 10;
while (t.subtract(c.divide(t, scale, RoundingMode.CEILING)).abs().compareTo(epsilon) > 0) {
t = c.divide(t, scale, RoundingMode.CEILING).add(t).divide(two, scale, RoundingMode.CEILING);
}
// print out the estimate of the square root of c
System.out.println(t);
}
Yet if you choose just 3 for the rounding scale, you will be caught up again in an unending loop.
So it seems that it is the precision of the floating point division which is actually causing the unending loop in your case. The multiplication of epsilon * t is just a trick to overcome the lack of rounding precision in the default floating point operations.
A: double has around 15 digits of precision (or 1 to 2^52 or 4.5e15). When you calculate t * epsilon you around requiring an error of 1 to 1e15/234 ratio which is possible with double, when you use epsilon you are requiring a ratio of 1 to 1e15 which is at the limits of the precision of double unless it's an exact value and the error is 0. e.g. try this for 256 and it might work, but anything which is not an exactly value probably doesn't.
A simple solution to an arbitrary end point is to stop once the error doesn't improve from one iteration to the next. This is will give you the most accurate solution using this formula possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55954989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Disable a button inside ion-nav-buttons How can I disable a button inside ion-nav-buttons depending on an action in the ion-content?
example: if I click in a button inside ion-content the button inside
ion-nav-buttons get disabled.
As I see, I can´t controll the elements inside ion-nav-buttons from the controller of the template that has the ion-nav-buttons.
A: This can be done with ng-disabled in button
Check this Try ng-disabled
<ion-view>
<ion-nav-buttons side="primary">
<button class="button" ng-disabled="disabled" ng-click="doSomething()">
I'm a button on the primary of the navbar!
</button>
</ion-nav-buttons>
<ion-content>
<button class="button" ng-click="disable()">
Click to disable
</button>
</ion-content>
</ion-view>
//Angular code
$scope.disable=function(){
$scope.disabled=true;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36990043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Table without a identity column but this column can't have repeated values I'm creating a table that needs to have 2 columns. The first column can't be repeated. The thing is, I will insert the value of the first column. How do I create this column?
SQLServer 2005
A: Make the first column the primary key of the table.
A: Set the column as a primary key. I doesn't have to be an identity column to has a PK.
A: Create it the same way you would any other column: create table sometable (column1 varchar(10), column2 varchar(20)) or whatever.
Do you mean: How can you get the database to force it to be unique? Either declare it to be the primary key, or create a unique index on the column.
Perhaps you're thinking that a primary key must be auto-generated? There's no such rule. Whether you invent the value yourself or use an autonumber feature has nothing to do with whether a field can be a primary key.
A: Why not just put a unique constraint on it:
ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
UNIQUE(<column_name>)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6031953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to make a particular record stay at the end of sql server database I am making a dialog based application in MFC, where in there is a need to read the database and display the contents from database, i managed to find the record and display it in a list box by comparing unique Id from edit box and database, but the problem is I cannot display the last record for some reason it's not happening, I am successfully able to display from 1 to n-1 so I decided to put nth record as dummy so I just need a method in which I can make that dummy record to always stay at the last or end of the database,
Thank you
{
int flag = 0;
CString ID;
CDatabase database;
CString sqlString=L"SELECT *FROM FM_REGISTER";
wchar_t connstring[500] = L"Driver={SQL SERVER};Server=FCS-LOKANATH\\SQLEXPRESS;DataBase=FM;Integrated Security=True";
database.Open(NULL, 0, 0, connstring);
m_InfoID.GetWindowText(ID);
m_InfoList.ResetContent();//this is a report command
CRecordset recordset(&database);
CString temp, record,temp2;
recordset.Open(CRecordset::forwardOnly, sqlString, CRecordset::readOnly);
while (!recordset.IsEOF()){//is null
record = _T("");
register int len = recordset.GetODBCFieldCount();
for (register int i = 0; i < 2; i++)
{
recordset.GetFieldValue(i, temp);
if (i == 0 & ID.CompareNoCase(temp) == -1)
{
//MessageBox(L"Positive Macth");
flag = 1;
}
else
{
//MessageBox(L"Nagative Macth");
flag = 0;
}
record += temp + _T("|");
}
m_InfoList.AddString(record);
recordset.MoveNext();
}
MessageBox(_T("Query done."), 0, 0);
// TODO: Add your control notification handler code here
}
A: OK, re-read and this didn't answer what you asked.
Post your code, we need to see how you are iterating the results. The answer below is about ordering and not a missing record.
You can do this with an order by on your query.
SELECT id, description, order FROM mytable ORDER BY order ASC
This will cause the query to be retrieved ordered by the order column, and you just need to make sure that the order in the database is largest for the record you want to appear last.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31139675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visible lines but no idea where in the html or css I've a small problem by creating my website. Some div or text element show some lines by moving the mouse over it.
they get invisible by clicking somewhere else. But I haven't define a border.
I do not know how to continue, may someone has a idea what that could be?
My website use bootstrap 4.0
example Picture
A: Did you try
text-decoration: none;
It is hard to guess the problem from your description.
You can also try inspecting that perticular div. Right click that div and select inspect element. There the browser will show you the css applied to that div or text.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45656158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to get database off of localhost and running permanently? So not sure it this is stupid to ask, but I'm running a neo4j database server (using Apollo server) from my React Application. Currently, I run it using node in a separate terminal (and I can navigate to it on localhost), then run npm start in a different terminal to get my application going. How can I get the database just up and running always, so if customers use the product they can always access the database? Or, if this isn't good practice, how can I establish the database connection while I run my client code?
Technologies being used: ReactJS, Neo4j Database, GraphQL + urql
I tried moving the Apollo server code into the App.tsx file of my application to run it from there directly when my app is launched, but this was giving me errors. I'm not sure if this is the proper way to do it, as I think it should be abstracted out of the client code?
A: If you want to run your server in the cloud so that customers can access your React application you need two things:
*
*one server/service to run your database, e.g. Neo4j AuraDB (Free/Pro) or other Cloud Marketplaces https://neo4j.com/docs/operations-manual/current/cloud-deployments/
*A service to run your react application, e.g. netlify, vercel or one of the cloud providers (GCP, AWS, Azure) that you then have to configure with the server URL + credentials of your Neo4j server
You can run neo4j-admin dump --to database.dump on your local instance to create a copy of your database content and upload it to the cloud service. For 5.x the syntax is different, I think neo4j-admin database dump --path folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75253674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I display the values from my DB (phpmyadmin) into a drop-down-box in unity? I am new in codding and I couldn't find any solution to solve my issue.
I just need to see the data from the database in my drop-down-box in Unity.
Please give me advices step by step.
A: I managed for now to connect to the DB.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// create conntection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT item_name FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "-".$row["item_name"]. "<br>";
}
}
$conn->close();
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57843164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to validate or wrap user inputted HTML to fix unclosed tags I have text boxes in a form where users can input formatted text or raw HTML. It all works fine, however is a user doesn't close a tag (like a bold tag), then it ruins all HTML formatting after it (it all becomes bold).
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
A: You may try jquery-clean
$.htmlClean($myContent);
A:
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
Yes: When the user is done editing the text area, you can parse what they've written using the browser, then get an HTML version of the parsed result from the browser:
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
Live example — type an unclosed tag in and click the button:
$("input[type=button]").on("click", function() {
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
$(document.body).append("<p>You wrote:</p><hr>" + html + "<hr>End of what you wrote.");
});
<p>Type something unclosed here:</p>
<textarea id="the-textarea" rows="5" cols="40"></textarea>
<br><input type="button" value="Click when ready">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Important Note: If you're going to store what they write and then display it to anyone else, there is no client-side solution, including the above, which is safe. Instead, you must use a server-side solution to "sanitize" the HTML you get from them, to remove (for instance) malicious content, etc. All the above does is help you get mostly-well-formed markup, not safe markup.
Even if you're just displaying it to them, it would still be best to sanitize it, since they can work around any client-side pre-processing you do.
A: You could try and use : http://ejohn.org/blog/pure-javascript-html-parser/ .
But if the user is entering the html by hand you could just check to have all tags closed properly. If not, just display an error message to the user.
A: You can create a jQuery element using the text and then get it's html, like so
Sample
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
Script
alert($($('textarea').text()).html());
alert($($('textarea').text()).html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
A: The simple way to check if entered HTML is actually valid and parseable by browser is to let browser try it out itself using DOMParser. Then you could check if result is ok or not:
function checkHTML(html) {
var dom = new DOMParser().parseFromString(html, "text/xml");
return dom.documentElement.childNodes[0].nodeName !== 'parsererror';
}
$('button').click(function() {
var html = $('textarea').val();
var isValid = checkHTML(html);console.log(isValid)
$('div').html(isValid ? html : 'HTML is not valid!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="80" rows="7"><div>Some HTML</textarea> <button style="vertical-align:top">Check</button>
<div></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32177105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Java List that will be remembered through each iteration I have created a BST in a class called BinaryTree
I am trying to create nodes with specific values in class called Test and add them to binary tree in class called AddToTree. At the moment I have created a class called BinaryTree which knows how to create a BST when its given the correct values.
It is working fine when i create multiple nodes inside class AddToTree but when I try to do it from class Test I believe the tree starts from a scratch with every new node. My question is how can I make it remember the all values that have been added previously.
Here is the method (addToBST) that Test class calls out which should add nodes to the tree and remember them :
public class AddToTree implements SomeClass {
private BinaryTree waitingLine1 = new BinaryTree();
private BinaryTree waitingLine2 = new BinaryTree();
@Override
public SimpleEntry<SomeClass, Someclass> addToBST(Someclass someclass) throws IllegalArgumentException {
waitingLine1.addNode(fristData, secondData, thirdData);
return null;
}
Now i call it with my Test class:
public class Test {
public static void main(String[] args) {
foo();
}
static void foo() {
AddToTree impl = new AddToTree();
addNodeAndTest(30, 120, null);
}
private static void addNodeAndTest(AddToTree impl, int firstValue, int secondValue, int thirdValue) {
//Some code
}
I believe that adding the BST class is irrelevant since i dont create a list in that class. Should I create a new class with the list implementation or how should I make it remember the list.
I would be really thankful if you could point me in the right direction.
If needed I can provide additional information.
EDIT!
Here is how i create the BinaryTree (addNode method).
public class BinaryTree{
Node root = null;
public void addNode(int firstValue, int secondValue, int thirdValue) {
Node newNode = new Node(fristValue, secondValue, thirdValue);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (ID < focusNode.firstValue) {
focusNode = focusNode.leftChild;
if (focusNode == null) {
parent.leftChild = newNode;
return;
}
} else {
focusNode = focusNode.rightChild;
if (focusNode == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47290821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get Process Handle of Windows Explorer I want to get the Handle of my "Windows Explorer" Windows (not Internet Explorer).
Normally it works with
var processes = Process.GetProcesses();
foreach (var process in processes)
{
var handle = process.Handle;
}
What i want to do is following:
Bring the a specific Explorer Window to ForeGround.
I have implemented the "ToForeGround" Method and it works fine for all other Windows except the Windows Explorer
But with the Windows Explorer i only get the Process of the Taskbar independent of how much Windows are open, there is only one "Windows Explorer" Process.
Or can somebody explain me why the "Windows Explorer" is different from other Programms?
A: Point well taken, so let me try to explain briefly what the code does - you can read more about the ShellWindows object here.
The code below helps you find all running instances of Windows Explorer (not Internet Explorer, note that "explorer" is used in the if statement and not "iexplore").
Add Reference to Shell32.dll, located in the Windows/system32 folder
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
ArrayList windows = new ArrayList();
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename.Equals("explorer"))
{
//do something with the handle here
MessageBox.Show(ie.HWND.ToString());
}
}
A:
can somebody explain me why the "Windows Explorer" is different from other Programms?
It's the default shell. Explorer.exe handles many (user interface) tasks of Windows, some of which are the taskbar, hosting extensions and harboring the file explorer.
It's a (sort-of) single-instance process, so when you launch a new instance, it'll hand the parameters to the running instance.
If you want to focus or open an Explorer at a certain path, just use:
Process.Start(@"C:\SomeFolder\");
A: Following code iterates through all explorer and internet explorer windows(tabs) (W7/IE11). Location URL will give the folder that is being viewed in the explorer. If the folder is the one you need to bring to foreground, you can use HWND for that window and bring it to foreground.
Note location URL for explorer window for "Computer" will be blank. I am not sure if there are more special cases like that.
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
foreach (SHDocVw.InternetExplorer window in shellWindows){
if (window.LocationURL.Contains("Some Folder I am interested in")){
SetForegroundWindow((IntPtr)window.HWND);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27855828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Select multiple tuples into one SELECT contact_id, name, email, phone, city
FROM ak_contact
WHERE email = 'test@gmail.com'
ORDER BY contact_id DESC
Tis query returns me something like this:
contact_id name email phone city
8499 Serj test@gmail.com
8498 Serj test@gmail.com 3-33-333
8494 Serj test@gmail.com London
8493 Serj test@gmail.com 2-22-222
But I need one tuple as a result containing only latest values ( if they are not null/empty )
So the result I need should looks like this:
contact_id name email phone city
8499 Serj test@gmail.com 3-33-333 London
A: I'm not generally a fan of nested select statements, but that is one way to approach this in MySQL:
select (select contact_id
from ak_contact
where email = 'test@gmail.com' and
contact_id is not null
order by contact_id desc
limit 1
) as contact_id,
(select name
from ak_contact
where email = 'test@gmail.com' and
name is not null
order by contact_id desc
limit 1
) as name,
(select phone
from ak_contact
where email = 'test@gmail.com' and
phone is not null
order by contact_id desc
limit 1
) as phone,
(select city
from ak_contact
where email = 'test@gmail.com' and
city is not null
order by contact_id desc
limit 1
) as city
Each column might be coming from a different row, so each gets its own query.
A: More along the lines of Gordon's answer...
SELECT a.c_id,
CASE
WHEN b.name IS NULL THEN (SELECT name
FROM ak_contact
WHERE name IS NOT NULL
AND email = a.email
ORDER BY c_id DESC
LIMIT 1)
ELSE b.name
end AS name,
b.email,
CASE
WHEN b.phone IS NULL THEN (SELECT phone
FROM ak_contact
WHERE phone IS NOT NULL
AND email = a.email
ORDER BY c_id DESC
LIMIT 1)
ELSE b.phone
end AS phone,
CASE
WHEN b.city IS NULL THEN (SELECT city
FROM ak_contact
WHERE city IS NOT NULL
AND email = a.email
ORDER BY c_id DESC
LIMIT 1)
ELSE b.city
end AS city
FROM (SELECT email,
Max(c_id) AS c_id
FROM ak_contact
WHERE email = 'test@gmail.com'
GROUP BY email) a
LEFT JOIN ak_contact b
ON b.c_id = a.c_id
Result
| C_ID | NAME | EMAIL | PHONE | CITY |
----------------------------------------------------
| 8499 | Serj | test@gmail.com | 3-33-333 | London |
See the demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15684182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: AutoMapper - Nested Generic Object mapping I am learning automapper for mapping the entities.
I have an object named MyResponse1 as:
public class MyResponse1
{
public bool IsSuccessful {get;set;}
public string Message {get;set;}
public Object ReturnedObject {get;set;}
}
than I have MyResponse2
public class MyResponse2
{
public bool IsSuccessful {get;set;}
public string Message {get;set;}
public Object ReturnedObject {get;set;}
}
MyResponse1 is the source and MyResponse2 is destination, than I have class like:
public class User1
{
public int UserId {get;set;}
}
public class User2
{
public int UserId {get;set;}
}
my mapping configuration is like:
Mapper.CreateMap<User1, User2>();
Mapper.CreateMap<MyResponse1, MyResponse2>();
now I have like:
MyResponse1 resp = new MyResponse1();
resp.IsSuccessful = true;
resp.Message = "User retreived.";
User1 oUser = new User1();
oUser.UserId = 1;
resp.ReturnedObject = oUser;
But when I do like:
MyResponse2 resp2 = Mapper.Map<MyResponse1, MyResponse2>(resp);
than resp2 has User1 as the Returned object but I want User2 as the returned object, I canot change the type of ReturnedObject because I need to send objects of different types in it.
Any idea how it can be achieved?
Edit:
One way out that I used is that I did it like this and it worked:
MyResponse2 resp2 = Mapper.Map<MyResponse1, MyResponse2>(resp);
resp2.ReturnedObject = Mapper.Map<User1, User2>(resp.ReturnedObject as User1);
is there any other better way to do it?
A: You cannot map to the destination ReturnedObject type since it doesn't exist when you are mapping the MyResponse1. What you are doing in your edit is exactly that, you are mapping explicitly to a known type.
The only way to automate the mapping would be to declare what object MyResponse2 can expect. Perhaps transforming MyResponse2 to a generics type would be a possible way to do it:
public class MyResponse2<T>
{
public bool IsSuccessful {get;set;}
public string Message {get;set;}
public T ReturnedObject {get;set;}
}
Then you could generalize the mapping process like so:
private static void CreateMapFromUser1To<T>() where T: class {
Mapper.CreateMap<MyResponse1, MyResponse2<T>>()
.ForMember(destination => destination.ReturnedObject, opt => opt.Ignore()) // ignore the object
.AfterMap((source, destination) => destination.ReturnedObject = Mapper.Map(source.ReturnedObject, source.ReturnedObject.GetType(), typeof(T)) as T);
}
You won't be able to map from an object to.. basically nothing so you need a destiantion type. But frankly you may have a bad design in your app and i'd recommend stepping back a taking a good look at the conversions you want to achieve
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22684667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual Studio 15.8.1 not running MS unit tests When I updated Visual Studio to the latest version, 1 of my test projects stopped running tests and outputted this message:
Test project {} does not reference any .NET NuGet adapter. Test
discovery or execution might not work for this project. It is
recommended to reference NuGet test adapters in each test project in
the solution.
UPDATED: I was using MS Test as opposed to any other test frameworks like Nunit or Xunit.
A: I had to add the following Nuget packages:
MSTest.TestAdapter
MSTest.TestFramework
Microsoft.NET.Test.Sdk
Visual Studio release notes
A: Ok, you can add Nuget packages as asked. But you can also try to disable the following setting (Tools->Options->Test):
"For improved performance, only use test adapters in test assembly folder or as specified in runsettings file".
Let me know if it works for you.
A: If you are using MS Test, try installing
MSTest.TestAdapter via nuget or
if you are using nunit, install
NUnit3TestAdapterlatest versions via nuget.
After installing please restart the visual studio and then you can see the tests running.
A: I had the same issue and none of the answers above worked.
Installing NUnit3TestAdapter V3.10.0 fixed it.
A: I had a very similar issue recently with xUnit, the same outcome, however my fix was due to the fact that previously with lower versions of Microsoft.NET.Test.Sdk you didn't need XUnit.Runner.VisualStudio explicitly installed.
When I updated my Microsoft.NET.Test.Sdk to version 15.9.0 it stopped allowing tests to run until I installed the XUnit.Runner.VisualStudio Nuget.
Now, This may seem blatantly obvious, but, previously it would cope without it and still work. Now, it does not. The same will probably be true of other test platforms. It worked for me.
A: My reputation score does not currently allow me to add this as a comment to the accepted answer. For reference, I've appended version numbers to the nuget packages referenced in csharpsql's answer:
MSTest.TestAdapter v1.3.2
MSTest.TestFramework v1.3.2
Microsoft.NET.Test.Sdk v15.9.0
A: I know that it is stupid, but for me nothing from earlier answers were working. After that I just restart my computer and everything is working correctly :)
(My proble was that one day everything was working correctly and next day it stopped working)
A: For me I felt very foolish after spending hours, trying EVERYTHING, only to find that I had simply forgotten to add the [TestMethod] directive on the unit test method.
A: I was trying to run an existing project. I had the .NET Core SDK 3.3 installed, but did not have 2.1 installed. This was causing the tests to silently fail.
A: I ran into this problem too (in VS 2019), which can be found all over the web.
I also support @csharpsql's simple solution.
I also couldn't directly comment (how annoying Stack Overflow!)
I had used 'Remove unused references' in VS.
I did have to restart VS to get the references removed from view.
Cleaning and rebuilding posed no problem.
But running all tests from the Test Explorer reported 'Not run' on all tests, without any explanation or error message. Very annoying.
After finding the suggestion here I started experimenting with re-adding the latest versions of those 3 references.
That solved my problem.
I just remains annoying this unnecessary problem occurs!
A: Adding NuGet packages doesn't work for me.
Disable the following setting (Tools->Options->Test): "For improved performance, only use test adapters in test assembly folder or as specified in runsettings file" works.
A: Since its just a checkbox, Ive tried disabling the following setting before anything else, and it worked!
Tools -> Options -> Test -> "For improved performance, only use test adapters in test assembly folder or as specified in runsettings file"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51967866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
}
|
Q: Inserts are out of order even with auto-incrementing primary key I have a table with 3 columns: id (auto-incrementing PK), product_id, project_id.
product_id and project_id are foreign keys. There is also a unique key for those 2 columns.
I'm finding that when I do a simple "SELECT * FROM myTable", the results are not primarily being ordered by the id column. They appear to first be ordered by id but then also the other 2 columns. So, I insert (5, 10) into the table and then (5, 6), then select them, I get:
id | product_id | project_id
2 | 5 | 6
1 | 5 | 10
How does this happen?
A: If you don't explicitly request an order with ORDER BY, MySQL displays the results in the order it reads them from an index.
I would infer that MySQL is using your UNIQUE index to read these rows, so they're read from that index in order by product_id first, then by project_id.
By analogy, if you read names from the telephone book, you read them in order by last name and then by first name. That's the order they're stored, regardless of which phone number was assigned first.
The id column is the primary key, which is implicitly appended to every non-primary index.
A: Normally, databases do not have a "default" order, so if you do not specify an implicit order, you can not make any assumptions on the final order of the results. If you need to retrieve the records in any certain order, you should append " ORDER BY " at the end of your query.
Please, note that the exact same query, without an order by clause, can produce results in very different order.
A: Do not depend on order when ORDER BY is missing.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.
So there's even no guarantee that two queries which look the same will return results in the same order: if you don't specify it, you cannot rely on it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39211936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can't see node after joining it to cluster - "getsockopt: connection refused" I am new in Kubernetes.
I have two nodes:
*
*Master
*Worker
I installed Kubernetes on both of them and on the muster I ran the kubeadm init... command in the Master node and received the command to join a new worker to the cluster:
sudo kubeadm join --token 61a503.3bdf2341a37a2732 192.168.190.159:6443 --discovery-token-ca-cert-hash sha256:ef66d8b7284af9e80f18767af39b5f164e00fd7fe714d3092e8ff682f07076da
I ran the above command inside the Worker node and it seems that it succeed:
This is the output:
[preflight] Running pre-flight checks.
[WARNING FileExisting-crictl]: crictl not found in system path
[discovery] Trying to connect to API Server "192.168.190.159:6443"
[discovery] Created cluster-info discovery client, requesting info from "https://192.168.190.159:6443"
[discovery] Requesting info from "https://192.168.190.159:6443" again to validate TLS against the pinned public key
[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server "192.168.190.159:6443"
[discovery] Successfully established connection with API Server "192.168.190.159:6443"
This node has joined the cluster:
* Certificate signing request was sent to master and a response
was received.
* The Kubelet was informed of the new secure connection details.
Run 'kubectl get nodes' on the master to see this node join the cluster.
But when I go to the Master and run:
kubectl get nodes
I see only the master:
master@osboxes:~$ kubectl get nodes
NAME STATUS ROLES AGE VERSION
osboxes Ready master 4h v1.9.1
Docker version on both nodes:
Client:
Version: 1.13.1
API version: 1.26
Go version: go1.6.2
Git commit: 092cba3
Built: Thu Nov 2 20:40:23 2017
OS/Arch: linux/amd64
Server:
Version: 1.13.1
API version: 1.26 (minimum version 1.12)
Go version: go1.6.2
Git commit: 092cba3
Built: Thu Nov 2 20:40:23 2017
OS/Arch: linux/amd64
Experimental: false
How can I find what is the problem?
Any idea what can it be ?
By the way, I tried the same thing on two nodes in AWS and it worked fine.
EDIT (15.5.2018): Logs
These are the logs from the kubelet daemon from the Worker node, I exported it with sudo journalctl -u kubelet > logs.txt
May 15 06:39:05 osboxes kubelet[12160]: E0515 06:39:05.113840 12160 kubelet_node_status.go:375] Unable to update node status: update node status exceeds retry count
May 15 06:39:06 osboxes kubelet[12160]: E0515 06:39:06.060871 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:06 osboxes kubelet[12160]: E0515 06:39:06.072458 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:06 osboxes kubelet[12160]: E0515 06:39:06.075082 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:07 osboxes kubelet[12160]: E0515 06:39:07.064412 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:07 osboxes kubelet[12160]: E0515 06:39:07.082627 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:07 osboxes kubelet[12160]: E0515 06:39:07.084203 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:08 osboxes kubelet[12160]: E0515 06:39:08.084848 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:08 osboxes kubelet[12160]: E0515 06:39:08.085296 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:08 osboxes kubelet[12160]: E0515 06:39:08.086186 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:09 osboxes kubelet[12160]: E0515 06:39:09.091850 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:09 osboxes kubelet[12160]: E0515 06:39:09.092907 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:09 osboxes kubelet[12160]: E0515 06:39:09.093494 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:10 osboxes kubelet[12160]: E0515 06:39:10.094472 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:10 osboxes kubelet[12160]: E0515 06:39:10.097289 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:10 osboxes kubelet[12160]: E0515 06:39:10.098355 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:11 osboxes kubelet[12160]: E0515 06:39:11.101260 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:11 osboxes kubelet[12160]: E0515 06:39:11.102788 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:11 osboxes kubelet[12160]: E0515 06:39:11.103772 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:12 osboxes kubelet[12160]: E0515 06:39:12.109494 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:12 osboxes kubelet[12160]: E0515 06:39:12.126419 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:12 osboxes kubelet[12160]: E0515 06:39:12.127858 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:13 osboxes kubelet[12160]: E0515 06:39:13.128797 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:13 osboxes kubelet[12160]: E0515 06:39:13.130811 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:13 osboxes kubelet[12160]: E0515 06:39:13.132159 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:14 osboxes kubelet[12160]: E0515 06:39:14.132703 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:14 osboxes kubelet[12160]: E0515 06:39:14.133885 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:14 osboxes kubelet[12160]: E0515 06:39:14.134534 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.123979 12160 kubelet_node_status.go:383] Error updating node status, will retry: error getting node "osboxes": Get https://192.168.190.159:6443/api/v1/nodes/osboxes?resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.126886 12160 kubelet_node_status.go:383] Error updating node status, will retry: error getting node "osboxes": Get https://192.168.190.159:6443/api/v1/nodes/osboxes: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.128832 12160 kubelet_node_status.go:383] Error updating node status, will retry: error getting node "osboxes": Get https://192.168.190.159:6443/api/v1/nodes/osboxes: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.132161 12160 kubelet_node_status.go:383] Error updating node status, will retry: error getting node "osboxes": Get https://192.168.190.159:6443/api/v1/nodes/osboxes: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.134043 12160 kubelet_node_status.go:383] Error updating node status, will retry: error getting node "osboxes": Get https://192.168.190.159:6443/api/v1/nodes/osboxes: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.134746 12160 kubelet_node_status.go:375] Unable to update node status: update node status exceeds retry count
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.142404 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.143773 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:15 osboxes kubelet[12160]: E0515 06:39:15.144730 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:16 osboxes kubelet[12160]: E0515 06:39:16.146062 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:16 osboxes kubelet[12160]: E0515 06:39:16.147948 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:16 osboxes kubelet[12160]: E0515 06:39:16.148963 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:17 osboxes kubelet[12160]: E0515 06:39:17.153690 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:17 osboxes kubelet[12160]: E0515 06:39:17.169648 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:17 osboxes kubelet[12160]: E0515 06:39:17.170775 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:18 osboxes kubelet[12160]: E0515 06:39:18.171909 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:18 osboxes kubelet[12160]: E0515 06:39:18.174020 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:18 osboxes kubelet[12160]: E0515 06:39:18.175013 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:19 osboxes kubelet[12160]: E0515 06:39:19.178296 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:19 osboxes kubelet[12160]: E0515 06:39:19.182903 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:19 osboxes kubelet[12160]: E0515 06:39:19.184147 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:20 osboxes kubelet[12160]: E0515 06:39:20.183063 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:20 osboxes kubelet[12160]: E0515 06:39:20.198007 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:20 osboxes kubelet[12160]: E0515 06:39:20.199996 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:21 osboxes kubelet[12160]: E0515 06:39:21.186122 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/config/apiserver.go:47: Failed to list *v1.Pod: Get https://192.168.190.159:6443/api/v1/pods?fieldSelector=spec.nodeName%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:21 osboxes kubelet[12160]: E0515 06:39:21.203974 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:474: Failed to list *v1.Node: Get https://192.168.190.159:6443/api/v1/nodes?fieldSelector=metadata.name%3Dosboxes&limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
May 15 06:39:21 osboxes kubelet[12160]: E0515 06:39:21.207920 12160 reflector.go:205] k8s.io/kubernetes/pkg/kubelet/kubelet.go:465: Failed to list *v1.Service: Get https://192.168.190.159:6443/api/v1/services?limit=500&resourceVersion=0: dial tcp 192.168.190.159:6443: getsockopt: connection refused
Logs from Kubelet:
worker2@osboxes:~$ sudo kubelet
I0515 11:22:38.938557 33604 feature_gate.go:220] feature gates: &{{} map[]}
I0515 11:22:38.938712 33604 controller.go:114] kubelet config controller: starting controller
I0515 11:22:38.938757 33604 controller.go:118] kubelet config controller: validating combination of defaults and flags
W0515 11:22:38.949230 33604 cni.go:171] Unable to update cni config: No networks found in /etc/cni/net.d
I0515 11:22:38.987488 33604 server.go:182] Version: v1.9.1
I0515 11:22:38.987524 33604 feature_gate.go:220] feature gates: &{{} map[]}
I0515 11:22:38.987620 33604 plugins.go:101] No cloud provider specified.
W0515 11:22:38.987656 33604 server.go:328] standalone mode, no API client
W0515 11:22:39.028891 33604 server.go:236] No api server defined - no events will be sent to API server.
I0515 11:22:39.028997 33604 server.go:428] --cgroups-per-qos enabled, but --cgroup-root was not specified. defaulting to /
I0515 11:22:39.029367 33604 container_manager_linux.go:242] container manager verified user specified cgroup-root exists: /
I0515 11:22:39.029459 33604 container_manager_linux.go:247] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>}]} ExperimentalQOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s}
I0515 11:22:39.029627 33604 container_manager_linux.go:266] Creating device plugin manager: false
W0515 11:22:39.032405 33604 kubelet_network.go:139] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0515 11:22:39.032456 33604 kubelet.go:571] Hairpin mode set to "hairpin-veth"
I0515 11:22:39.034512 33604 client.go:80] Connecting to docker on unix:///var/run/docker.sock
I0515 11:22:39.034568 33604 client.go:109] Start docker client with request timeout=2m0s
W0515 11:22:39.042224 33604 cni.go:171] Unable to update cni config: No networks found in /etc/cni/net.d
I0515 11:22:39.052530 33604 docker_service.go:232] Docker cri networking managed by kubernetes.io/no-op
I0515 11:22:39.075356 33604 docker_service.go:237] Docker Info: &{ID:N4M2:L4UZ:CZTV:LQHL:KAFZ:EB2Z:ZCF2:ED6G:KRR4:AI6X:KFQH:BTAH Containers:2 ContainersRunning:2 ContainersPaused:0 ContainersStopped:0 Images:7 Driver:aufs DriverStatus:[[Root Dir /var/lib/docker/aufs] [Backing Filesystem extfs] [Dirs 25] [Dirperm1 Supported true]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[]} MemoryLimit:true SwapLimit:false KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:29 OomKillDisable:true NGoroutines:34 SystemTime:2018-05-15T11:22:39.055044415-04:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:0 KernelVersion:4.13.0-36-generic OperatingSystem:Ubuntu 16.04.4 LTS OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc4206ae690 NCPU:1 MemTotal:2066481152 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:osboxes Labels:[] ExperimentalBuild:false ServerVersion:1.13.1 ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:0xc420690500} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID: Expected:aa8187dbd3b7ad67d8e5e3a15115d3eef43a7ed1} RuncCommit:{ID:N/A Expected:9df8b306d01f59d3a8029be411de015b7304dd8f} InitCommit:{ID:N/A Expected:949e6facb77383876aeff8a6944dde66b3089574} SecurityOptions:[name=apparmor name=seccomp,profile=default]}
I0515 11:22:39.075476 33604 docker_service.go:250] Setting cgroupDriver to cgroupfs
I0515 11:22:39.103735 33604 remote_runtime.go:43] Connecting to runtime service unix:///var/run/dockershim.sock
I0515 11:22:39.105235 33604 kuberuntime_manager.go:186] Container runtime docker initialized, version: 1.13.1, apiVersion: 1.26.0
I0515 11:22:39.114094 33604 server.go:755] Started kubelet
E0515 11:22:39.114169 33604 server.go:511] Starting health server failed: listen tcp 127.0.0.1:10248: bind: address already in use
E0515 11:22:39.114305 33604 kubelet.go:1275] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
W0515 11:22:39.114329 33604 kubelet.go:1359] No api server defined - no node status update will be sent.
I0515 11:22:39.114672 33604 kubelet_node_status.go:273] Setting node annotation to enable volume controller attach/detach
I0515 11:22:39.115490 33604 server.go:129] Starting to listen on 0.0.0.0:10250
I0515 11:22:39.117147 33604 server.go:299] Adding debug handlers to kubelet server.
F0515 11:22:39.119054 33604 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use
A:
error reading /var/lib/kubelet/pki/kubelet.key, certificate and key must be supplied as a pair
Usually, this is a permission issue. Check permissions of the certificate file, it should be readable for Kubelet user.
If it does not help you - please share the Kubelet logs, namely the logs of the daemon, do not start it manually in the console.
Based on the update of the question:
192.168.190.159:6443: getsockopt: connection refused
It means that Kubelet on the node cannot connect to the master. Check the network connection between your node and the master. The node should be able to connect to https://192.168.190.159:6443, which is your API server endpoint.
A: OK, the problem was that both nodes (Master and Worker) had the same hostname :).
I noticed it after I ran kubectl describe node and in the Addresses field I saw the IP address of the worker with the same Hostname of the master:
Addresses:
InternalIP: 192.168.190.162
Hostname: worker2node
I run sudo kubeadm reset on both Master and Worker.
On Master:
sudo swapoff -a
sudo kubeadm init --pod-network-cidr=10.244.0.0/16 --apiserver-advertise-address=192.168.190.159
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
kubectl apply -f kube-flannel.yml
On Worker:
Changed the hostname:
hostnamectl set-hostname worker2node
sudo vi /etc/hosts # (edit this file with the new name for 127.0.1.1)
Restart the worker and join it again.
I checked and now it was added.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50334963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Tuning of mtry by caret returning strange value I tune the mtry parameter of randomForest using the train function from the caret package. There are only 48 columns in my X data, however train returns mtry=50 as the best value whereas this is not a valid value (>48). What is the explanation of that ?
> dim(X)
[1] 93 48
> fit <- train(level~., data=data.frame(X,level), tuneLength=13)
> fit$finalModel
Call:
randomForest(x = x, y = y, mtry = param$mtry)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 50
OOB estimate of error rate: 2.15%
Confusion matrix:
high low class.error
high 81 1 0.01219512
low 1 10 0.09090909
It is even worse if I don't set the tuneLength parameter:
> fit <- train(level~., data=data.frame(X,level))
> fit$finalModel
Call:
randomForest(x = x, y = y, mtry = param$mtry)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 55
OOB estimate of error rate: 2.15%
Confusion matrix:
high low class.error
high 81 1 0.01219512
low 1 10 0.09090909
I don't provide the data cause it is confidential. But there's nothing special in these data: each column is numerical or is a factor, and there are no missing value.
A: The apparent discrepancy is most likely[1] between the number of columns in your data set and the number of predictors, which may not be the same if any of the columns are factors. You used the formula method, which will expand the factors into dummy variables. For example:
> head(model.matrix(Sepal.Width ~ ., data = iris))
(Intercept) Sepal.Length Petal.Length Petal.Width Speciesversicolor Speciesvirginica
1 1 5.1 1.4 0.2 0 0
2 1 4.9 1.4 0.2 0 0
3 1 4.7 1.3 0.2 0 0
4 1 4.6 1.5 0.2 0 0
5 1 5.0 1.4 0.2 0 0
6 1 5.4 1.7 0.4 0 0
So there are 3 predictor columns in iris but you end up with 5 (non-intercept) predictors.
Max
[1] This is why you need to provide a reproducible example. Often, when I get ready to ask a question, the answer becomes apparent while I take the time to write a good description of the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25763977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Including disturbance rejection in GEKKO MPC I am trying to implement an MPC algorithm using GEKKO MPC to compare against my own MPC implementation. I have managed to perform the set point changes without a problem however, when I try to include steps in a disturbance the controlled variable does not return to steady state (a value of zero for deviation variables). This would make me think that I need to include a command which allows feedback? I am unsure.
from gekko import GEKKO
import numpy
import matplotlib.pyplot as plt
t = numpy.linspace(0,300,100)
m = GEKKO(remote = False)
m.time = t
# Parameters
T1 = m.Param(value = 53.97272679974334)
T2 = m.Param(value = 48.06851424706475)
T3 = m.Param(value = 38.48651254747577)
T4 = m.Param(value = 31.018933652439845)
k1 = m.Param(value = 5.51)
k2 = m.Param(value = 6.58)
γ1bar = m.Param(value = 0.333)
γ2bar = m.Param(value = 0.307)
A1 = m.Param(value = 730)
A2 = m.Param(value = 730)
A3 = m.Param(value = 730)
A4 = m.Param(value = 730)
v1bar = m.Param(value = 60)
v2bar = m.Param(value = 60)
# Manipulated variable
v1 = m.MV(value=0, lb=0, ub=100)
v1.STATUS = 1
#v1.DCOST = 0.1
#v2.DMAX = 20
v2 = m.MV(value=0, lb=0, ub=100)
v2.STATUS = 1
#v2.DCOST = 0.1
#v2.DMAX = 20
γ1 = m.MV(value=0, lb=0, ub=1)
γ1.STATUS = 1
#γ1.DCOST = 0.1
#v2.DMAX = 20
γ2 = m.MV(value=0, lb=0, ub=1)
γ2.STATUS = 1
#γ2.DCOST = 0.1
#v2.DMAX = 20
d = numpy.ones(t.shape)
d[0:10] = 0
d22 = numpy.zeros(t.shape)
d1 = m.Param(name='d1', value=d) # Disturbance
d2 = m.Param(name='d2', value=d22) # Disturbance
m.options.CV_TYPE = 2 # squared error
# Controlled Variable
h1 = m.CV(value=0)
h1.STATUS = 1 # add the SP to the objective
h1.SP = 1 # set point
h1.TR_INIT = 1 # set point trajectory
h1.TAU = 1 # time constant of trajectory
h1.BIAS = 1
h1.FSTATUS = 1
h2 = m.CV(value=0)
h2.STATUS = 1 # add the SP to the objective
h2.SP = 0 # set point
h2.TR_INIT = 1 # set point trajectory
h2.TAU = 1 # time constant of trajectory
h2.BIAS = 1
h2.FSTATUS = 1
h3 = m.CV(value=0)
h3.STATUS = 1 # add the SP to the objective
h3.SP = 0 # set point
h3.TR_INIT = 1 # set point trajectory
h3.TAU = 1 # time constant of trajectory
h3.BIAS = 1
h3.FSTATUS = 1
h4 = m.CV(value=0)
h4.STATUS = 1 # add the SP to the objective
h4.SP = 0 # set point
h4.TR_INIT = 1 # set point trajectory
h4.TAU = 1 # time constant of trajectory
h4.BIAS = 1
h4.FSTATUS = 1
m.Equation(h1.dt() == -(1/T1)*h1 + (A3/(A1*T3))*h3 + (γ1bar*k1*v1)/A1 + (γ1*k1*v1bar)/A1)
m.Equation(h2.dt() == -(1/T2)*h2 + (A4/(A2*T4))*h4 + (γ2bar*k2*v2)/A2 + (γ2*k2*v2bar)/A2)
m.Equation(h3.dt() == -(1/T3)*h3 + ((1-γ2bar)*k2*v2)/A3 - k2*v2bar*γ2/A3 - (k1*d1)/A3)
m.Equation(h4.dt() == -(1/T4)*h4 + ((1-γ1bar)*k1*v1)/A4 - k1*v1bar*γ1/A4 - (k2*d2)/A4)
m.options.IMODE = 6 # control
m.solve(disp=False,debug = True)
A: Try setting h1.SP = 0 instead of 1 to set the objective to drive it back to 1. Also, these options are not needed if h4.TR_INIT = 0 to create a setpoint that is zero everywhere (not a reference trajectory).
h4.TAU = 1
h4.BIAS = 1
h4.FSTATUS = 1
I also added lower bounds of zero for each of the height CVs with lb=0. There is a move on v2 when the disturbance starts. It appears that the controller can't resolve this offset. Is this the correct response?
from gekko import GEKKO
import numpy
import matplotlib.pyplot as plt
t = numpy.linspace(0,300,100)
m = GEKKO(remote=False)
m.time = t
T1 = m.Param(value = 53.97272679974334)
T2 = m.Param(value = 48.06851424706475)
T3 = m.Param(value = 38.48651254747577)
T4 = m.Param(value = 31.018933652439845)
k1 = m.Param(value = 5.51)
k2 = m.Param(value = 6.58)
γ1bar = m.Param(value = 0.333)
γ2bar = m.Param(value = 0.307)
A1 = m.Param(value = 730)
A2 = m.Param(value = 730)
A3 = m.Param(value = 730)
A4 = m.Param(value = 730)
v1bar = m.Param(value = 60)
v2bar = m.Param(value = 60)
# Manipulated variable
v1 = m.MV(value=0, lb=0, ub=100)
v1.STATUS = 1
#v1.DCOST = 0.1
#v2.DMAX = 20
v2 = m.MV(value=0, lb=0, ub=100)
v2.STATUS = 1
#v2.DCOST = 0.1
#v2.DMAX = 20
γ1 = m.MV(value=0, lb=0, ub=1)
γ1.STATUS = 1
#γ1.DCOST = 0.1
#v2.DMAX = 20
γ2 = m.MV(value=0, lb=0, ub=1)
γ2.STATUS = 1
#γ2.DCOST = 0.1
#v2.DMAX = 20
d = numpy.ones(t.shape)
d[0:10] = 0
d22 = numpy.zeros(t.shape)
d1 = m.Param(name='d1', value=d) # Disturbance
d2 = m.Param(name='d2', value=d22) # Disturbance
m.options.CV_TYPE = 2 # squared error
# Controlled Variable
h1 = m.CV(value=0,lb=0)
h1.STATUS = 1 # add the SP to the objective
h1.SP = 0 # set point
h1.TR_INIT = 0 # set point trajectory
#h1.TAU = 1 # time constant of trajectory
#h1.BIAS = 1
#h1.FSTATUS = 1
h2 = m.CV(value=0,lb=0)
h2.STATUS = 1 # add the SP to the objective
h2.SP = 0 # set point
h2.TR_INIT = 0 # set point trajectory
#h2.TAU = 1 # time constant of trajectory
#h2.BIAS = 1
#h2.FSTATUS = 1
h3 = m.CV(value=0,lb=0)
h3.STATUS = 1 # add the SP to the objective
h3.SP = 0 # set point
h3.TR_INIT = 0 # set point trajectory
#h3.TAU = 1 # time constant of trajectory
#h3.BIAS = 1
#h3.FSTATUS = 1
h4 = m.CV(value=0,lb=0)
h4.STATUS = 1 # add the SP to the objective
h4.SP = 0 # set point
h4.TR_INIT = 0 # set point trajectory
#h4.TAU = 1 # time constant of trajectory
#h4.BIAS = 1
#h4.FSTATUS = 1
m.Equation(h1.dt() == -(1/T1)*h1 + (A3/(A1*T3))*h3 + (γ1bar*k1*v1)/A1 + (γ1*k1*v1bar)/A1)
m.Equation(h2.dt() == -(1/T2)*h2 + (A4/(A2*T4))*h4 + (γ2bar*k2*v2)/A2 + (γ2*k2*v2bar)/A2)
m.Equation(h3.dt() == -(1/T3)*h3 + ((1-γ2bar)*k2*v2)/A3 - k2*v2bar*γ2/A3 - (k1*d1)/A3)
m.Equation(h4.dt() == -(1/T4)*h4 + ((1-γ1bar)*k1*v1)/A4 - k1*v1bar*γ1/A4 - (k2*d2)/A4)
m.options.IMODE = 6 # control
m.solve(disp=True)
plt.subplot(3,1,1)
plt.plot(m.time,d1.value,'k-',label='Disturbance')
plt.ylabel('Disturbance'); plt.grid(); plt.legend()
plt.subplot(3,1,2)
plt.plot(m.time,h1.value,'r-',label='Height 1')
plt.plot(m.time,h2.value,'g--',label='Height 2')
plt.plot(m.time,h3.value,'b:',label='Height 3')
plt.plot(m.time,h3.value,'k--',alpha=0.5,label='Height 4')
plt.ylabel('CVs'); plt.grid(); plt.legend()
plt.subplot(3,1,3)
plt.plot(m.time,v1.value,'r-',label='MV 1a')
plt.plot(m.time,v2.value,'g--',label='MV 2a')
plt.plot(m.time,γ1.value,'b:',label='MV 1b')
plt.plot(m.time,γ2.value,'k--',alpha=0.5,label='MV 2b')
plt.ylabel('MVs'); plt.grid(); plt.legend()
plt.show()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70087745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is SSH public key need to be the same each time I do push/pull with git repository? I am just started using Git, so I apologize if it is a newbie question.
I am using two different machines to commit changes to remote Git repository on github.com. Do I need to use the same SSH public key (the one I mentioned for my repository on Github)?
A: No -- if you go to your GitHub accounts page, you can add as many SSH public keys as you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2585904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Segmentation Fault p_thread with a possible race condition Issue: I created a linked list of Child thread TIDS and want to wait on all the child tids to finish execution before I continue my main thread. Basically I have directory traversal (a directory is specified by the members of a given struct). Every time I see a directory or file I create a new thread and put its threadID into the linked list. However when I traverse the linked list and call pthread_join I get a segmentation fault (core dumped) - I cannot understand why. I believe in may have to do with race condition but I am not sure. When I remove the pthread_join I no longer segfault however I don't get full traversal of directories within directories.
Program:
void *handy(void *arguments)
{
static pthread_t threadA;
threadA=pthread_self();
handarg *thestruct=(handarg*)arguments;
DIR *dp=opendir(thestruct->directory);
DIR *outExist=opendir(thestruct->outputdirectory);
if(outExist==NULL)
{
if((thestruct->outputdirectory = ""))
{
;
}
else
{
printf("The outputdirectory doesnt exist, program terminated\n");
exit(1);
}
}
struct dirent *entry; // has two important members (d-type)-tells me if its a directory (d-name) tells me current file name
if(dp==NULL)
{
printf("directory doesnt exist: %s\n", thestruct->directory);
exit(1);
}
NODE *head=NULL; //linked list
NODE *ptr=(NODE*)malloc(sizeof(NODE));//node POINTER
int count;
while((entry=readdir(dp))!=NULL)
{
if(strcmp(entry->d_name,"..")==0||strcmp(entry->d_name,".")==0)
{
continue;
}
if((entry->d_type==DT_DIR))
{
unsigned int const sz1 = strlen(thestruct->directory);
unsigned int const sz2 = strlen(entry->d_name);
char *dnewname=(char *)malloc((sz1+sz2+2)*sizeof(char));
memcpy(dnewname,thestruct->directory,sz1);
memcpy(dnewname+sz1,"/",sizeof(char));
memcpy(dnewname+sz1+1,entry->d_name,sz2);
dnewname[strlen(dnewname)]='\0';
pthread_t tid;
handarg *current=(handarg*)malloc(sizeof(handarg));//malloc
current->directory=dnewname;
current->outputdirectory=thestruct->outputdirectory;
current->column=thestruct->column;
pthread_create(&tid,NULL,&handy,current);
threadA=pthread_self();
printf("The Filepath is: %s, The Parent TID = %ld, THE peer TID = %ld\n",dnewname, threadA, tid);
NODE *newNode=(NODE*)malloc(sizeof(NODE));
newNode->peerTid=tid;
newNode->next=NULL;
if(head==NULL)
{
head=newNode;
ptr=newNode;
//printf("THE TID I PUT INTO THIS NODE IS FUCK YOU FUCK YOU FUCK YOU %ld\n",ptr->peerTid);
}
else
{
ptr->next=newNode;
ptr=newNode;
//printf("THE TID I PUT INTO THIS NODE IS YAMAKA %ld\n",ptr->peerTid);
}
//and call wait on each of tids for loop only exit if last tid is waiting on
}
if((entry->d_type==DT_REG))
{
char *filename = entry->d_name;
int len = strlen(filename);
const char *last_four = &filename[len-4]; //need to account for if filename is less than 4 characters
if(strcmp(last_four,".csv")==0)
{
char *dnewname = (char*)malloc(sizeof(char)*(strlen(thestruct->directory)+strlen(entry->d_name)+2));
char *slash = (char*)malloc(sizeof(char));
strcpy(dnewname, thestruct->directory);
strcpy(slash, "/");
strcat(dnewname, slash);
strcat(dnewname, entry->d_name);
dnewname[strlen(dnewname)]='\0';
pthread_t tid;
handarg *current=(handarg*)malloc(sizeof(handarg));
current->directory=dnewname;
current->outputdirectory=thestruct->outputdirectory;
current->column=thestruct->column;
pthread_create(&tid,NULL,&handleFile,current);
//count++;
threadA=pthread_self();
printf("The Filepath is: %s, The Parent TID = %ld, THE peer TID = %ld\n",dnewname, threadA, tid);
NODE *newNode=(NODE*)malloc(sizeof(NODE));
newNode->peerTid=tid;
newNode->next=NULL;
if(head==NULL)
{
head=newNode;
ptr=newNode;
//printf("THE TID I PUT INTO THIS NODE IS %ld\n",ptr->peerTid);
}
else
{
ptr->next=newNode;
ptr=newNode;
//printf("THE TID I PUT INTO THIS NODE IS %ld\n",ptr->peerTid);
}
}
}
}
printf("the thread produced %d threads\n", count);
if(head==NULL)
{
printf("no child threads\n");
}
ptr=head;
printf("\nthese are the items from the linkedlist\n\n");
while (ptr!=NULL)
{
printf("%ld\n",ptr->peerTid);
ptr=ptr->next;
}
printf("\n");
ptr=head;
while (ptr!=NULL)
{
threadA=pthread_self();
printf("THE PEER THREAD %ld --------I AM THE THREAD %ld\n",ptr->peerTid,threadA);
pthread_join(ptr->peerTid,NULL);
printf("got here");
ptr=ptr->next;
}
printf("\n");
//return NULL;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47544737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WPF Storyboards in Datatemplates Can you programmatically begin a storyboard that is within a datatemplate?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4226699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to trigger a searchDisplayController by a button? I was wondering is there any way to implement such UI features.
As we know when we dragged in a search bar and searchDisplay control in xcode 5, we are be given a set of search controls including a search bar and a searchDisplayController.
Instead of using the native search bar, I want to use a button to trigger the search display control like that one in the latest facebook app.
I have tried to delete the search bar. But the display control failed directly.
I have tried to insert the search bar inside the tableView (Which I don't know its correct or not)
- (void)viewDidLoad
{
[self hideSearchBar];
}
- (void)hideSearchBar
{
self.UISearchBar.hidden = YES;
self.UISearchBar.bounds = CGRectMake(0, 0, 0, 0);
}
- (IBAction)SearchClicked:(UIButton *)sender {
[self.searchDisplayController setActive:YES animated:NO];
self.UISearchBar.hidden = NO;
}
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
[self hideSearchBar];
}
But the problem with it is:
When I cancel the search the scroll view is not return to its previous state. (There is a gap space where the hidden searchBar sits).
Instead of seeing this:
I want to see this when the cancel button is clicked in the search view.
How can I address this issue?
Can any body provide me with a better solution?
Thanks
A: So simple!
-(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar{
[self.searchDisplayController setActive:NO animated:YES];
self.navigationController popToViewController:UIViewControllerA animated:YES;
}
A: Create a CGPoint based on the scrollview's original center.
In viewDidLoad() :
self.originalCenter = scrollView.center;
And when your user closes the searchbar:
- (void)hideSearchBar
scrollView.center = self.originalCenter;
Where scrollView is whatever you've called your UIScrollView.
A: So finally instead of dragging a searchBar control into the storyboard.
I'm creating and destroying the searchBarControl on the fly.
-(void)initialiseSearch
{
//Start
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
searchBar.delegate = self;
searchBar.showsCancelButton = YES;
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self;
[self.view addSubview:searchBar];
searchBar.hidden = YES;
[searchDisplayController setActive:NO animated:NO];
// [self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:@"CustomSearch" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"search"];
//End
}
The method is called in the view did load.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19580503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to disable coffeescript on Rails 5 I started a new rails 5.1.4 project but I have forgotten to add --skip-coffee on rails new.
Is there a way to remove the coffeescript dependency without creating a new project?.
A: *
*Remove or comment out gem 'coffee-rails' from Gemfile.
*Change Javascript files that ends with .js.coffee to .js.
*Add config.generators.javascript_engine = :js to your application.rb.
*Make sure your tmp cache is cleared with rake tmp:cache:clear
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47784650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
}
|
Q: How to push data into widget using dashing dashboard I want to push numeric data from a file to my dashboard.
I am using the following .rb file as job for pushing the data
SCHEDULER.every '30s' do
var = File.open("/dashing/abhi/sample.txt", "r")
var.each_line do |line|
puts line
send_event('polarion', { value: var })
end
end
but the data is not being displayed in dashboard.
A: I think this should be:
SCHEDULER.every '30s' do
var = File.open("/dashing/abhi/sample.txt", "r")
var.each_line do |line|
puts line
send_event('polarion', { value: line })
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44948556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Properly resize main kivy window when soft keyboard appears on android I'm trying to use Window.softinput_mode to resize the window content when the soft keyboard appears:
softinput_mode = 'resize'
With this mode, the window is resized (i.e., window height is reduced by keyboard_height), but the keyboard still overlaps the content because, as it seems, the adapted window y coordinate is reduced by keyboard_height.
How can i vertically top-align the window content when the soft keyboard appears?
The modes 'pan' and 'below_target' didn't also help, because with them the window is moved along the y-axis (+ keyboard_height) so the top part of the window content is invisible.
EDIT:
A minimal code (taken and adapted from a kivy git-issue), that illustrates the described behavior when ran on Android:
http://pastebin.com/EzKCRMj7
A: The problem is solved by puting
if smode == 'resize':
y += kheight
in function Window.update_viewport(), I added the next code to my app in order to workout. DO NOT MUST CHANGE THE KIVY LIBS DIRECTLY
def update_viewport(self=Window):
from kivy.graphics.opengl import glViewport
from kivy.graphics.transformation import Matrix
from math import radians
w, h = self.system_size
if self._density != 1:
w, h = self.size
smode = self.softinput_mode
target = self._system_keyboard.target
targettop = max(0, target.to_window(0, target.y)[1]) if target else 0
kheight = self.keyboard_height
w2, h2 = w / 2., h / 2.
r = radians(self.rotation)
x, y = 0, 0
_h = h
if smode == 'pan':
y = kheight
elif smode == 'below_target':
y = 0 if kheight < targettop else (kheight - targettop)
if smode == 'scale':
_h -= kheight
if smode == 'resize':
y += kheight
# prepare the viewport
glViewport(x, y, w, _h)
# do projection matrix
projection_mat = Matrix()
projection_mat.view_clip(0.0, w, 0.0, h, -1.0, 1.0, 0)
self.render_context['projection_mat'] = projection_mat
# do modelview matrix
modelview_mat = Matrix().translate(w2, h2, 0)
modelview_mat = modelview_mat.multiply(Matrix().rotate(r, 0, 0, 1))
w, h = self.size
w2, h2 = w / 2., h / 2.
modelview_mat = modelview_mat.multiply(Matrix().translate(-w2, -h2, 0))
self.render_context['modelview_mat'] = modelview_mat
frag_modelview_mat = Matrix()
frag_modelview_mat.set(flat=modelview_mat.get())
self.render_context['frag_modelview_mat'] = frag_modelview_mat
# redraw canvas
self.canvas.ask_update()
# and update childs
self.update_childsize()
if __name__ == '__main__':
app = MainApp()
Window.update_viewport = update_viewport
Window.softinput_mode = 'resize'
app.run()
Have in count the import of Window and depending onn the kivy version kheight variable may have a different name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36770050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: python get pointer to an item in a nested dictionary/list combination based on a list of keys I have a data structure that looks something like this:
someData = {"apple":{"taste":"not bad","colors":["red","yellow"]},
"banana":{"taste":"perfection","shape":"banana shaped"},
"some list":[6,5,3,2,4,6,7]}
and a list of keys which describes a path to some item in this structure
someList = ["apple","colors",2]
I already have a function getPath(path) (see below) that is supposed to return a pointer to the selected object. It works fine for reading, but I get into trouble when trying to write
print(getPath(someList))
>> yellow
getPath(someList) = "green"
>> SyntaxError: can't assign to function call
a = getPath(someList)
a = "green"
print(getPath(someList))
>> "yellow"
Is there a way to make this work? Maybe like this:
someFunc(someList, "green")
print(getPath(someList))
>> green
This question looks like this question, except that I want to write something to that item, and not just read it.
My actual data can be seen here (I used json.loads() to parse the data). Note that I plan on adding stuff to this structure. I want a general approach to future proof the project.
My code:
def getPath(path):
nowSelection = jsonData
for i in path:
nowSelection = nowSelection[i]
return nowSelection
A: The result you're getting from getPath() is the immutable value from a dict or list. This value does not even know it's stored in a dict or list, and there's nothing you can do to change it. You have to change the dict/list itself.
Example:
a = {'hello': [0, 1, 2], 'world': 2}
b = a['hello'][1]
b = 99 # a is completely unaffected by this
Compare with:
a = {'hello': [0, 1, 2], 'world': 2}
b = a['hello'] # b is a list, which you can change
b[1] = 99 # now a is {'hello': [0, 99, 2], 'world': 2}
In your case, instead of following the path all the way to the value you want, go all the way except the last step, and then modify the dict/list you get from the penultimate step:
getPath(["apple","colors",2]) = "green" # doesn't work
getPath(["apple","colors"])[2] = "green" # should work
A: You could cache your getPath using custom caching function that allows you to manually populate saved cache.
from functools import wraps
def cached(func):
func.cache = {}
@wraps(func)
def wrapper(*args):
try:
return func.cache[args]
except KeyError:
func.cache[args] = result = func(*args)
return result
return wrapper
@cached
def getPath(l):
...
getPath.cache[(someList, )] = 'green'
getPath(someList) # -> 'green'
A: You can't literally do what you're trying to do. I think the closest you could get is to pass the new value in, then manually reassign it within the function:
someData = {"apple":{"taste":"not bad","colors":["red","yellow"]}, "banana":{"taste":"perfection","shape":"banana shaped"}, "some list":[6,5,3,2,4,6,7]}
def setPath(path, newElement):
nowSelection = someData
for i in path[:-1]: # Remove the last element of the path
nowSelection = nowSelection[i]
nowSelection[path[-1]] = newElement # Then use the last element here to do a reassignment
someList = ["apple","colors",1]
setPath(someList, "green")
print(someData)
{'apple': {'taste': 'not bad', 'colors': ['red', 'green']}, 'banana': {'taste': 'perfection', 'shape': 'banana shaped'}, 'some list': [6, 5, 3, 2, 4, 6, 7]}
I renamed it to setPath to reflect its purpose better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59323310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: SPSite in Visual Studio 2010 So instead of banging my head against the wall for another couple of hours, I thought I'd just double check a few things here.
First of all, I've been trying to access lists stored on a SharePoint 2007 server (which I should start off by saying is out of my control minus the fact that I'm a member of it who can edit list information) through Visual Studio 2010 on a Windows 7 64bit computer (that is not associated with the server in any real way). I say out of my control because a) the application I'm writing can't be stored on the server comp and b) I can't reconfigure any part of the server (since it's, well, out of my control and such...)
I started off by using web services to read the listitems from a certain list, which worked (to a certain extent.) I couldn't do any more testing because it was immediately recommendeded that I stop using that method and instead try to use SharePoint's own services (like by using Microsoft.Sharepoint and the respective .dll in my project.) I found plenty of tutorials on how to go about doing this online, but I keep getting hung up on one part: namely, the SPSite portion.
I know this question has been brought up dozens of times, but I just can't be sure of what exactly I need control over in order to get this working. Upon reaching this line of code:
SPSite siteCollection = new SPSite(siteUrl);
it fails every time. (Note that siteUrl is a string that leads to a working URL of the server that worked with the web services, so I don't see why it wouldn't work now.)
I've tested multiple .Net Frameworks (3.5, 4.0...) and changed my architecture around from x86 to x64 to Any CPU and it still always fails. Now I need credentials to get onto this website, so I'm assuming that's why I can't access it. Is there some sort of credentials I need to associate with my program in order to get this to work? Or would it ask for them if it successfully accessed that site?
Sorry for all of the confusion here, my mind has just been melting from trying to absorb all of this so quickly.
(On a little sidenote, is the .Net Framework requirement of 3.5 strict? Because this is a Microsoft Surface app, which means it needs a minimum of 4.0...) :P
A: The SharePoint server-side object model you were recommended to use can't be used for your scenario. It only works when run on a server that is a part of the SharePoint farm (which your code won't in this scenario). Since you're on 2007 (no client object model), you're stuck with the webservices (or writing and deploying your own web service code to a server in the SharePoint farm, which your code then calls).
A: Is this code running in the same App Pool as the SharePoint website? If not, your easiest bet would be to use the list service (/_vti_bin/Lists.asmx). SharePoint 2010 added the Client Object Model, but obviously you're excluded from that. Example code can be found here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11568922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sharing several variables using one file I'm trying to share two variables between two different processes: an array and an int. And I want to use the same file. When I call mmap(), and using the offset as I think it works, I get a segmentation fault when I try to use the int.
buf = (int *)mmap(NULL,N*sizeof(int),PROT_WRITE,MAP_SHARED,compart,0);
count = (int *)mmap(NULL,sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED,compart,N*sizeof(int));
*count = 0;
What I do is locate the array at the beginning of the file, and the int at the position following the size of the array.
Am I getting something wrong?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36304290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to prevent multiple Initialization of property from derived classes The code below is a short "summary" of my real project that contain only the relevant parts to understand my question. (and don`t want to ruin someones day with the original code).
imagine you have 4 classes: Division, Branch, Department and Team. every class inherits base class in that order.
The final goal: return one division object that holds List of 7 Branches, each Branch holds List of 7 Departments and each Department holds List of 7 Teams.
for example i will be able to reach from outside to every class instance:
division d = new division();
d.CreateDivisionStructure();
int Example = d.ListOfBranches[5].ListOfDepartments[4].ListOfTeam[3].SomeIntegerProperty;
(the original code has that lists, override functions, properties etc..)
the problem: imagine that protected string _myVar in the code below is a Datatable that needs to initialized via myVarproperty with heavy resource consuming SQL query. hence, my wish is to initialize protected string _myVar only one time for all the creation of the "division units structure". in the code below protected string _myVar will be null 64 times and will be initialized 64 times (for my understanding 7 times for each unit and one time for each base() call).
how can i achieve that?
i tried quite a lot other ways but could not solve that. I would appreciate any help, different way of thinking or advice.
class Program
{
static void Main(string[] args)
{
division d = new division();
d.CreateDivisionStructure();
Console.ReadLine();
}
}
class division
{
private static int CountHowManyTimesMyVarWasInitilized = 0;
public division()
{
}
protected string _myVar;
public string myVar
{
get
{
if (_myVar == null)
{
CountHowManyTimesMyVarWasInitilized++;
Console.WriteLine(CountHowManyTimesMyVarWasInitilized);
_myVar = "now myVar is not null";
return _myVar;
}
else
{ return _myVar; }
}
set { _myVar = value; }
}
public void CreateDivisionStructure()
{
Console.WriteLine(myVar);
for (int i = 0; i < 7; i++)
{
Branch b = new Branch(7);
}
}
}
class Branch : division
{
public Branch(bool dImDerivedClass)
{
// constructor for department to prevent recursive stackoverflow if base of department will call the empty constructor
}
public Branch(int NumberOfBranches)
{
Console.WriteLine(myVar);
Department d = new Department(7);
}
}
class Department : Branch
{
public Department(bool ImDerivedClass) : base(true)
{
// constructor for team to prevent recursive stackoverflow if base of Team will call the empty constructor
}
public Department(int numberOfDep) : base(true)
{
for (int i = 0; i < numberOfDep; i++)
{
Console.WriteLine(myVar);
Team t = new Team(7);
}
}
}
class Team : Department
{
public Team(int numberOfTeams) : base(true)
{
for (int i = 0; i < numberOfTeams; i++)
{
Console.WriteLine(myVar);
}
}
}
}
A: This is likely a good use of the Lazy<T> class, used in a static variable so there is only a single copy for the process. It will run the Func you give it once to initialize during the first access of the variable.
https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx
However, based on your class structure I'm not sure if it is the best approach. What is the purpose for the hierarchy of Branch : division and Department : Branch. Is the Branch a Division? If you are trying to share common properties as to not code them over again, I would suggest creating a common class that can hold those variables that Branch, Division, and Department can inherit from.
A: You can use a static variable / static constructor in the lowest class in the hierarchy. The static constructor will only be called once.
A: A simple solution is to use a "control" variable.
I'm sure you can improve your design and avoid this problem but I don't have time to check it now..
using System;
namespace Program
{
internal class Program
{
private static void Main(string[] args)
{
division d = new division();
d.CreateDivisionStructure();
Console.ReadLine();
}
}
internal class division
{
private static int CountHowManyTimesMyVarWasInitilized = 0;
public division()
{
}
protected string _myVar;
private bool _isReadyForInitialization;
public string myVar
{
get
{
if (!_isReadyForInitialization)
return null;
if (_myVar == null)
{
CountHowManyTimesMyVarWasInitilized++;
Console.WriteLine(CountHowManyTimesMyVarWasInitilized);
_myVar = "now myVar is not null";
return _myVar;
}
else
{ return _myVar; }
}
set { _myVar = value; }
}
public void CreateDivisionStructure()
{
// now _myVar is spposed to be initilized to all dirved clasess isnt is?
Console.WriteLine(myVar);
for (int i = 0; i < 7; i++)
{
Branch b = new Branch(7);
}
_isReadyForInitialization = true;
Console.WriteLine(myVar);
}
}
internal class Branch : division
{
public Branch(bool dImDerivedClass)
{
// constructor for department to prevent recursive stackoverflow if base of department will call the empty constructor
}
public Branch(int NumberOfBranches)
{
Console.WriteLine(myVar);
Department d = new Department(7);
}
}
internal class Department : Branch
{
public Department(bool ImDerivedClass) : base(true)
{
// constructor for team to prevent recursive stackoverflow if base of Team will call the empty constructor
}
public Department(int numberOfDep) : base(true)
{
for (int i = 0; i < numberOfDep; i++)
{
Console.WriteLine(myVar);
Team t = new Team(7);
}
}
}
internal class Team : Department
{
public Team():base(false)
{
}
public Team(int numberOfTeams) : base(true)
{
for (int i = 0; i < numberOfTeams; i++)
{
Console.WriteLine(myVar);
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39235456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Automatically update annotations in mx:ColumnChart So, I have a chart (simplified):
<fx:Declarations>
<mx:SolidColor id="solidColor" color="0x90ee90"/>
<mx:SolidColorStroke id="solidColorStroke" color="0x90ee90"/>
</fx:Declarations>
<mx:ColumnChart id="columnChart" width="100%" height="100%">
<mx:annotationElements>
<mx:CartesianDataCanvas id="cartesianDataCanvas" includeInRanges="true"/>
</mx:annotationElements>
<mx:horizontalAxis>
<mx:DateTimeAxis id="dateTimeAxis"/>
</mx:horizontalAxis>
<mx:horizontalAxisRenderers>
<mx:AxisRenderer axis="{dateTimeAxis}"/>
</mx:horizontalAxisRenderers>
<mx:verticalAxis>
<mx:LinearAxis id="linearAxis" baseAtZero="false"/>
</mx:verticalAxis>
<mx:verticalAxisRenderers>
<mx:AxisRenderer axis="{linearAxis}"/>
</mx:verticalAxisRenderers>
<mx:series>
<mx:ColumnSeries xField="time" yField="value" fill="{solidColor}" stroke="{solidColorStroke}"/>
</mx:series>
</mx:ColumnChart>
From time to time in chart is updated columnChart.dataProvider. I need to draw over this chart two horizontal lines (for min and max values) and yet something. I know that all of this can be drawn in annotationElements oncartesianDataCanvas.
The question is: At what point (or what event) should redraw the annotations so that they always match the actual data?
I tried to do it immediately after updating columnChart.dataProvider. But it's too early - in dateTimeAxis andlinearAxis did not have time to calculate the new min and max values. It is foolish to calculate them manually.
A: I believe you can try change event on ColumnChart as:
<mx:ColumnChart id="columnChart" width="100%" height="100%" change="handleChange(event)">
</mx:ColumnChart>
Then in the method handleChangeyou can do all the work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29864534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: last modified file date in node.js I'm trying to retrieve the last modified date of a file on the server using node.js.
I've tried
file.lastModified;
and
file.lastModifiedDate;
both come back as undefined.
A: For node v 4.0.0 and later:
fs.stat("/dir/file.txt", function(err, stats){
var mtime = stats.mtime;
console.log(mtime);
});
or synchronously:
var stats = fs.statSync("/dir/file.txt");
var mtime = stats.mtime;
console.log(mtime);
A: Just adding what Sandro said, if you want to perform the check as fast as possible without having to parse a date or anything, just get a timestamp in milliseconds (number), use mtimeMs.
Asynchronous example:
require('fs').stat('package.json', (err, stat) => console.log(stat.mtimeMs));
Synchronous:
console.log(require('fs').statSync('package.json').mtimeMs);
A: With Async/Await:
const fs = require('fs').promises;
const lastModifiedDate = (await fs.stat(filePath)).mtime;
A: You should use the stat function :
According to the documentation :
fs.stat(path, [callback])
Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. It looks like this:
{ dev: 2049
, ino: 305352
, mode: 16877
, nlink: 12
, uid: 1000
, gid: 1000
, rdev: 0
, size: 4096
, blksize: 4096
, blocks: 8
, atime: '2009-06-29T11:11:55Z'
, mtime: '2009-06-29T11:11:40Z'
, ctime: '2009-06-29T11:11:40Z'
}
As you can see, the mtime is the last modified time.
A: Here you can get the file's last modified time in seconds.
fs.stat("filename.json", function(err, stats){
let seconds = (new Date().getTime() - stats.mtime) / 1000;
console.log(`File modified ${seconds} ago`);
});
Outputs something like "File modified 300.9 seconds ago"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
}
|
Q: @DateTimeFormat annotation not working in Spring Controller I am following Spring Documentation 4. Through its guidelines I successfully collected the correctly formatted Date field.
The Controller Class is
@Controller
public class HomeController{
@RequestMapping("/home")
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("page1", "myForm", new MyForm());
}
}
MyForm Class has a field date annotated with @DateTimeFormat
public class MyForm{
@NumberFormat(style = Style.CURRENCY)
private Double value = 50.00;
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date date = new Date();
@NumberFormat(style = Style.CURRENCY)
public Double getValue() {
return value;
}
@DateTimeFormat(pattern = "dd/MM/yyyy")
public Date getDate() {
return date;
}
}
The JSP code that takes this myForm object and evaluates correctly formatted value of date field is
<spring:eval expression="myForm.date"/>
This far everything is correct. But when I try to use the date field inside my Spring Controller class
@Controller
public class HomeController {
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date date;
@RequestMapping("/home")
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
date = new Date();
return new ModelAndView("page1", "date", getDate());
}
@DateTimeFormat(pattern = "dd/MM/yyyy")
public Date getDate() {
return date;
}
}
The JSP code that takes this myForm object and evaluates incorrectly formatted value of date field is
<spring:eval expression="date"/>
It still displays the date but doesn't format it. Please explain why it formats a field in MyForm Class but not a field in Controller.
A: POJO MyForm is populated by Spring framework itself while submitting the form. Spring takes request parameters, convert into correct format and populate fields of your empty POJO but if you call methods annotated by @DateTimeFormat manually then it doesn't work as expected.
You have to use java SimpleDateFormat or joda DateTime in controller.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28956471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to replace selected text with stored text with JavaScript/jQuery? Let's say I have a textarea and I select some text (with my cursor):
Text
Text <-- selected text
Text
And lets say I have a variable called storedText. How do I got about to replace the selected text with the content of storedText?
Text
Stored Text <-- selected text
Text
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25859010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Variable Values in Java I have a quick question in regards to the value of how variable values work. I am working on a program right now, which looks like this:
public void run() {
println("There are " + ATOMS + " initially.");
int atoms = ATOMS;
int year = 0;
while (atoms > 0) {
for (int i = atoms; i > 0; i--) {
println(i);
if( rgen.nextBoolean() ) {
atoms--;
println("The total atoms is " + atoms);
}
println("The total for i is " + i + "\n" );
}
year++;
println("There are " + atoms + " at the end of year " + year );
}
}
At the part with the for loop, and setting the variable i to the value of atoms, is what has me confused. Lets say the value of atoms starts at 20. It goes through the for loop and lets assume that the first time through the RandomGenerator makes it true. So that subtracts 1 from atoms. Then after that the value of i should also be minused due to the i--. So my question is: When I set the variable i to the value of atoms does that just take i and set it to the initial value of 20? And then from there every time I adjust the value of i it is taking off of its own version of 20, and then when I change the value of atoms it, too has its own value. So when I subtract from atoms, that is not also being subtracted from i? That is the only way I can make sense of it because this program is written and works correctly, but that part has me confused.
Thank you very much in advance for any help!
A: Once you set the value of i=atoms, it no longer changes. It is the loop initializer, and will no longer be processed.
"i" of course will be decremented continuously (because of the i-- decrement).
But you can change the value of atoms to whatever and the results will not change.
A: i=atoms is the initialization in the for loop. So then on, value of i independent of atoms.
A: yes you have answered your own question. the variable i and atoms are two separate instances.
when you start the loop you are setting i equal to the same value as atoms but they are still separate variables. therefore inside the loop when you change the value of one it does not affect the other.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14692040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Installing an app to my home screen android I am looking for a way for when someone installs my application it goes in their "all applications menu". Then, after they run the app and go into the setup, when they click save on their options, it will create a shortcut on the home screen (not the all applications menu). Also, is it possible to have this shortcut not do the same thing as the other app? meaning that if I wanted to change the settings I could click on the app in the all applications menu and if I click on the app in the home screen it does something else.
A: First off, there's lots of different home screen implementations on Android. The stock Android one, Samsung, HTC and Motorola all have their own variants, then third party ones like Launcher Pro. All use different stores as to what to keep on the home screen, may provide different profiles for the home screen (home, work, etc).
Second, the home screen is prime real estate. And it is also the user's real estate. If there was programmatic access to the home screen, what happened to the Windows quick launch, desktop, favorites menu (in older versions of IE), and older pin area of the start menu (the very top of it in Win 95/98).
To quote Raymond Chen "I bet somebody got a really nice bonus for that feature". So, in short, even if it was possible, please don't. As awesome as you think your program is, the user might not think the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6576556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gradle runs fine under interactive account but not under NT service We have a batch file to build our Android application. It basically runs gradlew.bat assemble. When I remote desktop into the build machine (Windows 8) and run the batch file, everything builds as expected. However, when I invoke the batch file through an NT service, we start getting errors.
The account that the service runs under does have administrative privileges on the machine.
The first error was javax.net.ssl.SSLHandshakeException. Based on another post Android Studio Gradle build failed. Error:Cause: peer not authenticated, I modified gradle-wrapper.properties to use http instead of https for the distribution url. That took care of this problem.
The next error was also similar but this time it was with downloading pom file. Based on another post android- Gradle: An issue occurred configuring root project android studio, I modified build.gradle to use http://jcenter.bintray.com/ as the url instead of default https.
Now I am getting the following error:
Could not parse POM
http://jcenter.bintray.com/com/android/tools/build/gradle/1.1.0/gradle-1.1.0.pom
I am wondering why https could cause a problem in NT service account but not in normal interactive account. Is there a way to fix it? If not, would appreciate if someone has an insight on what the above error means. Regards.
A: A common source of problems when programs that execute successfully as an interactive user, but fail when run as a service, is the user settings surrounding the execution have changed. For example, when you run Gradle, there are settings in %USERPROFILE% \ .gradle (typically c:\users\<username>, which for you logged in interactively is different than the account under which the service is running.)
When you run as a service, there is a different user profile, or possibly none at all. Have your batch script dump the environment (add "set" near the top of the .bat file - this will dump an alphabetical list of environment variables), and compare the output when it runs as a service to when you run it interactively. See if USERPROFILE is defined, and if it is compare the .gradle folder in the service's area to your own .gradle folder.
In addition to Gradle settings, Gradle's cache is also typically under the .gradle folder. Your cache is likely to contain different items than the cache of the service, which may be significant if there are authentication issues in the external repositories to which your build tries to connect (again, possibly as a result of the different credentials in your user configurations!)
The tool processing the https request may look for certificates somewhere in your user profile. You may have accepted a certificate (used to 'recognize' an https server) that is not included in the accepted certificates of the service. These would likely be in the .keystore file in your user profile. Java's keytool.exe can help to decode and dump this file.
Other tools involved in your build may also have settings stored in the USERPROFILE space, which differ between your space and that of the service account - for example Android (.android), Java, Maven (.m2), Git (.gitconfig), etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36731213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: problems installing scrapy ..missing gcc 4.0 I am having trouble installing scrapy with easy_install, I get:
unable to execute gcc-4.0: No such file or directory
error: Setup script exited with error: command 'gcc-4.0' failed with exit status 1
I have gcc-4.2. I've been trying to downgrade to gcc-4.0 but cannot figure out a way ...
A: You need to setup your environment:
*
*First, install Command Line Tools for Xcode (I'm not 100% sure that you can install without XCode, if not then install XCode from App Store).
*Then install MacPorts
To complete macports setup run this command in Terminal.app:
% sudo port selfupdate
If you done, then you can install scapry from macports:
% sudo port install py27-scrapy
Afther this you should be able to use scrapy command in Terminal.app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11510809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: pytest: selective log levels on a per-module basis I'm using pytest-3.7.1 which has good support for logging, including live logging to stdout during tests. I'm using --log-cli-level=DEBUG to dump all debug-level logging to the console as it happens.
The problem I have is that --log-cli-level=DEBUG turns on debug logging for all modules in my test program, including third-party dependencies, and it floods the log with a lot of uninteresting output.
Python's logging module has the ability to set logging levels per module. This enables selective logging - for example, in a normal Python program I can turn on debugging for just one or two of my own modules, and restrict the log output to just those, or set different log levels for each module. This enables turning off debug-level logging for noisy libraries.
So what I'd like to do is apply the same concept to pytest's logging - i.e. specify a logging level, from the command line, for specific non-root loggers. For example, if I have a module called test_foo.py then I'm looking for a way to set the log level for this module from the command line.
I'm prepared to roll-my-own if necessary (I know how to add custom arguments to pytest), but before I do that I just want to be sure that there isn't already a solution. Is anyone aware of one?
A: I had the same problem, and found a solution in another answer:
Instead of --log-cli-level=DEBUG, use --log-level DEBUG. It disables all third-party module logs (in my case, I had plenty of matplotlib logs), but still outputs your app logs for each test that fails.
A: I got this working by writing a factory class and using it to set the level of the root logger to logger.INFO and use the logging level from the command line for all the loggers obtained from the factory. If the logging level from the command line is higher than the minimum global log level you specify in the class (using constant MINIMUM_GLOBAL_LOG_LEVEL), the global log level isn't changed.
import logging
MODULE_FIELD_WIDTH_IN_CHARS = '20'
LINE_NO_FIELD_WIDTH_IN_CHARS = '3'
LEVEL_NAME_FIELD_WIDTH_IN_CHARS = '8'
MINIMUM_GLOBAL_LOG_LEVEL = logging.INFO
class EasyLogger():
root_logger = logging.getLogger()
specified_log_level = root_logger.level
format_string = '{asctime} '
format_string += '{module:>' + MODULE_FIELD_WIDTH_IN_CHARS + 's}'
format_string += '[{lineno:' + LINE_NO_FIELD_WIDTH_IN_CHARS + 'd}]'
format_string += '[{levelname:^' + LEVEL_NAME_FIELD_WIDTH_IN_CHARS + 's}]: '
format_string += '{message}'
level_change_warning_sent = False
@classmethod
def get_logger(cls, logger_name):
if not EasyLogger._logger_has_format(cls.root_logger, cls.format_string):
EasyLogger._setup_root_logger()
logger = logging.getLogger(logger_name)
logger.setLevel(cls.specified_log_level)
return logger
@classmethod
def _setup_root_logger(cls):
formatter = logging.Formatter(fmt=cls.format_string, style='{')
if not cls.root_logger.hasHandlers():
handler = logging.StreamHandler()
cls.root_logger.addHandler(handler)
for handler in cls.root_logger.handlers:
handler.setFormatter(formatter)
cls.root_logger.setLevel(MINIMUM_GLOBAL_LOG_LEVEL)
if (cls.specified_log_level < MINIMUM_GLOBAL_LOG_LEVEL and
cls.level_change_warning_sent is False):
cls.root_logger.log(
max(cls.specified_log_level, logging.WARNING),
"Setting log level for %s class to %s, all others to %s" % (
__name__,
cls.specified_log_level,
MINIMUM_GLOBAL_LOG_LEVEL
)
)
cls.level_change_warning_sent = True
@staticmethod
def _logger_has_format(logger, format_string):
for handler in logger.handlers:
return handler.format == format_string
return False
The above class is then used to send logs normally as you would with a logging.logger object as follows:
from EasyLogger import EasyLogger
class MySuperAwesomeClass():
def __init__(self):
self.logger = EasyLogger.get_logger(__name__)
def foo(self):
self.logger.debug("debug message")
self.logger.info("info message")
self.logger.warning("warning message")
self.logger.critical("critical message")
self.logger.error("error message")
A: Enable/Disable/Modify the log level of any module in Python:
logging.getLogger("module_name").setLevel(logging.log_level)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52086974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: How to reduce the width of dropdown-menu? I am using bootstrap 3 to create a simple drop-down menu, but I want to decrease its width and I can't figure it out how to do this.
HTML:
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#">Action</a></li>
<li><a href="#">Another</a></li>
<li><a href="#">Something</a></li>
<li><a href="#">Separated</a></li>
</ul>
</div>
CSS:
.dropdown-menu {
width: 60px !important;
}
A: .dropdown-menu has min-width: 160px; and min-width overrides width so you can not change width you can use min-width instead of width.
.dropdown-menu {
min-width: 60px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#">Action</a>
</li>
<li><a href="#">Another</a>
</li>
<li><a href="#">Something</a>
</li>
<li><a href="#">Separated</a>
</li>
</ul>
</div>
It works. You should call bootstrap lib and jquery. Please, read bootstrap documentation.
Jsfiddle
A: Give a ID for the div and specify the min-width in the css as follows:
.dropdown #mydiv{ min-width:60px; }
Note: Do NOT use '!important'.
For more information check out this great post by Chris Coyier : Specifics on CSS Specificity
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33755750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Increasing number once per mouse click/key press in XNA This has been bothering me lately- when I use some code like below to increase selection every mouse click:
if (m.LeftButton == ButtonState.Pressed)
currentSelection++;
Then currentSelection increases by a ton, simply because this code is in my Update() function and by design, runs every frame and so increases currentSelection. There is almost no chance you can click and release fast enough to prevent currentSelection from increasing more than one.
Now my question is what I should do to make it so everytime I click the mouse down once, it only increases currentSelection once until the next time I click down again.
A: You will need to compare the current mouse state and the last update's mouse state.
In your class you'll have MouseState mouseStateCurrent, mouseStatePrevious; declared and so it'll be something like:
mouseStateCurrent = Mouse.GetState();
if (mouseStateCurrent.LeftButton == ButtonState.Pressed &&
mouseStatePrevious.LeftButton == ButtonState.Released)
{
currentSelection++;
}
mouseStatePrevious = mouseStateCurrent;
So it will detect that previous time you pressed it, then you release it - only then it is considered as a click and it will add to currentSelection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2395107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: The analyzer produces case_block_not_terminated in a case block with nested if/else statement, although return statement is executable I have a case that I would like to understand.
If I have following Switch Case statement with nested if/else:
f(int x, int y) {
switch (x) {
case 0:
if (y > 10) {
return 'StringA';
} else {
return 'StringB';
}
default:
return 'Anything';
}
}
the analyses throws an error: case_block_not_terminated
case_block_not_terminated: The last statement of the ‘case’ should be
‘break’, ‘continue’, ‘rethrow’, ‘return’, or ‘throw’.
if I add a break; at the end of the case statement the error disappears, but it is clearly dead code, because one of the return statements should be executed.
f(int x, int y) {
switch (x) {
case 0:
if (y > 10) {
return 'StringA';
} else {
return 'StringB';
}
break;
default:
return 'Anything';
}
}
A: This issue should go away when you enable the null-safety feature. The analyzer's code flow analysis has been much improved for NNBD to fix this and similar cases. (You can verify this in DartPad with null-safety enabled.)
In the meantime, you also could just remove the superfluous else:
String f(int x, int y) {
switch (x) {
case 0:
if (y > 10) {
return 'StringA';
}
return 'StringB';
default:
return 'Anything';
}
}
or remove the superfluous default case:
String f(int x, int y) {
switch (x) {
case 0:
if (y > 10) {
return 'StringA';
} else {
return 'StringB';
}
}
return 'Anything';
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65485181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: slideUp different on actual page I am trying to use the slideUp() JQuery function on a bunch of items without images. The code I've written works fine in JSFiddle, but on my actual page, it collapses in a clunky way.
Why are they not acting the same way?
JSFiddle
To activate the function on the page, press the checkbox in the right menu
Real page
A: Sifting through CSS for a few minutes and I found a solution, I have made a list of corrections.
Here is the CSS code on pastebin, it does all the fixes I have mentioned below.
Manual Fix
Find #middlewrapper #content .contentbox, disable float:left.
#middlewrapper #content .contentbox {
width: 650px;
padding: 15px;
/* float: left; */
background-color: white;
}
Find #middlewrapper #content .contentbox_shadow, disable float:left.
#middlewrapper #content .contentbox_shadow {
width: 690px;
height: 20px;
/* float: left; */
background-image: url('http://xn--nstvedhandel-6cb.dk/naestved/public/css/../images/content_skygge.png');
background-repeat: no-repeat;
}
Find #middlewrapper #content, disable float:left.
#middlewrapper #content {
width: 690px;
/* float: left; */
}
Finally, find #middlewrapper #content .contentbox, after it's definition, place #content.
#content {
width: 680px;
float: left;
}
Do not delete or alter the definition of #middlewrapper #content found a few lines later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17334760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to parse HTML tags as raw text using ElementTree I have a file that has HTML within XML tags and I want that HTML as raw text, rather than have it be parsed as children of the XML tag. Here's an example:
import xml.etree.ElementTree as ET
root = ET.fromstring("<root><text><p>This is some text that I want to read</p></text></root>")
If i try:
root.find('text').text
It returns no output
but root.find('text/p').text will return the paragraph text without the tags. I want everything within the text tag as raw text, but I can't figure out how to get this.
A: Your solution is reasonable. An element object is the list of children. The .text attribute of the element object is related only to things (usually a text) that are not part of other (nested) elements.
There are things to be improved in your code. In Python, string concatenation is an expensive operation. It is better to build the list of substrings and to join them later -- like this:
output_lst = []
for child in root.find('text'):
output_lst.append(ET.tostring(child, encoding="unicode"))
output_text = ''.join(output_lst)
The list can be also build using the Python list comprehension construct, so the code would change to:
output_lst = [ET.tostring(child, encoding="unicode") for child in root.find('text')]
output_text = ''.join(output_lst)
The .join can consume any iterable that produces strings. This way the list need not to be constructed in advance. Instead, a generator expression (that is what can be seen inside the [] of the list comprehension) can be used:
output_text = ''.join(ET.tostring(child, encoding="unicode") for child in root.find('text'))
The one-liner can be formatted to more lines to make it more readable:
output_text = ''.join(ET.tostring(child, encoding="unicode")
for child in root.find('text'))
A: I was able to get what I wanted by appending all child elements of my text tag to a string using ET.tostring:
output_text = ""
for child in root.find('text'):
output_text += ET.tostring(child, encoding="unicode")
>>>output_text
>>>"<p>This is some text that I want to read</p>"
A: Above solutions will miss initial part of your html if your content begins with text. E.g.
<root><text>This is <i>some text</i> that I want to read</text></root>
You can do that:
node = root.find('text')
output_list = [node.text] if node.text else []
output_list += [ET.tostring(child, encoding="unicode") for child in node]
output_text = ''.join(output_list)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24393029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating a REST API with MySQL and PHP formatted as a JSON response I'm trying to create a public REST API from scratch without using any framework and I've created where it retrieve all the data as JSON response when the user enter in this at the end of the address "...?list=all" However, I want to retrieve a row by an ID or retrieving the most popular items. I know that I will probably have to change that in the query string, but how would I create the end of the address that retrieves it? like ?ID=05 (retrieving row ID 5 from database) or TOP=15 (retrieving top popular 15). If there's a better or more efficient way to rewrite my code, feel free to let me know.
<?php
// Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
die('SQL ERROR: Connection failed: '.mysqli_error($db));
exit;
}
return $db;
}
//call the passed in function
if(function_exists($_GET['list'])) {
$_GET['list']();
}
//methods
function all(){
$db = getMysqlDB();
$query = "SELECT * FROM books;";
$books_sql = mysqli_query($db, $query);
$books = array();
while($book = mysqli_fetch_array($books_sql)) {
$books[] = $book;
}
$books = json_encode($books);
echo $_GET['jsoncallback'].$books;
}
?>
A: A simple start for a PHP based REST API would be:
<?php
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
// connect to the mysql database
$link = mysqli_connect('localhost', 'user', 'pass', 'dbname');
mysqli_set_charset($link,'utf8');
// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
if ($value===null) return null;
return mysqli_real_escape_string($link,(string)$value);
},array_values($input));
// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
$set.=($i>0?',':'').'`'.$columns[$i].'`=';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
// create SQL based on HTTP method
switch ($method) {
case 'GET':
$sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
case 'PUT':
$sql = "update `$table` set $set where id=$key"; break;
case 'POST':
$sql = "insert into `$table` set $set"; break;
case 'DELETE':
$sql = "delete `$table` where id=$key"; break;
}
// excecute SQL statement
$result = mysqli_query($link,$sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error());
}
// print results, insert id or affected row count
if ($method == 'GET') {
if (!$key) echo '[';
for ($i=0;$i<mysqli_num_rows($result);$i++) {
echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
}
if (!$key) echo ']';
} elseif ($method == 'POST') {
echo mysqli_insert_id($link);
} else {
echo mysqli_affected_rows($link);
}
// close mysql connection
mysqli_close($link);
source
For a more complete implementation check out:
https://github.com/mevdschee/php-crud-api
Disclosure: I am the author.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30059250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MongoDB java drivers not compatible in Android I am trying to delete a document from MongoDB (database present at http://mlab.com) through my Android application, but since mongo-db-java-drivers are not compatible with Android so therefore I am getting different Exceptions. So please tell is there any way to delete from MongoDB through Android application?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37289664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I get the text decoding of the Chinese? Python in the Chinese part of the result of requests.get (url) is
"æ ?? ¯ä¸? ǧ? Å? ¯ä» ¥ è ?? ªç? ± å? ¼å? ¸ç? ??? Æ ???? è§? ï¼ "
came out in this way.
How it is necessary to decode Can you print Chinese characters?
In the following method, source and other statements will be output.
*
*result.content.decode("gbk","ignore").encode("utf-8","ignore")
*content.encode('utf-8').decode('gbk')
Example of a site is here. https://lvyou.baidu.com/notes/20fd27d671563fe1e8927d21?sid=9739db6e97289b7e6b22f9ea?request_id=831992042&idx=0
Let us know would really appreciate.
A: The problem has been resolved.
Set the encoding option in requests, we were able to obtain the required value.
Thank you very much.
sub_result = requests.get(sub_url)
sub_result.encoding = 'utf-8'
sub_soup = BeautifulSoup(sub_result.text, 'lxml')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38610329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: JUnit @After not executing when Jenkins pipeline is stopped I'm working with a declarative Jenkins pipeline that runs some tests which make use of JUnit 4. In the tests there are @After methods where test cleanup occurs. When a pipeline is aborted during a test I've confirmed that the @After methods are never executed (confirmed using log statements in the @After methods and checking the Jenkins console log).
This leaves test data (e.g. users that the tests use) in a bad state and cause later tests (and pipeline builds) to fail, so it's an issue.
The pipeline is aborted via the Jenkins UI "stop" button, or through the pipeline hitting a timeout for that stage. In both cases the pipeline exits with code 143, which is a SIGTERM.
How can I ensure that JUnit 4.x @After methods are executed when a declarative Jenkins pipeline is aborted?
A: I have a workaround that you could use to solve the issue. Create two classes. TestClass and AfterClass. In the AfterClass, you will have to keep one test method so that after will get triggered. Now, In test execution step of declarative pipeline, you can execute
mvn clean test -PTest
and in the post always of declarative pipeline script, you can execute below maven command
mvn clean test -PCleanup
TestClass:
import org.junit.Test;
public class TestClass
{
@Test
public void testClass()
{
System.out.println("Test");
}
}
AfterClass:
@Test
public void beforeCleanUp()
{
System.out.println("Before Cleanup");
}
@After
public void after()
{
System.out.println("After");
}
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>stackovrflw-62492859</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>Test</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<test>com.test.junit.classes.TestClass</test>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>Cleanup</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<test>com.test.junit.classes.AfterClass</test>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Note: This is not the actual solution as I do not have much experience on JUnit. But you could use this workaround, if you do not get any proper solution. I will be also trying to find proper solution for you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62492859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: POST Method not using Params I dont know why the getParams() is not working in my method?
The System.out.println works fine under getHeaders but not under getParams?
//---------------------------------------POST request with headers---------------------------------------
public void post(String url, final String param1, final String param2, String source) {
// Request a string response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,
getReponse(source), createMyReqErrorListener()) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("loginAlias", "username");
params.put("loginPassword", "12345");
System.out.println("Params are: " + params.toString());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put(ACCEPT, ACCEPT_JSON); //Accepting JSON
headers.put(AUTH_ID, AUTH_ID_VALUE);
headers.put(PLATFORM, PLATFORM_VALUE);
headers.put(CID, "");
headers.put(DEVICE_TYPE_MOBILE, DEVICE_TYPE_MOBILE_VALUE);
System.out.println("Headers are: " + headers.toString());
return headers;
}
};
// Add the request to the RequestQueue.
queue.add(request);
}
I have followed all the Google Volley documentation and tried a couple options on SO but for some reason, this does not work?
Thanks
A: also faced the same issue, Finally I found that there is some issue with volley - JSONObject request. (after few googling!)
the getParams() doesn't invoke because JsonObjectRequest extended JsonRequest which invoke getBody() directly to encoding the constructor second parameter(call requestBody) as contentType, that's why it ignore your getParam() method.
try this solution, it resolved my problem.
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
In activity/fragment do use this
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());
requestQueue.add(jsObjRequest);
Volley JsonObjectRequest Post request not working
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31941149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can you put a Canvas instance inside a jQuery gallery? I've made several simple particle and game examples using Canvas and KineticJS and I was thinking about the using a slider like Nivo to show them off. First thoughts are that I would need to redraw each canvas on transition of the slider, but I was just wondering if anyone has tried this already with any success or failures and if it's feasible?
A: Try:
var mystage = stage.toImage(config);
to convert the canvas to an image, then you can transition images.
But if you want the whole stage saved as an object you just do:
var json = stage.toJSON();
and that saves your stage for reloading later, which you can do with:
var stage = Kinetic.Node.create(json, 'container');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11579539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not getting detailed error log for java application on Tomcat on Azure App Service We deployed a java web application (WAR file) onto an Azure App Service with newest Tomcat (8.5). The WAR file is detected by Azure but on startup we are seeing the following in the catalina.date.log
06-Feb-2018 07:57:24.494 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
06-Feb-2018 07:57:24.512 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.20
06-Feb-2018 07:57:27.697 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [D:\home\site\wwwroot\webapps\myapp.war]
06-Feb-2018 07:59:16.570 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
06-Feb-2018 07:59:16.570 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Context [/myapp] startup failed due to previous errors
06-Feb-2018 07:59:16.629 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [D:\home\site\wwwroot\webapps\myapp.war] has finished in [108,932] ms
We cannot find this log file anywhere. We have set all possible logging settings to verbose. Should this be a separate file or are some logging settings missing?
We also see the follwing row
06-Feb-2018 12:00:43.922 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=D:\Program Files (x86)\apache-tomcat-8.5.20\conf\logging.properties
It is not possible for us to change this file.
A: Azure Web services are deployed to a Windows Server 2016.
You can access the log files and change the location of the log files using
*
*Open the url https://<app service name>.scm.azurewebsites.net/DebugConsole {or choose Menu > Debug Console > CMD)
*Type the dir command to go the location of the tomcat install. For example dir D:\Program Files (x86)\apache-tomcat-8.5.6\conf
*Alternatively you can also click on the folder name dispalyed above the command/terminal
*In your case, to enable detailed logging, open logging.properties under \Program Files (x86)\apache-tomcat-8.5.6\conf and set 1catalina.org.apache.juli.FileHandler.level = FINE. You can read more info at Documentation on Apache Tomcat 8.5 Logging
Sample screen from my Tomcat setup as a webservice:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48642837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Directive with and indirection I have several multi-selects on a page, each with a bit of logic that fills that multi-select from the server, and I want to wrap each one up into a Directive.
Before trying to wrap these into Directives, I built each as such:
index.html
<select name="groups" ng-model="inputs.groups" ng-change="groupsChanged()" ng-options="g for g in allgroups" multiple></select>
controllers.js
In the first pass, I do my $http calls from here. Yes, I know, not best practices, but I wanted to prove that this works to myself first.
$scope.loadSelect = function(_url) {
$http({
url: _url,
method: 'POST',
data: $scope.inputs,
model: 'all' + _url
}).success(function(data, status, headers, config) {
$scope[config.model] = data;
});
};
// Fill groups
$scope.loadSelect('groups');
// When groups change, reload other select fields that depend on groups
$scope.groupsChanged = function() {
$scope.loadSelect('categories');
$scope.loadSelect('actions');
}
Now I want to migrate this to a Directive. I see two major challenges:
1.) How do I encapsulate the entire set of options (e.g. what is now the "allgroups" model) into the Directive?
2.) Based on initial experiments, I tried to physically build the <select/> into the template, but realized that I have to manipulate the DOM to physically replace name, ng-model, and ng-options. That lead me to the compile attribute, but a.) that feels wrong and b.) setting <select ng-options="x for x in allgroups" /> doesn't actually repeat after it's been inserted into the DOM. Using compile doesn't feel right; what's the right way to approach this?
Here is my first attempt at the Directive looks like this. It doesn't really work, and I think I'm going about it incorrectly:
index.html
<dimension ng-model="inputs.users" alloptions-model="allusers">Users</dimension>
directives.js
directive('dimension', function() {
return {
restrict: 'E',
scope: {
ngModel: '=',
alloptionsModel: '='
},
template:
'<div>' +
'<label ng-transclude></label>' +
'<fieldset>' +
'<div class="form-group">' +
'<select ng-model="{{ngModel}}" ng-options="x for x in {{alloptionsModel}}" multiple class="form-control"></select>' +
'</div>' +
'</fieldset>' +
'</div>',
replace: true,
transclude: true
};
});
Clearly I haven't even gotten to the server load part yet, but I plan to roll that into a controller in the Directive, with the actual $http call in a service.
I feel like I'm moving down the wrong track. If you have suggestions on how to realign, please help!
A: The main problem with your directive is that you can't use mustache binding in ngModel and ngOptions directive because they are evaluated directly. You can directly bind to the scoped property (ngModel and alloptionsModel):
directive('dimension', function() {
return {
restrict: 'E',
scope: {
ngModel: '=',
alloptionsModel: '='
},
template:
'<div>' +
'<label ng-transclude></label>' +
'<fieldset>' +
'<div class="form-group">' +
'<select ng-model="ngModel" ng-options="x for x in alloptionsModel" multiple class="form-control"></select>' +
'</div>' +
'</fieldset>' +
'</div>',
replace: true,
transclude: true
};
});
See this plunkr for a working example.
Edit
As for the compile route, there is nothing wrong with it. It is useful when you need to dynamically create a template which will clearly be your case when you will get to the select's item template.
compile: function(tElement, tAttrs) {
var select = tElement.find('select'),
value = tAttrs.value ? 'x.' + tAttrs.value : 'x',
label = tAttrs.label ? 'x.' + tAttrs.label : 'x',
ngOptions = value + ' as ' + label + ' for x in alloptionsModel';
select.attr('ng-options', ngOptions);
}
// In the HTML file
<dimension ng-model="inputs.users"
alloptions-model="allusers"
label="name">
Users
</dimension>
I've updated the plunkr with the compile function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18273632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using a Logic App Condition To Compare Multiple Values From The Same Field I am trying to setup a condition that compares multiple values in a field. So if the field contains 1,2 3 do this otherwise do something else. As shown in the attached image. However this only goes false if the field contains the first value. If the second or third value is contained it goes true. How can I make it false for all three values?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68127477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pass input html data to a javascript function as its variables and get a response My problem: I can't get to pass the input data from html to js function as its variables and get the appropriate response.
My goal: when the user clics on submit button he receives whatever response the js function provided.
I have two files in the same directory:
- index.html
- index.js
index.js content:
function quEq(a, b, c) {
var delta = (b ** 2) - (4 * a * c);
if (a == 0) {
return "Not a quadratic equation";
};
if (delta < 0) {
return "Complex root! No solution in real numbers";
} else {
var first= (-b + Math.sqrt(delta)) / (2*a);
var second= (-b - Math.sqrt(delta)) / (2*a);
return {first, second};
};
};
index.html content:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="index.js"></script>
<title>Quadratic Equation</title>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="bg-red-400">
<div class="">
<form>
<div class="form-group">
<label>Enter 'a' value</label>
<input type="number" class="form-control" id="a" placeholder="1">
<label>Enter 'b' value</label>
<input type="number" class="form-control" id="b" placeholder="5">
<label>Enter 'c' value</label>
<input type="number" class="form-control" id="c" placeholder="6">
<button onclick="quEq(document.getElementById('a').nodeValue, document.getElementById('b').value, document.getElementById('c').value)" type="submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
THANK YOU FOR YOUR HELP
I HOPE I AM NOT BREAKING ANY RULES
A: Your onclick event handler should successfully handle the click event, but it isn't clear what you want to do with the return value of your function. The browser will not do anything by default. Instead, you need to manage this yourself.
For example, you could write the results into some other part of the DOM.
In your HTML you can create some nodes to hold the output:
<div id="result-1" />
<div id="result-2" />
Then in your event handler:
document.getElementById('result-1').innerText = first;
document.getElementById('result-2').innerText = second;
A: You have a variety of HTML and JavaScript syntax errors.
See comments in the code below:
// Get references to the DOM elements that you'll work with
var btn = document.querySelector("button");
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');
// Do event binding in JavaScript, not with inline HTML attributes
btn.addEventListener("click", function(){
// Use "value", not "nodeValue"
quEq(a.value, b.value, c.value);
});
function quEq(a, b, c) {
// Carefull with syntax!
var delta = (b * 2) - (4 * a * c);
if (a == 0) {
// return doesn't show up anywhere
alert("Not a quadratic equation");
} else if (delta < 0) {
alert("Complex root! No solution in real numbers");
} else {
var first= (-b + Math.sqrt(delta)) / (2*a);
var second= (-b - Math.sqrt(delta)) / (2*a);
alert(first + " " + second);
}
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="index.js"></script>
<title>Quadratic Equation</title>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="bg-red-400">
<div class="">
<form>
<div class="form-group">
<label for="a">Enter 'a' value</label>
<input type="number" class="form-control" id="a" placeholder="1">
<label for="b">Enter 'b' value</label>
<input type="number" class="form-control" id="b" placeholder="5">
<label for="c">Enter 'c' value</label>
<input type="number" class="form-control" id="c" placeholder="6">
<button type="button" class="btn btn-primary">Submit</button>
</div>
<!-- The followng line doesn't have a closing tag and so is invalid. -->
<!-- <div class="form-group"> -->
</form>
</div>
</div>
</div>
</div>
</body>
</html>
A: I see two flaws in this code
1)
document.getElementById('a').nodeValue
instead of
document.getElementById('a').value
2) you should be aware that placeholder is just a text, it seems strange that you can see 6 but there's no number yet, so instead of placeholder set value attribute directly if you want some default numbers
<input type="number" class="form-control" id="a" value="1">
A: Now its working
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
c: <input type="number" name="c" id="c"><br>
<button onclick="quEq(document.getElementById('a').value,document.getElementById('b').value,document.getElementById('c').value)">Submit</button>
<script>
function quEq(a, b, c) {
var delta = (b ** 2) - (4 * a * c);
if (a == 0) {
alert("Not a quadratic equation");
};
if (delta < 0) {
alert("Complex root! No solution in real numbers");
} else {
var first= (-b + Math.sqrt(delta)) / (2*a);
var second= (-b - Math.sqrt(delta)) / (2*a);
alert(first, second);
};
};
</script>
</body>
A: There are a couple of things in your index.html file that are not correct, for example, you opened a second div with a class "form-group" yet you did not close it, also you did not pass properly the value for "a" (.nodeValue when it should be .value).
I made some changes to your code and appended the response in the div you weren't using (the second "form-group") and changed it's name, also I added type="button" to your button so it won't submit as soon as you click on it, you can find the html and js in codepen
Here is your function:
function quEq() {
var a = document.getElementById('a').value
var b = document.getElementById('b').value
var c = document.getElementById('c').value
var delta = (b ** 2) - (4 * a * c)
if (a == 0) {
document.getElementsByClassName("info")[0].innerHTML = "Not a quadratic equation"
}
if (delta < 0) {
document.getElementsByClassName("info")[0].innerHTML = "Complex root! No solution in real numbers"
}
else {
var first= (-b + Math.sqrt(delta)) / (2*a)
var second= (-b - Math.sqrt(delta)) / (2*a);
document.getElementsByClassName("info")[0].innerHTML = first + ", " + second
}
}
Here is your div changed:
<div class="container">
<div class="row justify-content-center">
<div class="bg-red-400">
<div>
<form>
<div class="form-group">
<label>Enter 'a' value</label>
<input type="number" class="form-control" id="a" placeholder="1" value="1"/>
<label>Enter 'b' value</label>
<input type="number" class="form-control" id="b" placeholder="5" value="5" />
<label>Enter 'c' value</label>
<input type="number" class="form-control" id="c" placeholder="6" value="6" />
<button onclick="quEq()" type="button" class="btn btn-primary">Submit</button>
</div>
<div class="info"></div>
</form>
</div>
</div>
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59513269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "Book like" view in Openseadragon (several "2 pages" sequences) Openseadragon newbbie here !
I'm trying to display images by group of 2 AND keeping sequence mode activated, so I can "turn pages".
I managed to display 2 pages, I managed to read pages 1 by 1 in sequence mode, ...
But I just didn't find a way to do both.
To display 2 pages, I loaded 2 tiles sets and configured "sequenceMode=false". Then I set coordinates, to display visuals aside.
To read pages 1 by 1, I loaded several tiles and configured "sequenceMode = true".
What I would like to do is display two visuals (= tiles sets) aside (like an open book). And then, on "next" button click, display the two next visuals from my "tilesSources" array... and so on !
Thank you for your help !
A: I recommend keeping sequence mode off, like you did for the two pages, and lay out the entire sequence (in pairs) that way. You should then create your own next/previous buttons and use viewer.viewport.fitBounds to animate the viewer to each pair as needed.
Here's an example of a system that does something like that (plus a lot more):
https://iangilman.com/osd/test/demo/m2/
Press the "book" button at the top to see the "two-page" mode. The code for this is here:
https://github.com/openseadragon/openseadragon/tree/master/test/demo/m2
Of course you don't need all of that code, but hopefully it can be a helpful reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61009639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: move camera with player [unity] using System.Collections.Generic;
using UnityEngine;
public class follow_mainship : MonoBehaviour
{
public Transform Playerposition;
private Vector3 cameraoffset;
// Start is called before the first frame update
void Start()
{
cameraoffset = Playerposition.position - transform.position;
}
// Update is called once per frame
void Update()
{
Vector3 newpos = Playerposition.position + cameraoffset;
}
}
I am using this code to move camera with my player, but it is not working. I have added my object in the Playerposition box. What should I do?
Update:
As per the answer, camera is following my ship, whenever the ship touches the ground, the camera flies back a long distance. Is there any way to fix it?
A: Your logic to get the new position is correct, but in your Update() function, you have to update the position of the camera using transform.position, assuming this script is a component you have added to the Camera in the scene.
// Update is called once per frame
void Update()
{
Vector3 newpos = Playerposition.position + cameraoffset;
transform.position = newpos;
}
If this script isn't on the camera, you'll need a reference to the camera by taking it as an input in the Unity inspector (declaring public Camera cam; at the top of your class) and then set in in the inspector by dragging the camera object onto that input. Then you can do cam.transform.position = newpos; in Update().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63359032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: PhoneGap/Cordova blank screen on pause/resume I have a simple html/javascript app that starts and works up fine on an Android device. However, when the app is put in background by using the 'home button' and then brought back to the foreground by clicking on the app again - it starts with a blank screen (white blank screen on android ) and stays that way until the 'back button' is pressed.
Once the 'back button' is pressed the screen refreshes to the last page displayed by the app.
I am new to PhoneGap and I am sure there is something simple/fundamental that I am missing - in terms of how to handle the 'resume' event/etc.. I have followed the instructions provided on this link by Phil Mitchell http://wiki.phonegap.com/w/page/35501397/Tutorials (which is a great resource btw..)
Thanks.
Update :
After looking at the DroidGap code, I have tried to add the following line :-
super.setBooleanProperty("keepRunning", false);
But this does not seem to help. I am happy for the app to exit every time the home button is entered and then do a full restart when the app is clicked on the mobile.
Any help is much appreciated..
A: I was having the same problem and I want to share a hack that worked for me.
My app is based on ionic/angular/cordova and the android version was giving me a white screen around 50% the times on pause/resume.
When it happened, tapping anywhere on the screen or hitting the back button would make the screen to render again just fine.
I added a div tied to a scope variable named random, like this:
<body ng-app="starter" id="body">
<div>{{ random }}</div>
<ion-nav-view>
</ion-nav-view>
</body>
Then I added a listener inside my app.js to capture the resume event fired by cordova, to then change the random variable and call $apply(), like this:
document.addEventListener("resume", function() {
angular.element(document.querySelector('#body')).scope().random = Math.random();
angular.element(document.querySelector('#body')).scope().$apply();
})
Since the ion-nav-view takes over the whole screen that div never shows up, but angular doesn't know that and refreshes the page, causing the whole thing to work.
(I tried to tie the variable to an invisible element but then angular doesn't refresh the page)
I hope this helps someone!
A: There seem to be issues around rendering the pages thru PhoneGap and 'Dialog'ing thru Client side FB authentication flow using the JS SDK. If I disable the client side authentication, then the rendering and display of the page works very well, when the app is brought to foreground from background (pause/resume/etc).
I am assuming that the page will need to sense that it is being displayed over a mobile device and use the IOS or Androi SDK for client side authentication.. (if/when I get around to testing that, I update the answer - if there is anybody who has any more light to shed, please feel free to embellish).
A: If you still say "I am happy for the app to exit every time the home button is entered and then do a full restart when the app is clicked on the mobile." then go for it.
@Override
protected void onStop(){
super.onStop();
}
Try this from where you create activity or from the class which "extends DroidGap".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11170592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript check to see if an event has already been fired or clicked I have a function that needs to fire when I click on a chevron tab. However I only need that function to fire that first time we load the page. How can I prevent it form firing every time the tab is clicked?
$('#navi a').bind('click',function(e){
var $this = $(this);
var prevButton = current;
$this.closest('ul').find('li').removeClass('selected');
if ( $(this).attr('id') == 'tab2')
{
//fire function only once
}
});
A: Use the .one binding instead. This will attach it to fire on the first click and remove itself.
A: In case you need only part of your event handler to run once :
$("div").on("click",function(){
if (!$(this).data("fired")) {
console.log("Running once");
$(this).data("fired",true);
}
console.log("Things as usual");
});
Demo
A: Use:
var isalreadyclicked=false;
$('#navi a').bind('click',function(e){
var $this = $(this);
var prevButton = current;
$this.closest('ul').find('li').removeClass('selected');
if ( $(this).attr('id') == 'tab2')
{
if(!isalreadyclicked){
//fire function only once
isalreadyclicked=true;
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21164008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: addClass function working properly but removeClass function not working on input text field for form? Creating an Online form and I'd like only the field that the user is focused on to be notfaded so i decided to add some jQuery to my form but the remove class function is not working. addClass works when I click into a field it shows brightly and not faded as it adds the Focused class but as soon as I click away or am no longer focused on that field the Focused class remains.
I've seen some similar posts but the solutions on the other posts don't seem to pertain to my issue.
Below is my form
<form name="contactform" method="post">
<div class="row">
<div class="col-md-12 inputFaded">
<span class="larger"><strong>Name</strong> <span class="textGreen">*</span></span><br><br>
<span>Please provide your full name</span>
<input type="text" maxlength="100" class="form-control discuss" name="projectname">
<br>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">
</div>
</div>
</form>
Below is my jQuery
$(document).ready(function(){
$('input[type="text"]').on('focus', function() {
$('.inputFaded').addClass('Focused');
});
$('input[type="text"]').off('focus', function() {
$('.inputFaded').removeClass('Focused');
});
});
Any help greatly appreciated!
Thanks,
A: You are misunderstanding .off()
Description: Remove an event handler.
So it seems that you need to listen focusin and focusout event.
$(document).ready(function(){
$('input[type="text"]').focusin(function() {
$('.inputFaded').addClass('Focused');
});
$('input[type="text"]').focusout(function() {
$('.inputFaded').removeClass('Focused');
});
});
.Focused{
background-color: #FFFFCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="contactform" method="post">
<div class="row">
<div class="col-md-12 inputFaded">
<span class="larger"><strong>Name</strong> <span class="textGreen">*</span></span><br><br>
<span>Please provide your full name</span>
<input type="text" maxlength="100" class="form-control discuss" name="projectname">
<br>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">
</div>
</div>
</form>
Updated
$(document).ready(function(){
$('input[type="text"]').focusin(function() {
$(this).addClass('Focused');
});
$('input[type="text"]').focusout(function() {
$(this).removeClass('Focused');
});
});
.Focused{
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="contactform" method="post">
<div class="row">
<div class="col-md-12 inputFaded">
<span class="larger"><strong>Name</strong> <span class="textGreen">*</span></span><br><br>
<span>Please provide your full name</span>
<input type="text" maxlength="100" class="form-control discuss" name="projectname">
<br>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">
</div>
</div>
</form>
A: The .off function is not used for running a function but for removing a function from an Event tied to an element, as already pointed out by @Phong. Instead use the .focusout() function or .on("focusout", ..)
Please note that if this is also quite simple in Vanilla JS:
// Vanilla JS solution
(function(){
let input = document.querySelector("input[type='text']"),
inputFaded = document.querySelector(".inputFaded");
input.addEventListener('focus', function() {
console.log("focused now!");
inputFaded.classList.add('Focused');
});
input.addEventListener('focusout', function(){
console.log("I will also be run! :)");
inputFaded.classList.remove('Focused');
})
})()
$(document).ready(function(){
$('input[type="text"]').on('focus', function() {
console.log("focused now!");
$('.inputFaded').addClass('Focused');
});
// Removing function from focus event that does not exist as a function to an eventlistener
$('input[type="text"]').off('focus', function() {
console.log("I will never be run? :(");
$('.inputFaded').removeClass('Focused');
});
// adding focusout eventlistener
$('input[type="text"]').on('focusout', function() {
console.log("I will be run! :)");
$('.inputFaded').removeClass('Focused');
});
// alternative way of adding focusout eventlistener
$('input[type="text"]').focusout( function() {
console.log("I will also be run! :)");
$('.inputFaded').removeClass('Focused');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form name="contactform" method="post">
<div class="row">
<div class="col-md-12 inputFaded">
<span class="larger"><strong>Name</strong> <span class="textGreen">*</span></span><br><br>
<span>Please provide your full name</span>
<input type="text" maxlength="100" class="form-control discuss" name="projectname">
<br>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">
</div>
</div>
</form>
A: You can also try like this :
$(document).ready(function(){
$("input").focus(function(){
$('.inputFaded').addClass('Focused');
});
$("input").on('blur', function() {
$('div').removeClass('Focused');
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59923836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trying to get Azimuth difference in a loop I have a micropython program on a ESP32 connected to a stepper motor via a driver board.
The software runs in a while true loop. I'm trying to get the azimuth difference between 30 second previous azimuth reading and the post 30 second azimuth reading, then send the difference to the stepper motor. Unfortunately they will not let me post all my code, so here is a small example.....
import math
import time
import Stepper
from machine import Pin
s1 = Stepper.create(Pin(26,Pin.OUT),Pin(25,Pin.OUT),Pin(33,Pin.OUT),Pin(32,Pin.OUT),
delay=2)
while True:
xxxxx loop in here I have working code that updates the Azimuth of the sun in
realtime every 30 seconds XXXXXXX
s1.angle(azimuth, -1)
time.sleep(30)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73215409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple slopes test for merMod object with R package interactions (jtools) I'm trying to conduct a simple slopes analysis for a mixed effects model obtained with lmer.
The model is similar to the following:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
When trying to conduct a simple slopes analysis with the function sim_slopes in the package interactions, I obtain the following error message.
interactions::sim_slopes(model=mod, pred=age, modx=Sex)
Error: One of the requested columns does not exist.
Backtrace:
1. interactions::sim_slopes(model = mod, pred = age, modx = Sex)
5. jtools:::summ.merMod(...)
6. jtools:::create_table(...)
In addition: Warning message:
Johnson-Neyman intervals are not available for factor moderators.
Would any one have any thoughts on what the problem might be?
Note that it works well with the package reghelper, but I need p values for these tests, which reghelper does not provide.
reghelper::simple_slopes(mod)
The output of sessionInfo() is:
R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.2
LTS
Matrix products: default BLAS:
/usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK:
/usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
locale: [1] LC_CTYPE=en_CA.UTF-8 LC_NUMERIC=C
LC_TIME=en_CA.UTF-8 [4] LC_COLLATE=en_CA.UTF-8
LC_MONETARY=en_CA.UTF-8 LC_MESSAGES=en_CA.UTF-8 [7]
LC_PAPER=en_CA.UTF-8 LC_NAME=C LC_ADDRESS=C
[10] LC_TELEPHONE=C LC_MEASUREMENT=en_CA.UTF-8
LC_IDENTIFICATION=C
attached base packages: [1] stats graphics grDevices utils
datasets methods base
loaded via a namespace (and not attached):
[1] Rcpp_1.0.1 magrittr_1.5 splines_3.6.0 MASS_7.3-51.1
[5] munsell_0.5.0 colorspace_1.4-1 lattice_0.20-38 rlang_0.3.4
[9] minqa_1.2.4 plyr_1.8.4 tools_3.6.0 grid_3.6.0
[13] gtable_0.3.0 nlme_3.1-140 cli_1.1.0 assertthat_0.2.1
[17] digest_0.6.19 lme4_1.1-21 lazyeval_0.2.2 tibble_2.1.2
[21] crayon_1.3.4 Matrix_1.2-17 reghelper_0.3.4 nloptr_1.2.1
[25] ggplot2_3.1.1 interactions_1.1.0 jtools_2.0.1 pander_0.6.3
[29] compiler_3.6.0 pillar_1.4.1 scales_1.0.0 boot_1.3-20
[33] pkgconfig_2.0.2
A: (Not an answer but way too long for a comment. Will delete later if appropriate.)
In a clean R session, this works for me:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
interactions::sim_slopes(model=mod, pred=age, modx=Sex)
sessionInfo()
SIMPLE SLOPES ANALYSIS
Slope of age when Sex = Female:
Est. S.E. t val. p
------ ------ -------- ------
0.48 0.09 5.13 0.00
Slope of age when Sex = Male:
Est. S.E. t val. p
------ ------ -------- ------
0.78 0.08 10.12 0.00
Warning message:
Johnson-Neyman intervals are not available for factor moderators.
Here is my sessionInfo(): the important stuff looks the same as yours (lme4 1.1-21, interactions 1.1.0, jtools 2.0.1), but it's certainly not identical ... ??
R Under development (unstable) (2019-05-21 r76566)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS
[matrix product and locale info deleted]
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] Rcpp_1.0.1 magrittr_1.5 splines_3.7.0 MASS_7.3-51.4
[5] tidyselect_0.2.5 munsell_0.5.0 colorspace_1.4-1 lattice_0.20-38
[9] R6_2.4.0 rlang_0.3.4 minqa_1.2.4 plyr_1.8.4
[13] dplyr_0.8.1 tools_3.7.0 grid_3.7.0 gtable_0.3.0
[17] nlme_3.1-140 cli_1.1.0 digest_0.6.19 assertthat_0.2.1
[21] lme4_1.1-21 lazyeval_0.2.2 tibble_2.1.2 numDeriv_2016.8-1
[25] crayon_1.3.4 Matrix_1.2-17 purrr_0.3.2 nloptr_1.2.1
[29] ggplot2_3.1.1 jtools_2.0.1 interactions_1.1.0 glue_1.3.1
[33] pander_0.6.3 compiler_3.7.0 pillar_1.4.1 scales_1.0.0
[37] lmerTest_3.1-0 boot_1.3-22 pkgconfig_2.0.2
A: I solved the problem by detaching lmerTest.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56401996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Next Js - Providers/getProviders() - FetchError - next build I am trying to build my application next js.
I use providers with next-auth.
It works fine when I use npm run dev.
But when I use npm run build I get this:
However, I use the variable NEXTAUTH_URL = localhost: 3000 in a .env.local
The error appears when I have "getProviders ()" in a file like this:
import {getProviders, useSession} from 'next-auth/client'
import Layout from "../components/layout";
export default function Page({providers}) {
const [session, loading] = useSession()
return (
<Layout providers={providers}>Page index</Layout>
)
}
export async function getStaticProps() {
const providers = await getProviders()
return {
props: {providers}
}
}
A: I think same probrem this.
ECONNREFUSED during 'next build'. Works fine with 'next dev'
It is working.
import {getProviders, useSession} from 'next-auth/client'
import Layout from "../components/layout";
export default function Page() {
const [session, loading] = useSession()
const [providers, setProviders] = useState({});
useEffect(() => {
(async () => {
const res = await getProviders();
setProviders(res);
})();
}, []);
return (
<Layout providers={providers}>Page index</Layout>
)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67689306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to set radio button selected value using jquery How to set radio button selected value in javascript:
HTML Code :
<input type="radio" name="RBLExperienceApplicable" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >
ASPX Code
<asp:RadioButtonList ID="RBLExperienceApplicable" runat="server" class="radio" RepeatDirection="Horizontal" EnableViewState="false">
<asp:ListItem Value="1" Text="Yes "></asp:ListItem>
<asp:ListItem Value="0" Text="No"></asp:ListItem>
</asp:RadioButtonList>
<asp:RadioButtonList ID="RBLExperienceApplicable2" runat="server" class="radio" RepeatDirection="Horizontal" EnableViewState="false">
<asp:ListItem Value="1" Text="Yes "></asp:ListItem>
<asp:ListItem Value="0" Text="No"></asp:ListItem>
</asp:RadioButtonList>
// Some Code Fetch from db
// Based on db value script block will execute
<script type="text/javascript">
RadionButtonSelectedValueSet('1');
</script>
Script Block :
function RadionButtonSelectedValueSet(SelectdValue) {
$('#RBLExperienceApplicable').val(SelectdValue);
//$("input[name='RBLExperienceApplicable']:checked").val(SelectdValue);
}
A: Try
function RadionButtonSelectedValueSet(name, SelectdValue) {
$('input[name="' + name+ '"][value="' + SelectdValue + '"]').prop('checked', true);
}
also call the method on dom ready
<script type="text/javascript">
jQuery(function(){
RadionButtonSelectedValueSet('RBLExperienceApplicable', '1');
})
</script>
A: You can try this also
function SetRadiobuttonValue(selectedValue)
{
$(':radio[value="' + selectedValue + '"]').attr('checked', 'checked');
}
A: You can do more elegantly.
function RadionButtonSelectedValueSet(name, SelectedValue) {
$('input[name="' + name+ '"]').val([SelectedValue]);
}
A: Below script works fine in all browser:
function RadionButtonSelectedValueSet(name, SelectdValue) {
$('input[name="' + name + '"][value="' + SelectdValue + '"]').attr('checked',true);
}
A: $('input[name="RBLExperienceApplicable"]').prop('checked',true);
Thanks dude...
A: If the selection changes, make sure to clear the other checks first. al la...
$('input[name="' + value.id + '"]').attr('checked', false);
$('input[name="' + value.id + '"][value="' + thing[value.prop] + '"]').attr('checked', true);
A: for multiple dropdowns
$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");
here RBLExperienceApplicable is the matching part of the radio button groups input tag ids.
and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable
A: <input type="radio" name="RBLExperienceApplicable" class="radio" value="1" checked >
// For Example it is checked
<input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >
$( "input[type='radio']" ).change(function() //on change radio buttons
{
alert('Test');
if($('input[name=RBLExperienceApplicable]:checked').val() != '') //Testing value
{
$('input[name=RBLExperienceApplicable]:checked').val('Your value Without Quotes');
}
});
http://jsfiddle.net/6d6FJ/1/
Demo
A: <asp:RadioButtonList ID="rblRequestType">
<asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
<asp:ListItem Value="Value2">Value2</asp:ListItem>
</asp:RadioButtonList>
You can set checked like this.
var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");
radio0.checked = true;
radio1.checked = true;
A: A clean approach I find is by giving an ID for each radio button and then setting it by using the following statement:
document.getElementById('publicedit').checked = true;
A: Can be done using the id of the element
example
<label><input type="radio" name="travel_mode" value="Flight" id="Flight"> Flight </label>
<label><input type="radio" name="travel_mode" value="Train" id="Train"> Train </label>
<label><input type="radio" name="travel_mode" value="Bus" id="Bus"> Bus </label>
<label><input type="radio" name="travel_mode" value="Road" id="Road"> Other </label>
js:
$('#' + selected).prop('checked',true);
A: This is the only syntax that worked for me
$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');
A: document.getElementById("TestToggleRadioButtonList").rows[0].cells[0].childNodes[0].checked = true;
where TestToggleRadioButtonList is the id of the RadioButtonList.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19294001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
}
|
Q: Spring service periodic task Lets suppose there is spring boot web app with 2 classes mapped as @Controller and @Service. Service is injected into controller's field. I need my service to run task once a second to update some external data. Is there something wrong with this code?
@Component
public class MyService implements Runnable{
public MyService() {
new Thread(this).start();
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
// operations here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
A: Though there are a lot of ways of creating a task, using job or spring task scheduler, below is one straightforward way.
Below task will run every second.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("hello");
}
}, 0, 1000); // o is delay time after which it starts, 1000 is time interval
Or you may want to refer here to implement spring task scheduler .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46749221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use a variable to pass a crop string argument to cpdf in bash This question is about how, in bash, one can (and cannot) pass a string—which is contained in a bash variable—as an argument to a binary executable. I am using a particular binary executable, but the question is broader, because we may want to pass string arguments to all kinds of binary executables.
I understand that the behavior described below may turn out to be very special to the binary executable I am calling. But I suspect that what I am describing is a reflection of something basic in how bash works, in which case it could be of interest to a border range of people.
Background
This question arose in the course of me writing a bash script that uses cpdf (link), which is a binary executable. The program cpdf is open source; the source code (in OCaml) is available here.
Basic usage of the binary executable in question
Suppose, in a bash terminal, the working directory contains a one-page pdf file called in.pdf.
Then the following command produces a pdf file called out.pdf containing a cropped window from in.pdf:
cpdf -crop "10pt 10pt 200pt 500pt" in.pdf -o out.pdf
The size of the crop is specified by the string "10pt 10pt 200pt 500pt" (For completeness: if the crop window has its lower-left corner at (x1,y1) and upper-right corner ar (x2,y2), then the string format is x1 y1 x2 y2—plus the units, all enclosed in quote marks.)
Using a variable to pass the crop string
The following will work:
cropstring="10pt 10pt 200pt 500pt"
cpdf -crop "$cropstring" $filein -o out1.pdf
But the following will not:
cropstring="\"10pt 10pt 200pt 500pt\""
cpdf -crop $cropstring $filein -o out2.pdf
If you execute the latter, it returns the error message
Bad rectangle specification "10pt
The difference is that in the first case, the enclosing quote marks are not part of the string which is contained in the variable cropstring, while in the second case, they are part of it.
Questions
Is this behavior likely to be very specific to cpdf, or is it reflective of some general properties of bash? If the latter, then two more questions: why doesn't the second way work? Is there a way to define the variable cropstring so that the second way (meaning, all required quote marks are somehow included in the content of the variable) does work?
A: The problem you have here is that cpdf is not a string interpreter like echo or printf and so on. In your case cpdf doesn't know how to interpret your escaped string and when you pass this "so called" variable (cropstring) to cpdf binary you actually tell to bash like this: pass to cpdf script this argument in which you close double-quote and after \"10pt you have a space which means cpdf jump to next argument (input file) and leave away this part of string 10pt 200pt 500pt\" (that means that your script will take 10pt as a single argument and that is unfortunate because your binary script expect other 3 arguments). This is why your binary raise an error because it cannot crop a window having just one argument 10pt. It expects yet 3 arguments in a string.
This is how your binary script will exit (with an error) and tell you that there is a Bad rectangle specification "10pt.
The arguments that you pass to cpdf are good in first example but in the second example are wrong. I described earlier how bash interpret parameters. In the first example your binary script treat cropstring as a string variable and in the second example it will pass only the first argument which is 10pt.
To respond to your answer, it is the way bash interpret strings and your script and not a problem of cpdf binary.
The line in which you write:
cropstring="\"10pt 10pt 200pt 500pt\""
can be interpreted well only by a text interpreter (you can play writing echo -e $cropstring) but NEVER in bash command line. When you pass your variable as an argument to some bash script, bash see your variable like cpdf -crop ""10pt. That's all because the rest of the string will be seen as file.in argument. The error occurs because your string parameter asked by crop argument is just 10pt and thus, the binary doesn't know how to crop that window.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66093989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to split one string in a column into two string pandas I have 2 STRING dataframe, each data is given name as dataset and colloquial.
dataframe colloquial:
|**wrong** | **correct** |
|sheis | she is |
|taht | that |
|diedwhen | died when |
The second dataframe is dataset with specific column that I use that look like this:
dataframe dataset['review'] :
review
[shewas, wrong, but, her, intentions, are, good]
[is, taht, you]
[he, diedwhen, he, was, young]
I want to change the wrong word in the dataset['review'] into the correct word according to dataframe colloquial. I use this:
normalizad_word = pd.read_excel("colloquial.xlsx")
normalizad_word_dict = {}
for index, row in normalizad_word.iterrows():
if row[0] not in normalizad_word_dict:
normalizad_word_dict[row[0]] = row[1]
def normalized_term(document):
return [normalizad_word_dict[term] if term in normalizad_word_dict else term for term in document]
dataset['review_normalized'] = dataset['review'].apply(normalized_term)
dataset['review_normalized']
BUT the result is like this:
review_normalized
[she was, wrong, but, her, intentions, are, good]
[is, that, you]
[he, died when, he, was, young]
I want it to be like this:
review_normalized
[she, was, wrong, but, her, intentions, are, good]
[is, that, you]
[he, died, when, he, was, young]
A: Change normalized_term function:
def normalized_term(document):
result = []
for term in document:
if term in normalizad_word_dict:
for word in normalizad_word_dict[term].split(' '):
result.append(word)
else:
result.append(term)
return result
Or if you want to use inline loop:
import itertools
def normalized_term(document):
return list(itertools.chain(*[normalizad_word_dict[term].split() if term in normalizad_word_dict else term.split() for term in document]))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74250905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: resigning the keyboard swift 1.2 So I just updated to swift 1.2 and now my code to resign the keyboard wont work?
the code is:
override func touchesBegan(touches:NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
the error says Overriding method with selector "touchesBegan:withEvent:" has incompatible type
A: Try replacing NSSet with Set<NSObject>
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
The syntax has been edited in swift 1.2. The NSSet was replaced by Set<NSObject>
See the Blog Post and the Xcode 6.3 release notes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29733938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP separate acces to some links I have a table in DB where I put all the admins and their rights. I am setting theri rights with letters A-Z and each letter has access to something else. The thing is I want to check where they have access and show links only to those areas. For now I got an idea to put all those letters in some aray with for loop and then when rendering the menu output only those items where they have access with if (in_array(letter, rights)) I think this would work but I would like to know whether there is another way
A: I wrote a PHP class that I use in all my projects that require different access for different roles. I put a copy of the class out on paste bin: class_role_restrictions.php.
This class also requires another class I wrote, which can be obtained here: better_mysqli.php
The initial setup involves the creation of some database tables (The SQL create statements are found in comments at end of the class_role_restrictions.php file) and adding roles / user memberships via it's admin interface.
Detailed setup/usage can be obtained here: role_restrictions_detailed_example.php
Once it is setup you can use it like this:
<?php
include_once('class_role_restrictions.php');
include_once('better_mysqli.php');
$mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
if (mysqli_connect_errno()) {
error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
exit;
}
$role = new role_restrictions($mysqli, 'http://your_server.com/path/to/this/page/example.php');
// == Restrict an entire page to authorized users only ==
$role->restrict_to('role_name, to_restrict user_to', 'username_currently_logged_in');
// .. now do stuff that only users in any of the roles listed are allowed to do
// -- OR --
// == Only do certain things if the username given is a member of any of the roles given ==
if( $role->has_role('a_list, of_roles, allowed', 'username_currently_logged_in') ){
// .. do stuff that only users in the given role(s) are allowed to do ..
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17813395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Duplicates removal from different excel files at a time I have 5 folders and each folder consists of around 20 excel sheets.
And these excel sheets contain duplicates within it. It is becoming very hectic to open every file and remove duplicates.
Is there anyother way to remove duplicates from all these files at once ?
All the files contain different set of duplicates and no common columns will be present.
A: XD I'm really understanding your situation but I think that the solution will be one of two :) :
1-make a program with any programming language you can use and try to load the files one by one to do what you want
2-(the easiest one)Try to find a good converter to convert all your files to SQL tables then come here to this site and ask how to delete duplicated rows from different SQL tables after doing that reconvert the SQL tables to EXCEL files again and it will be done (y) ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35675357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bash: using parameter expansion to add variables at front and end simultaneously How can i use parameter expansion to add strings at front and end at the same time.
Currently i'm doing this in two steps:
base_test_path=something
folder=anotherthing
test=(abc cde)
halfPaths=("${test[@]/#/$base_test_path}")
fullPath=("${halfPaths[@]/%//$folder/}")
can i eliminate one step here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53311243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is JQuery namespace a good practice? Can anyone explain to me please that if using a namespace is a good coding practice. And why is it needed? If it was a good approach why JQuery didn't include it by default. There is a separate plugin to allow this functionality.
I saw this post that mentions few ways to do it. Someone mentioned about memory leak in the post that is worrisome.
Lastly, what is the best way to organize JQuery libraries?
thanks,
A: Re: best ways to organize jQuery libraries, you should start by reading the Plugins Authoring article on jquery.com:
http://docs.jquery.com/Plugins/Authoring
A: Notes:
*
*Namespacing is a good practice because you have less chance of having conflicting names with other scripts. This way, only your name-space has to be unique, but multiple name-spaces can have the same functions in them.
*jQuery DOES use namespacing, and you do not need the plug-in. The jQuery object itself is a name-space. . . Any function inside jQuery is 'name-spaced' in the jQuery object. This is true for any JavaScript object.
In response to Amir's comment:
YUI achieves namespacing by adding a variable to the YUI object where the added variable is also an object. Their namespace function just builds it for you.
var lib = {
util:{},
widget:{},
tool:{}
};
//creates a function named reset in the lib.util namespace
lib.util.reset = function() {};
//creates a function named reset in the lib.widget namespace
lib.widget.reset = function() {};
In jQuery, you add it to the jQuery.fn (or $.fn if you use $ for jQuery() namespace.
A: require.js is a better practice because it doesn't require you to add objects onto the window object unnecessarily. It also doesn't mean you have to worry about the loading order of previous javascript files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6537655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Any ccTalk libraries available? I want to integrate a coin acceptor into one of our applications. This specific coin acceptor uses the ccTalk protocol (specs here).
I've been looking for a ccTalk library which I can use from C#, but until this point I've only found this open source project which seems not quite ready, and abandoned.
Any of you guys know of any ccTalk libraries out there? I can't believe this hasn't been done before. It doesn't necessarily has to be free.
A: Have you looked at cctalk-net? It's a rewrite of libcctalk and has been worked on up to August 2011 this year. It does not support everything in ccTalk but might just support enough for your needs.
A: I managed to come up with a solution based on the aforementioned cctalk-net project.
I hosted my project on github: https://github.com/Hitman666/nbCcTalkCoinAcceptor so I hope it will help someone. I made a full fledged documentation for an easy start (which can't be said for cctalk-net project).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2721885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: filter2D OpenCV function c++ I have noticed differences between the OpenCV implementation of filter2D in C++ and a direct implementation of the corresponding kernel. I have read the following question:
Opencv - how does the filter2D() method actually work?
The author of that question had tried to get a working implementation of the filter2D function. He claims that using a normalized version of filters yields correct results. I have tested his hypothesis and found that normalization gives the correct answer only when all the coefficients are positive. Thus an averaging filter can be successfully implemented using the filter2D function.[We must still normalize the kernel].
However this is not the case for filters with negative coefficients such as the Sobel,Laplacian and any edge detection filter. The author of that question has encountered the same problems as me.
https://stackoverflow.com/users/2669614/bovaz
The user mentioned above replied to the linked question. He claimed that filter2D might modify its implementation if the sum of the coefficients of the kernel equals zero. Is that the case? Why does the implementation of filter2D in C+ give different results from a direct implementation? I have checked that filter2D in Python and a direct implementation of the corresponding kernel in C++ yield the same results.
A: It is mainly because of scaling and overflow issues.
The documentation for filter2D does not mention(atleast i did not find) whether the overflowed values are clipped or scaled appropriately to the min-max range.
This is more important in the case of directional filters, where the co-efficients are positive and negative and after the algebraic
The function 'myfilter2D' presented on the link above does not scale to the min-max range which should be the case.
If you could post the sample code then it would be easier to help.
My suggestion would be to convert the matrices to float(with scaling) and perform algebraic operations because this tends to preserve the resulting values and values are not lost due to overflow or saturation.
im2double()->"perform algebraic operations"->im2uchar() for displaying
void im2uchar( Mat & src, Mat & dest){
double minVal, maxVal;
minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities
src.convertTo(dest, CV_8U, 255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal));
}
void im2float( Mat & src, Mat & dest){
double minVal, maxVal;
minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities
src.convertTo(dest, CV_32F, 1.0/(maxVal - minVal), -minVal * 1.0/(maxVal - minVal));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41934093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: API $http delete returns 405 when calling from factory in angular This is what I have in my factory. This was working fine when I was running it in regular ajax syntax from the controller.
function endAgentSession(sessionData, tokenData) {
var sessionId = sessionData.data.sessionId,
access_token = tokenData.access_token,
baseURI = tokenData.resource_server_base_uri,
endAgentSessionPayload = {
'sessionId': sessionId,
'forceLogOff': true,
'endContacts': true,
'ignorePersonalQueue': false
};
console.log(sessionId, "sessID");
return $http({
'url': baseURI + 'services/v6.0/agent-sessions/' + sessionId,
'type': 'DELETE',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + access_token,
'content-Type': 'application/json'
},
'data': endAgentSessionPayload
}).then(function(res){
return res })};
}
This is my controller. When I call the endAgentSession function from the controller with an ng-click, it errors out to a 405..
$scope.endAgentSession = function(){
agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};
What am I doing wrong? It was working w/ ajax in the controller, then seemed to break when I moved it to the factory and used a promise.
it's actually showing it' requesting a GET request in Network..
[![enter image description here][1]][1]
full controller:
csMgmtApp.controller('launchedController', ['$scope', '$http', '$document', '$resource', 'agentFactory', '$timeout', function ($scope, $http, $document, $resource, agentFactory, $timeout) {
$scope.agentStatePayload = {};
$scope.sessionData = {};
$scope.tokenData = {};
$scope.startSessionPayload = {
'stationPhoneNumber': '2223222222',
'inactivityTimeout': 0,
'inactivityForceLogout': 'false'
};
$document.ready(function () {
$scope.tokenData = agentFactory.getToken();
console.log($scope.tokenData);
});
agentFactory.startSession($scope.startSessionPayload, $scope.tokenData).then(function(res){
console.log("sessionId", res);
$scope.sessionData = res;
});
$scope.endAgentSession = function(){
agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};
}]);
It all seems to be working, except for the endSession, now..
A: I should have guessed that every time you said
regular ajax syntax from the controller
you meant you were using jQuery $.ajax previously.
The difference is that the property that sets the request method in Angular's $http is method, not type.
You can simplify it further using
return $http.delete(baseURI + 'services/v6.0/agent-sessions/' + sessionId, {
headers: {
Authorization: 'Bearer ' + access_token,
},
data: endAgentSessionPayload
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33862515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Declare explicit types for a dynamically created class function Say I've got this class:
class Foo {
bar = this.createDynamicFunction((param: string) => {
return "string" + param;
});
baz = this.createDynamicFunction((param: number) => {
return 1 + param;
});
createDynamicFunction(fn: (param: any) => any) {
return (param) => fn(param);
}
}
const foo = new Foo()
foo.bar('baz') // => barbaz
foo.baz(2) // => 3
How do I declare types for the functions Foo.prototype.bar and Foo.prototype.baz? I want to explicitly say that bar and baz accept and return string and number respectively.
I realize that this is a contrived example. For some context, I'm in the final stages of rewriting one of my message queue client libraries and a lot of the class functions are dynamically created. These functions share a lot of functionality, but their inputs/outputs differ.
A: Generics are made for this:
class Foo {
bar = this.createDynamicFunction((param: string) => {
return "string" + param;
});
baz = this.createDynamicFunction((param: number) => {
return 1 + param;
});
createDynamicFunction<Type>(fn: (param: Type) => Type) {
return (param : Type) => fn(param);
}
}
const foo = new Foo()
//console.log(foo.baz(2)) // => 3
console.log(foo.bar('baz')) // => barbaz
console.log(foo.baz(2)) // => 3
You create a generic function, for which the type can be anything. And you can define your overall function type based on that type
Playground Link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70502989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ipa extraction after you download an app from iTunes We are currently providing ios app via Itunes. The main function of the app is to verify `app integrity' and it is done by checking hash value (sha256) of the execution file in .ipa once we download it.
With the 32bit app we downloaded from iTunes, we can extract .ipa file to get execution file without problems. However, it does not seem to be possible with 64bit ios apps. (maybe there is a way and we couldn't find it. if this is the case please enlighten us.) Since we are planning provide our service both with 32 and 64bit, we do need to extract execution file from 64bit app.
So there are two questions we would like to ask regarding on this ipa extraction.
1. The hash value(sha256) of the app before we upload to iTunes and the value after we download it from iTunes is different. Why is that?
2. Is there any way we can extract .ipa (32/64 bit both) after we download the app from iTunes?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32987803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: lock/prevent close of menu reactjs I have a side menu that opens when an icon is clicked and closes when the either the page is clicked or an item on the menu is clicked. I am trying to implement a lock so when the lock icon is clicked, the menu will not close even if you click on a menu item or on the page.
I was able to setup the icon changing from a locked one to an unlocked one but I am having trouble with the functionality of stopping the close. Any help/suggestions would be awesome. Below are the 2 components that (the parent and the menu with the lock button) here is the code sandbox for a full look: https://codesandbox.io/s/pw6q46jp20
class SideBar extends Component {
constructor(props) {
super(props);
this.state = {
category: props.category,
currentPage: {
backgroundColor: '#383838',
color: '#A9A9A9',
},
menuLocked: false,
menuOpen: false,
selectedIcon: null,
};
}
handleIconClick = (category) => {
this.setState({
category,
menuOpen: true,
selectedIcon: category,
});
};
handleMenuItemClick = (category) => {
this.setState({
menuOpen: false,
selectedIcon: '',
currentPage: category,
});
}
handlePageClick = () => {
this.setState({
menuOpen: false,
});
}
handleMenuLock = () => {
this.setState({ menuLocked: !this.state.menuLocked });
}
render() {
return (
<div>
<TopBar {...this.props} />
<Container>
<SideNav>
<ListWrapper>
<IconList
currentPage={this.state.currentPage}
openMenu={this.handleIconClick}
selectedIcon={this.state.selectedIcon}
visible={this.state.menuOpen}
/>
</ListWrapper>
</SideNav>
<PageContentWrapper>
<Sidebar.Pushable>
<PushMenu
category={this.state.category}
closeOnItemClick={this.handleMenuItemClick}
handleMenuLock={this.handleMenuLock}
menuLocked={this.state.menuLocked}
params={this.props.params}
visible={this.state.menuOpen}
/>
<Sidebar.Pusher
onClick={this.handlePageClick}>
<Segment basic>
{this.props.children || <Home />}
</Segment>
</Sidebar.Pusher>
</Sidebar.Pushable>
</PageContentWrapper>
</Container>
</div>
);
}
}
SideBar.propTypes = {
children: PropTypes.any,
params: PropTypes.any,
category: PropTypes.any,
};
export default SideBar;
class PushMenu extends React.Component {
render() {
const category = sideNavData.lookupCategory(this.props.category);
const menuLockButton = !this.props.menuLocked
? <Icon
link={true}
name='unlock'
size='big'
/>
: <Icon
link={true}
name='lock'
size='big'
/>;
return (
<Sidebar
className='Push-menu'
animation='push'
width='thin'
visible={this.props.visible}
>
<Header>{this.props.category}</Header>
<Linebreak />
{
Object.keys(category).map((subCategory, index) => {
return (
<div key={index}>
<SubcategoryHeader>{subCategory}</SubcategoryHeader>
<List>
{
Object.keys(category[subCategory]).map((item, index) => (
<li key={index}>
<ListLink>
<Link
to={`/${this.props.category}/${subCategory}/${category[subCategory][item].name}`}
activeStyle={{ color: '#FFFFFF' }}
onClick={() => {
this.props.closeOnItemClick(this.props.category);
}}
>
{category[subCategory][item].name}
</Link>
</ListLink>
</li>
))
}
</List>
<LockButtonWrapper onClick={this.props.handleMenuLock}>
{menuLockButton}
</LockButtonWrapper>
</div>
);
})
}
</Sidebar>
);
}
}
PushMenu.propTypes = {
category: PropTypes.any,
closeOnItemClick: PropTypes.func,
currentPage: PropTypes.func,
handleMenuLock: PropTypes.func,
menuLocked: PropTypes.bool,
visible: PropTypes.bool,
};
export default PushMenu;
A: You can change your handlePageClick method to setState only when this.state.menuLocked is false.
handlePageClick = () => {
if (!this.state.menuLocked) {
this.setState({
menuOpen: false,
});
}
}
A: Inside of handlePageClick() you should do a check to see if this.state.menuLocked is true. If so, don't change the value of menuOpen in state.
handlePageClick = () => {
if (!this.state.menuLocked) {
this.setState({
menuOpen: false,
});
}
}
As a side note, in handleMenuLock() you are using the previous value of menuLocked to set the new value. Since setState is asynchronous, it's entirely possible that the value of menuLocked has changed by the time it actually saves and so you may not get the desired result. As such, you should pass it a function like this:
handleMenuLock = () => {
this.setState((prevState) => ({ menuLocked: !prevState.menuLocked }))
}
This ensures that the value is actually toggled. Docs on using setState in this manner can be found here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47190934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.