text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
C don't get the right result
I need the result of this variable in a program, but I don't understand why I can't get the right result.
double r = pow((3/2), 2) * 0.0001;
printf("%f", r);
A:
The problem is integer division, where the fractional part (remainder) is discarded
Try:
double r = pow((3.0/2.0), 2) * 0.0001;
The first argument of the pow() expects a double. Because the ratio: 3/2 uses integer values, the result passed to the argument is 1. By changing to float values, the result of the division can retain the fractional part, and the result becomes 1.5, the form expected by the function.
A:
(3/2) involves two integers, so it's integer division, with the result 1. What you want is floating point (double) division, so coerce the division to use doubles by writing it as (3.0/2.0)
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Cómo crear un bean que cree una instancia de HelloServiceImpl?
Tengo que definir un bean que cree una instancia dentro de la clase HelloServiceImpl, así está estructurada la clase:
package me.jmll.utm.web;
import org.springframework.stereotype.Service;
/** 1(a) Define que Spring cree una instancia de HelloServiceImpl */
//Escribe tu código aquí {
//}
public class HelloServiceImpl implements HelloService {
@Override
public String getHello(String name) {
return String.format("Welcome %s!", name).toString();
}
}
En otro programa lo ingresé como:
public HelloService HelloServiceImpl;
Pero no sé si es correcta la declaración
Agrego luego de las respuestas recibidas:
Tengo muchos archivos, en realidad tengo que hacer muchas modificaciones a varios archivos.
En la implementación del servicio me.jmll.utm.HelloService, src/main/java/me/jmll/utm/HelloServiceImpl.java realiza lo siguiente:
Define que Spring cree una instancia de HelloServiceImpl con la anotación requerida.
La clase HomeController.java
package me.jmll.utm.web;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import javax.inject.Inject;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private HelloService helloService;
private static final Logger logger = LogManager.getLogger(HomeController.class);
/**
* Simplemente selecciona el template home.jsp para
* interpretarlo como respuesta
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
/**
* Crea un Response Body con un servicio en específico.
*/
@ResponseBody
@RequestMapping(value = "/", method = RequestMethod.GET, params = {"name"})
public String homeName(Locale locale, Model model, @RequestParam("name") String name) {
logger.info("Welcome home! {} The client locale is {}.", name, locale);
return helloService.getHello(name);
}
/** 2(a) Inyectar HelloService en HomeController */
// Escribe tu código aquí {
// }
public void setHelloService(HelloService helloService)
{
this.helloService = helloService;
}
}
La clase HelloService.java
package me.jmll.utm.web;
public interface HelloService {
public String getHello(String name);
}
Y si me dan un beans en el archivo rootContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="me.jmll.utm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
A:
Para que Spring pueda reconocer el bean, debes configurarlo como un bean reconocible por el framework. Puesto que solo te dicen que uses código, es muy probable que tu proyecto esté basado en configuración por anotaciones. Lo que necesitas es anotar tu clase como @Service:
import org.springframework.stereotype.Service;
@Service
public class HelloServiceImpl implements HelloService {
}
Luego, en la clase donde necesitas que Spring inyecte una instancia de este bean, declaras el campo como la interfaz y además debes marcarlo como @Autowired:
import org.springframework.beans.factory.annotation.Autowired;
//definición de otro bean de Spring
//con su anotación particular
public class AlgunBeanManejadoPorSpring {
@Autowired
private HelloService helloService;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Xamarin ListView is empty or doesn't get filled
I have a problem. I created a ContentPage with a ListView like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="MyApp.HomePage">
<ContentPage.Content>
<StackLayout>
<ListView x:Name="ListViewMain">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Text="Employee Name" Grid.Column="1" Grid.Row="0" HorizontalOptions="Start"/>
<Image Source="VoteUp.png" VerticalOptions="End" Grid.Row="1" Grid.Column="0"/>
<Image Source="VoteDown.png" VerticalOptions="Start" Grid.Row="2" Grid.Column="0"/>
<Image Source="{Binding image}" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="1" Grid.RowSpan="2" BackgroundColor="AliceBlue" VerticalOptions="Fill" HorizontalOptions="Fill"/>
<Image Source="Favorite.png" Grid.Row="3" Grid.Column="1" HorizontalOptions="Start"/>
<Image Source="Send.png" Grid.Row="3" Grid.Column="1" HorizontalOptions="End"/>
<Image Source="Save.png" Grid.Row="3" Grid.Column="2" HorizontalOptions="End"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Here is the page constructor:
public HomePage()
{
InitializeComponent();
ListViewMain.ItemTemplate = new DataTemplate(typeof(CustomViewCell));
}
And here is the CustomViewCell:
public class CustomViewCell: ViewCell
{
public CustomViewCell()
{
//instantiate each of our views
var image = new Image();
image.SetBinding(Image.SourceProperty, "Example_Image.jpg");
}
}
I added all the icon images to the drawable folder in the android path, but when I launch the app, the whole page is blank and there is no picture at all. What am I doing wrong?
EDIT
Now I have added a ListSource to the ListView, but my result is very small:
How can I make the row WAY bigger?
A:
in CustomViewCell you create image but never assign it to the view hierarchy. You are also not setting the binding path correctly - you need to specify the name of a public property on your model
public CustomViewCell()
{
//instantiate each of our views
var image = new Image();
image.SetBinding(Image.SourceProperty, "name_of_some_property");
this.View = image;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get visual studio C++ toolset tag
Boost uses visual studio tool-set tag in its naming convention of its libraries as mentioned here. In visual studio, is there a variable that gives its tool-set tag? It will be helpful to construct library name independent of the tool-set.
libboost_regex-vc71-mt-d-1_34.lib
Above is the tool-set highlighted in the example library name.
A:
You can use $(PlatformToolsetVersion) which gives a version number
$(ProjectName)-vc$(PlatformToolsetVersion)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make pages to not get cached when logged in
Im using wamp server for my php scripts. And Im having difficulties on the logout code.
Every time I click on the logout link and then click on the back button on web browser it still shows the page which can only be access by the user who is logged in.
I have this code at the beginning of the index.php which is called by the log out link to destroy the session:
<?php
session_start();
session_destroy();
?>
And I have this at the beginning of the user page:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:login.php");
}
?>
I don't know why the userpage can still be access after the user has logged out.
As an another note will disabling the back-button for this can solve the problem
Please help.
A:
You should instead set the page to not be cacheable, like this:
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Thu, 15 Apr 2010 20:00:00 GMT");
This way the client should re-request the page when hitting back, getting the a fresh "logged out" version from the server.
On another note, don't ever mess with the client's buttons, they expect them to work a certain way, best for your site to behave like 99.999% of the internet and not break their experience.
A:
To stop your browser from caching the pages add these two lines of codes in your head tag of html or php file(if using with html)
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="expires" CONTENT="0">
| {
"pile_set_name": "StackExchange"
} |
Q:
Fill 2 different PickerView
I have 2 data pickers and I need to fill them with different data.
These data pickers are instances of class AKPickerView.
I have functions to fill them, but how I can do that with different information for every data picker view?
func numberOfItemsInPickerView(_ pickerView: AKPickerView) -> Int {
return self.titles.count
}
func pickerView(_ pickerView: AKPickerView, titleForItem item: Int) -> String {
return self.titles[item]
}
func pickerView(_ pickerView: AKPickerView, didSelectItem item: Int) {
print("Your favorite city is \(self.titles[item])")
}
A:
I assume that you have 2 instance properties that are of type AKPickerView.
In each method, you can check if the given pickerView is equals to one of them and do things according to the result.
func numberOfItemsInPickerView(_ pickerView: AKPickerView) -> Int {
if pickerView == self.myPicker1 {
return data.count
}
return data2.count
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I display all power plans in Windows 7 notification area?
By default, only the most recently used plan as well as "balanced" are available. How do I display all 3 default power plans? I'd like to avoid third party programs if possible.
A:
Shameless plug:
Power Buddy
Power Buddy is a very lightweight system tray application that allows you to switch between all the defined power plans.
No malware. No junk.
Full Disclosure: I am the author of this project.
A:
Windows 7 has no natural settings to show more than 2 power plans in the system tray. However, you can create shortcuts or hotkeys to switch between your power plans. How-to Geek has a nice article about how to do that: Create a Shortcut or Hotkey to Switch Power Plans.
One of the users in a forum having the same question as you says that this solution is perfect; but each time he ran the shortcut, the command prompt popped up for a second. To prevent this he created a small script. You can see the related post here.
There is also a Windows sidebar gadget which can do what you want. It's called Power Scheme and can be downloaded from this page.
Although you avoid 3rd party solutions, there is a tool called Power Plan Assistant for Windows® 7 which can do the job as well.
A:
Battery Care installs malware along with it. You can opt out (although not obviously at first glance). I would discourage users from installing software that bundles malware. The author gets barely enough to buy a beer per year from that stuff and it only serves as a distribution point for malware and spyware. It needs to end.
Here's an alternative that doesn't bundle any malware.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP script that writes a JSON file with iextrading API data
iextrading has two APIs (v1, v2) which provide financial market data. Following script records a JSON file with their equity information (using a CRON job).
Would you be kind and review it for any possible improvement or anything that may be incorrect?
<?php
date_default_timezone_set("UTC");
ini_set('max_execution_time' , 0);
ini_set('memory_limit','-1');
set_time_limit(0);
$i = new I();
I::scrapeAllStocks($i);
Class I
{
/**
*
* @var an integer for version of iextrading api
*/
private $version;
/**
*
* @var a string of iextrading symbols
*/
private $symbolsPath;
/**
*
* @var a string of our symbols json directory
*/
private $symbolsDir;
/**
*
* @var a string of target path and query
*/
private $targetQuery;
/**
*
* @var a string of iextrading base URL
*/
private $baseUrl;
/**
*
* @var a string of iextrading end point
*/
private $endPoint;
// For version 1, tokens are not required.
// SECRET TOKEN: *********************************
// PUBLISHABLE TOKEN: *********************************
## https://cloud.iexapis.com/beta/iex/tops?symbols=AAPL&token=*********************************
function __construct()
{
$this->version = 2;
$this->symbolsPath = __DIR__ . "/../../config/symobls.md";
$this->symbolsDir = __DIR__ . "/../../a/path/to/your/dir/symbols";
$this->targetQuery = "stock/market/batch?symbols=";
// baseUrl for version 1
$this->baseUrl = "https://api.iextrading.com/1.0/";
// baseUrl for version 2
// $this->baseUrl = "https://cloud.iexapis.com/beta/";
// endPoint for version 1
$this->endPoint = "&types=quote,chart&range=1m&last=10";
// endPoint for version 2
// $this->endPoint = "&token=*********************************&types=quote,chart&range=1m&last=10";
echo "YAAAY! Class I is running \n";
return true;
}
public static function symbs($i){
$fnm= $i->symbolsPath;
$cnt= file_get_contents($fnm);
$sym=preg_split('/\r\n|\r|\n/', $cnt);
$child=array();
$mother=array();
$c=100;
foreach ($sym as $k=>$v){
$c=$c-1;
$sym=preg_split('/[\t]/', $v);
array_push($child,$sym);
if($c<=0){
$c=100;
array_push($mother, $child);
$child=array();
}
}
return $mother;
}
public static function scrapeAllStocks($i){
$vStocks=I::symbs($i);
$baseUrl=$i->baseUrl.$i->targetQuery;
$currentTime=date("Y-m-d-H-i-s");
$allStocks=array();
foreach ($vStocks as $k=>$v) {
$s=array_column($v, 0);
$stockUrl=$baseUrl . implode(",", $s) . $i->endPoint;
$rawStockJson=file_get_contents($stockUrl);
$rawStockArray=json_decode($rawStockJson, true);
$allStocks=array_merge($allStocks, $rawStockArray);
}
$allStocksJson=json_encode($allStocks);
// Write the raw file
$symbolsDir= $i->symbolsDir;
if (!is_dir($symbolsDir)) {mkdir($symbolsDir, 0755,true);}
$rawStockFile=$symbolsDir . "/" . $currentTime . ".json";
$fp=fopen($rawStockFile, "x+");
fwrite($fp, $allStocksJson);
fclose($fp);
echo "YAAAY! stock large json file updated successfully! \n";
}
}
?>
Example of symobls.md:
A 2019-01-04 AGILENT TECHNOLOGIES INC
AA 2019-01-04 ALCOA CORP
AAAU 2019-01-04 PERTH MINT PHYSICAL GOLD ETF
AABA 2019-01-04 ALTABA INC
AAC 2019-01-04 AAC HOLDINGS INC
AADR 2019-01-04 ADVISORSHARES DORSEY WRIGHT
AAL 2019-01-04 AMERICAN AIRLINES GROUP INC
AAMC 2019-01-04 ALTISOURCE ASSET MANAGEMENT
AAME 2019-01-04 ATLANTIC AMERICAN CORP
AAN 2019-01-04 AARON'S INC
AAOI 2019-01-04 APPLIED OPTOELECTRONICS INC
AAON 2019-01-04 AAON INC
AAP 2019-01-04 ADVANCE AUTO PARTS INC
AAPL 2019-01-04 APPLE INC
AAT 2019-01-04 AMERICAN ASSETS TRUST INC
AAU 2019-01-04 ALMADEN MINERALS LTD - B
AAWW 2019-01-04 ATLAS AIR WORLDWIDE HOLDINGS
AAXJ 2019-01-04 ISHARES MSCI ALL COUNTRY ASI
AAXN 2019-01-04 AXON ENTERPRISE INC
AB 2019-01-04 ALLIANCEBERNSTEIN HOLDING LP
ABAC 2019-01-04 RENMIN TIANLI GROUP INC
ABB 2019-01-04 ABB LTD-SPON ADR
ABBV 2019-01-04 ABBVIE INC
ABC 2019-01-04 AMERISOURCEBERGEN CORP
ABCB 2019-01-04 AMERIS BANCORP
ABDC 2019-01-04 ALCENTRA CAPITAL CORP
ABEO 2019-01-04 ABEONA THERAPEUTICS INC
ABEOW 2019-01-04
ABEV 2019-01-04 AMBEV SA-ADR
ABG 2019-01-04 ASBURY AUTOMOTIVE GROUP
ABIL 2019-01-04 ABILITY INC
ABIO 2019-01-04 ARCA BIOPHARMA INC
ABM 2019-01-04 ABM INDUSTRIES INC
ABMD 2019-01-04 ABIOMED INC
ABR 2019-01-04 ARBOR REALTY TRUST INC
ABR-A 2019-01-04
ABR-B 2019-01-04
ABR-C 2019-01-04
ABT 2019-01-04 ABBOTT LABORATORIES
ABTX 2019-01-04 ALLEGIANCE BANCSHARES INC
ABUS 2019-01-04 ARBUTUS BIOPHARMA CORP
AC 2019-01-04 ASSOCIATED CAPITAL GROUP - A
ACA 2019-01-04 ARCOSA INC
ACAD 2019-01-04 ACADIA PHARMACEUTICALS INC
ACB 2019-01-04 AURORA CANNABIS INC
ACBI 2019-01-04 ATLANTIC CAPITAL BANCSHARES
ACC 2019-01-04 AMERICAN CAMPUS COMMUNITIES
A:
You cannot use a return in a __construct() method. If you need to check for any "badness", you can use throw/try/catch.Relevant resources: Return false from __constructor & PHP - constructor function doesn't return false (In the end, I support Sam's advice about writing class constants.)
Regarding your regex patterns, they can be simplified.
/\r\n|\r|\n/ is more simply expressed as /\R/ (I expect you will never need to contend with a solitary \r -- you could have also used /\r?\n/.)
/[\t]/ does not need to be expressed inside of a character class, so the square brackets can be omitted. (/\t/)
Now I am going to recommend that you completely abandon the contents of your symbs() method. Using regex is a sub-optimal tool for parsing your tab-delimited .md files. Using a combination of file() with iterative calls of str_getcsv() and a declaration of the your delimiting character makes for a concise and robust one-liner. So brief that you may choose to avoid writing the dedicated method entirely.
public static function symbs($i) {
return array_map(function($line){ return str_getcsv($line, "\t"); }, file($i->symbolsPath));
// PHP7.4: return array_map(fn($line) => str_getcsv($line, "\t"), file($i->symbolsPath));
}
// I tested this code locally using your .md file to make sure it worked as expected
Try to avoid single-use variable declarations. There are some cases where declaring variables improves the readability, but something straight forward like a datetime string generator is pretty safe to just inject into its final location in your script.
It is best to keep your variable declarations in reasonable proximity to the place(s) they are used. This will save you and other developers from having to do too much scanning to find what they need.
It would be a good idea for you to get familiar with PSR Coding Standards.
Most relevant to this question, please obey the PSR-2 recommendations.
A:
Why instantiate an object of class I if the only methods called are static? It appears that only private member variables that are never mutated are accessed. Instead of creating an object of class I just to pass to the static methods, you could use class constants or if you really want them kept private, use make those private variables static.
That way, the line the instance (i.e. $i = new I();) can be removed and the parameters (e.g. $i) can be removed from the method signatures, since they are no longer needed. It is up to you if you keep the constructor and destructor (e.g. if you end up needing to instantiate objects of that type then maybe you want those).
The class name I is a little vague/non-descriptive. Perhaps a more appropriate name would be something like StockController or StockScraper. Similarly the method name symbs could be better named - perhaps something like getSymbols.
What does the value 100 signify when used in that symbs method? Were you using 100 or more lines in your symbols.md file? If 100 is a special value, it should be stored in a constant or private static property.
I tried using the sample file which has 47 lines and thus when I tried the code, nothing was added to the array returned by symbs(). Perhaps the logic needs to be updated to handle array lengths lower than 100.
I presume there is a typo on this line:
$this->symbolsPath = __DIR__ . "/../../config/symobls.md";
given you gave a sample
Example of symobls.md:
So perhaps that line should be:
$this->symbolsPath = __DIR__ . "/../../config/symbols.md";
The last few lines of scrapeAllStocks() uses fopen(), fwrite() and fclose() to write the output file - is there a reason not to use file_put_contents() instead of all of those? Maybe you aren't familiar with that function, or else there is some write issue I am unaware of.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is meant by the rel="bookmark" link attribute?
What is the purpose of the rel="bookmark" attribute in <a> tags? For example:
<a href="http://stackoverflow.com/questions/ask" rel="bookmark">Click Here</a>
Does it serve any SEO- or SEM-related purpose?
A:
This has no SEO value or purpose. I believe the rel=bookmark tag was intended to mark permalinks but it never really gained traction
A:
An important use of the LINK element is to define a toolbar of navigation buttons or an equivalent mechanism such as menu items.
LINK relationship values reserved for toolbars are:
REL=Home
The link references a home page or the top of some hierarchy.
REL=ToC
The link references a document serving as a table of contents.
REL=Index
The link references a document providing an index for the current document.
REL=Glossary
The link references a document providing a glossary of terms that pertain to the current document.
REL=Copyright
The link references a copyright statement for the current document.
REL=Up
When the document forms part of a hierarchy, this link references the immediate parent of the current document.
REL=Next
The link references the next document to visit in a guided tour.
REL=Previous
The link references the previous document in a guided tour.
REL=Help
The link references a document offering help, e.g. describing the wider context and offering further links to relevant documents. This is aimed at reorienting users who have lost their way.
REL=Bookmark
Bookmarks are used to provide direct links to key entry points into an extended document. The TITLE attribute may be used to label the bookmark. Several bookmarks may be defined in each document, and provide a means for orienting users in extended documents.
From: http://www.w3.org/MarkUp/html3/dochead.html
A:
The attribute "rel" means relationship. It's a microformats. The HTML4 spec describes a bookmark as "a link to a key entry point within an extended document". By convention (citation needed), this entry point also captures the notion of a "permalink". Exemple:
<a href="archive/entry.html" rel="bookmark">A Document Entry</a>
Another exemple of rel attribute for tags:
<a href="http://technorati.com/tag/tech" rel="tag">tech</a>
http://microformats.org/wiki/rel-bookmark#rel.3D.22bookmark.22
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass value from JavaScript function to PHP variable?
I have a JavaScript that handles onkeydown event of a text input. How can I pass the value from this input or javascript function to a php variable ? I am not sure form can work, because the javascript function calls another Ajax function elsewhere
<?PHP
$valueOfInput = //how to assign this variable to value from text input ??
?>
<html>
<head>
<script>
function myFunc(e){
if (e.keyCode == 13)
{
pass_data_to_Ajax();
}
}
</script>
</head>
<body>
<div >
<input type="text" id = "lname" value="" onkeydown="myFunc(event)"/>
</div>
</body>
</html>
A:
Easy, but depends what exactly you want to do. Here's some example snippet of code:
<?php
if(!empty($_POST['lname'])) {
$valueOfInput = $_POST['lname'];
die(json_encode(array('status' => 'success', 'lname' => $valueOfInput)));
}
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<input type="text" id="lname" name="lname" value="" />
<script type="text/javascript">
$(document).ready(function() {
$("#lname").on("keypress", function() { // waiting for keypress event to be fired
setTimeout(function() { // delay to have the key value inserted into input, and affect value param
$.post(document.location.href, { lname: $("#lname").val() }, function(data) { // sending ajax post request
console.log(data);
});
}, 50);
});
});
</script>
</body>
</html>
You didn't write about any JS frameworks, but I assumed that it would be easier for you (beginner) to start with jQuery or some other framework which can help you with some abstraction around JS features.
Here brief description what's going on:
website is waiting till you start writing anything to the input (just as in your code)
script is handling typing event (keypress) and waits till the value is inserted to your input
script is sending an ajax request with input value as a param
PHP code is taking the value from $_POST superglobal array, and inserts it into your PHP variable
PHP code is sending response to the JS script that all good, and this response is printed in your console (you can do whatever you want - need with it)
Issue: It will send a lot of requests to the server, so consider better approach (change event instead of keypress?)
| {
"pile_set_name": "StackExchange"
} |
Q:
Does saving a jQuery element to a var cause the element to be re-sought upon use?
So, I have some JavaScript/jQuery that looks like this:
var $foo = $('#bar');
$foo.hide();
I've been operating under the assumption that jQuery operates on the given selector, and saves the resulting DOM element to the var $foo...which, as far as I can see is true.
However, does invoking $foo.hide() cause jQuery to re-seek the #bar element?
A:
No it doesn't, reference is made when $(elem) is called. This is why var is used, to store reference to element. It is always best practice to store references to var so next time code is used, old reference is used, and there is no need for searching DOM again.
//reference
var a = $('#id');
//use
a.hide();
//same reference, use again
a.show();
| {
"pile_set_name": "StackExchange"
} |
Q:
Ant macrodef: Is there a way to get the contents of an element parameter?
I'm trying to debug a macrodef in Ant. I cannot seem to find a way to display the contents of a parameter sent as an element.
<project name='debug.macrodef'>
<macrodef name='def.to.debug'>
<attribute name='attr' />
<element name='elem' />
<sequential>
<echo>Sure, the attribute is easy to debug: @{attr}</echo>
<echo>The element works only in restricted cases: <elem /> </echo>
<!-- This works only if <elem /> doesn't contain anything but a
textnode, if there were any elements in there echo would
complain it doesn't understand them. -->
</sequential>
</macrodef>
<target name='works'>
<def.to.debug attr='contents of attribute'>
<elem>contents of elem</elem>
</def.to.debug>
</target>
<target name='does.not.work'>
<def.to.debug attr='contents of attribute'>
<elem><sub.elem>contents of sub.elem</sub.elem></elem>
</def.to.debug>
</target>
</project>
Example run:
$ ant works
...
works:
[echo] Sure, the attribute is easy to debug: contents of attribute
[echo] The element works only in restricted cases: contents of elem
...
$ ant does.not.work
...
does.not.work:
[echo] Sure, the attribute is easy to debug: contents of attribute
BUILD FAILED
.../build.xml:21: The following error occurred while executing this line:
.../build.xml:7: echo doesn't support the nested "sub.elem" element.
...
So I guess I need either a way to get the contents of the <elem /> into a property somehow (some extended macrodef implementation might have that), or I need a sort of <element-echo><elem /></element-echo> that could print out whatever XML tree you put inside. Does anyone know of an implementation of either of these? Any third, unanticipated way of getting the data out is of course also welcome.
A:
How about the echoxml task?
In your example build file replacing the line
<echo>The element works only in restricted cases: <elem /> </echo>
with
<echoxml><elem /></echoxml>
results in
$ ant does.not.work
...
does.not.work:
[echo] Sure, the attribute is easy to debug: contents of attribute
<?xml version="1.0" encoding="UTF-8"?>
<sub.elem>contents of sub.elem</sub.elem>
Perhaps the XML declaration is not wanted though. You might use the echoxml file attribute to put the output to a temporary file, then read that file and remove the declaration, or reformat the information as you see fit.
edit
On reflection, you can probably get close to what you describe, for example this sequential body of your macrodef
<sequential>
<echo>Sure, the attribute is easy to debug: @{attr}</echo>
<echoxml file="macro_elem.xml"><elem /></echoxml>
<loadfile property="elem" srcFile="macro_elem.xml">
<filterchain>
<LineContainsRegexp negate="yes">
<regexp pattern=".xml version=.1.0. encoding=.UTF-8..." />
</LineContainsRegexp>
</filterchain>
</loadfile>
<echo message="${elem}" />
</sequential>
gives
$ ant does.not.work
...
does.not.work:
[echo] Sure, the attribute is easy to debug: contents of attribute
[echo] <sub.elem>contents of sub.elem</sub.elem>
| {
"pile_set_name": "StackExchange"
} |
Q:
IoC and .NET framework
I want to know what's the best practice with IoC pattern when dealing with .NET
For example, should I create SqlConnection/OracleConnection or any other provider through IoC container or with simple new keyword?
Does separating my class with concrete provider types has any value (including when I want to use only one type of provider)?
A:
It could have value for unit testing if you use the IDbConnection and all the other classes instead of concrete classes.
Other than IOC and stuff like that, I've actually used the DbFactoryProvider (some more info) several times to create my Connections and other DB related objects, and read the provider through the ConnectionString.
The major problem with the DB stuff is that usually you can't really use only ANSI-SQL with the database, so while you are decoupled from the concrete classes your sql is not transportable. (i/e limit in MySql or Over and Partition in Sql Server).
About DI/IOC with other stuff that's not DB related it's great to decouple your classes and remove dependencies, and helps when unit-testing, say when you have a service you're working against This is helpful even when not in unit testing, when you are working against a service and another team is still developing the service you can create a fake service that just basically solves your problems (not all) so you can work against something, before the real service is availiable.
There are a lot more examples, but working against services (DB repository/web/authorization/whatever) is the first most straightforward added value.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to select a row with maximum value in a column?
I have the following table
table_code table_family aa
---------------------------------------
F90 OT 49
F93 OT 1
F92 OT 1
I want to see result as follows:
F90 OT 49
I have tried the following SQL:
SELECT
table_code, MAX(table_family) table_family, aa
FROM
(SELECT
table_code, table_family, COUNT(*) aa
FROM
table1
GROUP BY
table_code, table_family)
GROUP BY
table_code, AA
This did not work.
Can anyone please help me?
A:
SELECT TOP(1) table_code, table_family, aa
FROM table1
ORDER BY aa DESC
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set up tns listeners for Multiple Oracle Installations on One machine
So I have two oracle installations on a development/testing machine (10g and 11g, respectively).
The platform is RHEL4.
Now I need to have both these oracle up and have tns listeners for them running.
How do I do that?
I've tried having separate listener.ora files in 10g's home dir and 11g's home dir, and try to start them up separately (under different users, oracer10 for 10g, oracer11 for 11g).
However, as soon as one of the tns listener is started, the other wont start and complain something like "TNS-01106: Listener using listener name LISTENER11 has already been started".
I do have different name for the two listeners. (LISTENER10 and LISTENER11)
Thanks,
Here are the listener.ora files
For 10g:
SID_LIST_LISTENER10 =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = /home/oracer/oracle/product/10.2.0/db_1)
(PROGRAM = extproc)
)
(SID_DESC =
(SID_NAME = CER)
(ORACLE_HOME = /home/oracer/oracle/product/10.2.0/db_1)
)
)
LISTENER10 =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC))
)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = SAP_1)(PORT = 1521))
)
)
)
For 11g:
SID_LIST_LISTENER11 =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = /home/oracer11/app/oracer11/product/11.2.0/dbhome_1)
(PROGRAM = extproc)
)
(SID_DESC =
(SID_NAME = CID)
(ORACLE_HOME = /home/oracer11/app/oracer11/product/11.2.0/dbhome_1)
)
)
LISTENER11 =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC))
)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = SAP_1)(PORT = 1522))
)
)
)
A:
You need to have different keys for the IPC entries in the two configurations, e.g. KEY = EXTPROC10 and KEY = EXTPROC11. IPC uses memory and semaphores etc. that may be shared across the machine, so you need to provide a way for the instances to be differentiated.
Also make sure you're starting the listeners explicitly, e.g. lsnrctl start listener10, and you have the environment set properly for your two accounts, including LD_LIBRARY_PATH pointing to the right ORACLE_HOME.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use of MongoDB in a Windows Service
I need to write a Windows Service in C# that stores data to a MongoDB database. My current code is:
var databaseName = MongoUrl.Create(connectionString).DatabaseName;
var server = new MongoClient(connectionString).GetServer();
_mongoDatabase = server.GetDatabase(databaseName);
var collection = _mongoDatabase.GetCollection<IMessageWrapper> ("Test");
collection.Save(test);
When using SQL databases it is usually very expensive to open a new connection, hence there's a pool. Is this still the case with Mongo?
I don't want to create a new connection on every save. On the other hand this is a long running service, if I use a single MongoClient I'm worried that say a network outage can kill it and stop my app until restart.
A:
The mongo driver does the connection pooling for you. There's no need to worry about it.
You won't create a new connection on every save and you don't need more than a single MongoClient.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I install software center on Ubuntu 18.04
I can't launch the Software & Updates center in Bionic Beaver. No video application will open. I tried to install the software center manually and got the following output:
neil@neil-ThinkPad-T420:~$ sudo apt-get install software-center
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package software-center is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'software-center' has no installation candidate
I'm not a technical adept and can barely follow simple terminal instructions. I need help.
A:
software-center has been replaced with gnome-software. So just type in a terminal
sudo apt install gnome-software
A:
as quality of packages in Ubuntu is going down the drain, Synaptic Package Manager is a decent replacement to Ubuntu Software Center, and is much better (far less buggy) than Gnome Software.
you can install it with:
sudo apt install synaptic
A:
If you want to get Software & Updates - it is located in software-properties-gtk package.
You can install it with:
sudo apt update
sudo apt install software-properties-gtk
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove current element from List in java
How do I remove current element from list while iterating using for loop?
I have below a list containing:
List<String> list = new ArrayList<String>();
list.add("a");
list.add("a2");
list.add("a3");
list.add("a4");
list.add("a5");
list.add("a6");
list.add("a7");
list.add("a8");
list.add("a9");
list.add("a10");
list.add("a11");
list.add("a12");
list.add("a13");
list.add("a14");
list.add("a15");
List<List<String>> parts = chopped(list, 4);
System.out.println(parts);
which gives me output below like this:
[[a, a2, a3, a4], [a5, a6, a7, a8], [a9, a10, a11, a12], [a13, a14, a15]]
Now I am trying to remove first list from the list in below program:
for(int i=0; i<parts.size(); i++){
System.out.println("Loop number: "+i);
System.out.println("Current list: "+parts);
Thread.sleep(2000);
parts.remove(i);
System.out.println("After removing: "+parts);
}
Here I am using parts.remove(i); to remove current element, it gives me the following output:
[[a, a2, a3, a4], [a5, a6, a7, a8], [a9, a10, a11, a12], [a13, a14, a15]]
Loop number: 0
Current list: [[a, a2, a3, a4], [a5, a6, a7, a8], [a9, a10, a11, a12], [a13, a14, a15]]
After removing: [[a5, a6, a7, a8], [a9, a10, a11, a12], [a13, a14, a15]]
Loop number: 1
Current list: [[a5, a6, a7, a8], [a9, a10, a11, a12], [a13, a14, a15]]
After removing: [[a5, a6, a7, a8], [a13, a14, a15]]
This one removes first current element [a, a2, a3, a4] which is correct but in running second loop it removes [a9, a10, a11, a12].
I want to remove it loop wise like below:
[[a, a2, a3, a4], [a5, a6, a7, a8], [a9, a10, a11, a12], [a13, a14, a15]]
[[a5, a6, a7, a8], [a9, a10, a11, a12], [a13, a14, a15]]
[[a9, a10, a11, a12], [a13, a14, a15]]
[[a13, a14, a15]]
[]
Edited:
When I try to access List inside List using parts.get(loopNumber) or parts.get(i)` it throws an exception error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at gmailSendLaptopGUI.MyProgram.main(MyProgram.java:156)
A:
The problem is that you are editing the list and at the same time reading it.
You have to decrease the counter when you remove an object from the list.
for(int i=0; i<parts.size(); i++){
System.out.println("Loop number: "+i);
System.out.println("Current list: "+parts);
Thread.sleep(2000);
parts.remove(i--);
System.out.println("After removing: "+parts);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Tinkerpop Gremlin server MissingPropertyException for SparkGraphComputer in remote mode
I am new to tinkerpop, gremlin and groovy.
I have configured a Tinkerpop Gremlin Server and Console [v3.2.3] with verified integration with HDFS and Spark.
Next I try to execute below code using gremlin console in local mode, everything works fine, a spark job is submitted and successfully processed.
:load data/grateful-dead-janusgraph-schema.groovy
graph = JanusGraphFactory.open('conf/connection.properties')
defineGratefulDeadSchema(graph)
graph.close()
hdfs.copyFromLocal('data/grateful-dead.kryo','data/grateful-dead.kryo')
graph = GraphFactory.open('conf/hadoop-graph/hadoop-load.properties')
blvp = BulkLoaderVertexProgram.build().writeGraph('conf/connection.properties').create(graph)
graph.compute(SparkGraphComputer).program(blvp).submit().get()
Next I connect gremlin console to gremlin server as remote using below command.
:remote connect tinkerpop.server conf/remote.yaml
After this I execute above code prefixing statements with ":> ". As soon as I submit last line which is submitting processing to SparkGraphComputer, I get below exception at the server -
[WARN] AbstractEvalOpProcessor - Exception processing a script on request [RequestMessage{, requestId=097785d6-7114-44fb-acbc-1b116dfdaac2, op='eval', processor='', args={gremlin=graph.compute(SparkGraphComputer).program(blvp).submit().get(), bindings={}, batchSize=64}}].
groovy.lang.MissingPropertyException: No such property: SparkGraphComputer for class: Script4
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)
at Script4.run(Script4.groovy:1)
at org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.eval(GremlinGroovyScriptEngine.java:619)
at org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.eval(GremlinGroovyScriptEngine.java:448)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233)
at org.apache.tinkerpop.gremlin.groovy.engine.ScriptEngines.eval(ScriptEngines.java:119)
at org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.lambda$eval$2(GremlinExecutor.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I am unable to understand what does MissingPropertyException means in groovy, is it similar to NoClassDefFound in java?
I believe some configuration is missing at the server end, can someone help me out?
A:
Well there's two ways to go about this. You can simply import SparkGraphComputer in the script that you're sending or you can add it to the scriptEngines configuration for your gremlin server. Something like
scriptEngines: {
gremlin-groovy: {
imports: [your.full.path.to.TheClass],
staticImports: [your.full.path.to.TheClass.StaticVar]
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
extracting check-box data from PDFs with Azure Read/OCR API
I have 1000s of survey forms which I need to scan and then upload onto my C# system in order to extract the data and enter it into a database. The surveys are a mix of hand-written 1) text boxes and 2) checkboxes. I am currently using the the Azure Read Api to extract hand-written text which should work fine e.g. question #4 below returns 'Python' and 'coding'.
So my question; will any Azure API (Read or OCR etc.) give me the capability to extract data for which checkbox is marked? e.g. see question #1 below - I need a string back saying 'disagree', is this possible with any Azure API or will I need to look elsewhere? If so, what API or library can I use to get hand-written checkbox data?
Can somebody with iText7 or IronOCR tell me if these libraries would allow me to extract the checkbox data below?
Survey Example:
A:
The answer for this isn't overly straightforward and involves creating custom code to parse the PDF yourself via a 3rd party library.
Since your forms are of a known shape, you know the locations of the checkboxes. You should construct a dictionary of "Checkbox name" and "Checkbox data" for each checkbox on the page. The data object could be an object that looks like:
public class CheckboxData {
public int startX { get; set; }
public int startY { get; set; }
public int endX { get; set; }
public int endY { get; set; }
public bool IsChecked { get; set; }
}
I would recommend using IronOCR to rasterize the PDF to an Image.
With your image, iterate over the checkbox dictionary and using the bounding points, move pixel by pixel and get the colour of the pixel. Store the colours in a list and then get the average colour of all pixels within the checkbox. If the average is above a threshold value for determining whether it's checked, set the IsChecked boolean.
For radio styled checkboxes, you will probably need a different data object and store the centre pixel of the circle. For the circles, you should store the centreX and centreY, along with the radius of the circle and use Bresenham Circle algorithm to know what pixels around that to check.
Below is an example of getting the pixel coordinates in GIMP for where the cursor is.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not all arguments converted during string formatting (Proving Collatz Conjecture)
When I run the code below I get an error. I have looked here on StackOverflow, but I ended up not solving my problem.
print "insert value"
value = raw_input ()
flag = False
i = 0
while flag:
if value == 1:
flag = True
elif value % 2 == 0:
value = value / 2
else:
value = value * 3
value = value + 1
i = i + 1
print "After", i, "attempts the conjecture has been demonstrated"
I get an error in the elif logical test value% 2 == 0 which says
not all arguments converted during string formatting
I think the problem is in the variable type but I tried the input function and forcing the int type, value = int (input (....)), but that also didn't work.
A:
In IDLE this worked for me
value = int(raw_input ())
converting raw input into integer
while True:
if value == 1:
break
elif value % 2 == 0:
value = value / 2
else:
value = value * 3
value = value + 1
i = i + 1
a bit simpler way to do while without having arbitrary flag
| {
"pile_set_name": "StackExchange"
} |
Q:
MicroBlaze AXI4 Exceptions
I am wondering about Data Bus Exceptions for the MicroBlaze. In the MicroBlaze product manual it states that the exception can only occur on M_AXI_DC when the cache is turned off? This doesn't make sense to me; does it mean that if an error response is given on the M_AXI_DC line, no exception will be triggered if caching is enabled? I currently have C_DCACHE_ALWAYS_USED set to 1 so that is not an issue.
Thanks.
Excerpt from MicroBlaze product guide:
The data cache AXI4 interface (M_AXI_DC) exception is caused by:
- An error response on M_AXI_DC_RRESP or M_AXI_DC_BRESP,
- OKAY response on M_AXI_DC_RRESP in case of an exclusive access using LWX.
The exception can only occur when C_DCACHE_ALWAYS_USED is set to 1 and the
cache is turned off
A:
Based on my hardware/software tests and using an AXI BRAM Controller to generate ECC fault injections, the MicroBlaze will not issue an data or instruction cache exception if caching is enabled, even if caching is disabled right before writing; and reenabled before reading to trigger the exception. This is also the case if the cache is flushed and invalidated, and then read immediately back.
This basically means that ECC is worthless in MicroBlaze designs that have caching enabled; as they do not trigger any hardware exceptions.
Even though the response by the AXI BRAM Controller is a SLVERR, the MicroBlaze will accept the data as is; as if nothing bad could possibly happen.
Who designed this. Seriously.
I guess the only surefire method is to use interrupts to detect ECC errors; which have a lower precedence than hardware exceptions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java calculating points of Angles in a non-right triangle
I am currently working on a project in which i need to draw a non-right triangle in the center of a JFrame using either, java.awt.Graphics's drawLine() or drawPolygon() methods. Both of these methods require the coordinates of all of the points to function. My problem is that instead of points, all i have are all of the angles and side lengths of the triangle. I've drawn up a nifty diagram of what I hope helps you visualize my problem:
(EDIT the position of C in this Senario is not fixed betwen a and b and may be anywhere below the axis on which AB rests)
as you can see from my picture, I need the coordantes of C based off the coordanes of A, is there any way to calculate this given the lengths of all sides and angles of the non-right triangle?
Bonus: How would i find an (x, y) value for A that would effectivly center the triangle in the middle of the JFrame?
A:
If you know angle CAB, the coordinate of point C should be:
(x+b·sin(θ), y-b·cos(θ))
In Java, there is:
double Math.sin(double radians);
double Math.cos(double radians);
Keep in mind that the angle needs to be in radians. If your angles are in degrees, try:
double Math.sin(Math.toRadians(double degrees));
double Math.cos(Math.toRadians(double degrees));
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
My app crashes suddenly
I am developing an android application. Suddenly, when I included a blank fragment, the application crashed. Before adding the fragment application worked without any problem. So it is clear that the fragment caused for the crash. So I want to get to know how to solve this issue.
A:
You could add breakpoints to your program and then run it in debug mode which should show you the line of code causing the crash.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to forward external traffic from specific port to specific external ip?
How do i forward outgoing traffic for specific port from internal network to specific external ip in watchguard? I know how to forward incoming traffic using SNAT.
A:
While I'm not familiar with Watchguard products, the concept of static NAT should work for both inbound and outbound traffic.
Researching it a little, it appears:
You would configure it using "1 to 1" NAT it appears (Watchguard's terminology for static NAT I guess).
http://www.watchguard.com/help/configuration-examples/nat_to_email_servers_configuration_example%20%28en-US%29.pdf
See OPTION #2 in that link from Watchguard.
(Oops...I misread your post. Are you wanting only specific outbound ports to be expressed as a certain external IP or all ports from one IP. My example is all ports from one internal IP. The example PDF should still help you. You should be able to use Dynamic NAT and a policy to allow for instance outbound port 25 from an internal IP to use one external IP and the rest of the ports (as a policy below the port 25 policy) to use a different external IP)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I get timepicker to fire on a click in the input field?
I have spent HOURS trying to get any new timepicker to work (previously used https://github.com/weareoutman/clockpicker which was great but always went off screen on mobile phones).
Most seem to be for Bootstrap 2.x and I cannot get any to work. Finally got https://github.com/Eonasdan/bootstrap-datetimepicker going (not great on a mobile but...)
My problem is I have lots of tiny input fields for dates so I need to get rid of the glyphicon and just onclick on the input field itself.
I have included my little test page in case anyone else is struggling. I did not realize that I needed moment.js and that cost me a very irritating 30 minutes.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" rel="stylesheet" href="/beta022/bootstrap/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/beta022/bootstrap/css/bootstrap-datetimepicker.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="/beta022/bootstrap/js/moment.js"></script>
<script type="text/javascript" src="/beta022/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="/beta022/bootstrap/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<form class="form">
<div class="form-group">
<div class='input-group date' id='datetimepicker4'>
<input type='text' class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker4').datetimepicker({
pickDate: false, minuteStepping:5,
});
});
</script>
</div>
</div>
</html>
EDIT: This is beyond weird. Got rid of the glyphicon. Put the other span around the input. Works but with a big ugly border. Tried disabling the input-group-addon class by changing it to adxxdon and worked perfectly (well no rounded corners). I then tried without that class and it stopped working. So looks like some sort of regex within span is going on.
I am well at the end of my JS/CSS ability. If anyone has a tidier solution I would be grateful.
A:
It's easy. Just refer to the documentation :)
http://eonasdan.github.io/bootstrap-datetimepicker/#example6
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable anchor tag in knockout.js
I need to disable the anchor tag inside a foreach loop of knockout.js in HTML.
Here is my code:
<a id="aQStreamSkype" data-bind="attr:{href: ''}, click: $parent.StoreUserClick,disable: ($data.SkypeId == 'null')">Skype </a>
A:
Anchor tags cannot be disabled. The easiest is to use ko if binding and then render a span instead of the anchor if the skype id is null
<!-- ko if: skypeId === null -->
<span >No Skype Id</span>
<!-- /ko -->
<!-- ko if: skypeId !== null -->
<a id="aQStreamSkype" data-bind="attr:{href: ''}, click: $parent.StoreUserClick,text: skypeId"></a>
<!-- /ko -->
Here is a fiddle
A:
If there is no href attribute on a element but only an action in a click binding, then an easy way would be passing expression condition && handler to a click binding.
If condition is observable you'll need to add parentheses.
<a data-bind="click: flag1() && handler">Enabled link</a>
<a data-bind="click: flag2() && handler">Disabled link</a>
It will be evaluated as false if condition is false (so nothing will happen), and will be evaluated as a handler if condition is true.
Fiddle here
A:
First off, there's a school of thought with which I have some sympathy that says just don't do it. A hyperlink that does nothing is just text.
However, I can see the flip side of the coin - I came across this same problem because I am using a Bootstrap dropdown menu which contains anchor tags as menu options, and to my mind it gives a better user experience to show the menu options as disabled rather than just not show them at all, and I feel it's cleaner to 'disable' the hyperlink than to include markup for a hyperlink and a span with the same text and then conditionally show one or the other. So, my solution was:
<a data-bind="click: checkCondition() ? myFunction : null, css: { disabled: !checkCondition() }"></a>
Note that checkCondition() is a function which returns true or false, indcating whether the hyperlink should be enabled or not. The css binding is just styling the hyperlink to appear disabled - you may have to add your own .disabled CSS class if you're not using Bootstrap.
The key to this working is that the anchor has no href attribute, so it's useless as a hyperlink without the Knockout click binding, which means that you could just as easily use this method with any element type (e.g. this could be a clickable span as easily as an anchor). However, I wanted to use an anchor so that my styling continued to be applied without any extra work.
| {
"pile_set_name": "StackExchange"
} |
Q:
log4j logging implementation at weblogic 12c
I am trying to change the logging implementation that weblogic12c uses to log4j.
I've followed these steps http://docs.oracle.com/middleware/1213/wls/WLLOG/config_logs.htm#i1014785 and I'v put log4j-1.2.14.jar and wllog4j.jar in DOMAIN_NAME/lib and restarted the domain.
After that I can't see the logging implementation list box that should be shown (http://docs.oracle.com/middleware/1213/wls/WLACH/taskhelp/logging/SpecifyTheLoggingImplementation.html) in environment -> server -> server -> loggin -> general -> advanced
I must be doing something wrong but I don't know what.
Thanks in advance
A:
I've been trying the same thing. I used WL 12.1.2 and the setting described in their documentation exists. Once I moved up to 12.1.3 the Logging Implementation drop down is gone. I found this comment that suggests that weblogic will be removing support for log4j.
https://www.linkedin.com/groups/Is-it-possible-send-weblogic-1320227.S.5926014706660704260
So, it's either a bug or forced removal. You might want to look at trying to configure slf4j in weblogic or just stick with java logging.
| {
"pile_set_name": "StackExchange"
} |
Q:
initializer lists in C and C++
For some reason I had this idea that C and C++ worked like this:
int foo[10] = {57};
for (int i=0; i<10; ++i)
assert (foo[i] == 57);
Turns out the remaining ints are initialized to 0, not 57. Where did I get this idea? Was this true at one point? Was it ever true for structure initializer lists? When did arrays and structures neatly and correctly start initializing themselves to 0 values when assigned to = {} and = {0}? I always thought they'd initialize to garbage unless explicitly told otherwise.
A:
It's been this way forever, as long as initializers existed. C89 says:
If there are fewer initializers in a list than there are members of an
aggregate, the remainder of the aggregate shall be initialized
implicitly the same as objects that have static storage duration.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I prove inequalities and one-to-one function?
Can anyone please help me with these questions?
1.Given
x + 1 < 0
Prove that:
i) $2x - 1 < 0 $
ii) ${2x-1\over x+1} > 2$
2.For $g(x) = {kx + 8\over 4x - 5}$
i) Find k if gg(x) = x
Is it fine if I just let any value of x for this question?
ii) Find the value of k so that g(x) is not a one-to-one function.
Thank you very much.
A:
(1 i) $x+1<0\Rightarrow 2\left( x+1 \right)<2.0\Rightarrow 2x+2<0\Rightarrow 2x+2-3<-3\Rightarrow 2x-1<-3<0$
so $2x-1<0.$
(1 ii)$$\frac{2x-1}{x+1}=\frac{2\left( x+1 \right)-3}{x+1}=2-\frac{3}{x+1}$$
because $x+1<0$ given we can write $$-\frac{3}{x+1}>0\Rightarrow 2-\frac{3}{x+1}>2 \Rightarrow\frac{2x-1}{x+1}>2$$
(2 i) we know if $g\left( x \right)=\frac{ax+b}{cx+d}$ then ${{g}^{-1}}\left( x \right)=\frac{-dx+b}{cx-a}$.
$g\left( g\left( x \right) \right)=x\Rightarrow g\left( x \right)={{g}^{-1}}\left( x \right)$ this means $g(x)=\frac{kx+8}{4x-5}=\frac{5x+8}{4x-k}={{g}^{-1}}\left( x \right)$ so $k=5.$
(2 ii) similar way
| {
"pile_set_name": "StackExchange"
} |
Q:
Where does the phrase "behind the wind" come from?
In Millennium: A History of the Last Thousand Years, chapter 4 ("The World Behind the Wind"), the second-to-last sentence:
On the evidence of the events of the fifteenth century, in the world east of the Bay of Bengal—the world "behind the wind", as Arab navigators called it—China could have [...]
There's more to the sentence, but it's not relevant to this question. (it's about why China didn't end up conquering Europe)
The part I'm interested in is the "the world 'behind the wind', as Arab navigators called it". Where was this term first used? i.e. he quotes Arab navigators, but which one and when?
A:
I can't answer when the term was first used but I can take a guess on why it was called that.
Arab sailors sailing the spice routes would have been dependent on the winds. Crossing the Indian Ocean, they would have experienced the prevailing winds, known as trade winds, blowing from the North East. So from the point of view of these Arab sailors, "the world east of the Bay of Bengal" would have been "behind the wind".
| {
"pile_set_name": "StackExchange"
} |
Q:
WINJS Timepicker how to
I have a service to which I receive two data (InTime & OutTime). These data are integer value in secs.
For example :
{
InTime : 36000,
OutTime : 57600
}
In my UI, I am using two TimePicker (WINJS.UI.Timepicker). In my timepicker I am using a 24 hour clock. I want to show these values in time picker. The values should be bound to time picker.
For example : In time should show me 10 : 00 and Out Time should show 16:00 in timepicker.
If user changes the value in time picker I should be bale to read that and convert that to seconds format so that I can do a post also.
So I have two problems:
How to convert these received time (in seconds to time) so that I can set the time picker value in UI.
When user changes, read the value from time picker, convert to seconds so that I can post it.
I have not been able to understand the TimePicker completely (Yes I have seen the samples), so I am having some issues here.
For the conversion, is there any javascript function already available ?
Any help appreciated.
Girija
A:
For you to convert the seconds to time format you can use the following javascript function
function secondsToTime(secs)
{
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
To display time in time picker ,you can set it in current property
<div data-win-control="WinJS.UI.TimePicker" data-win-options="{current='your value'}">
</div>
To detect user input and get value from time picker you can you need to register onchange event handler..
timePicker.onchange = hourChangeHandler;
function hourChangeHandler(event) {
// Insert code here.
}
Once you get the time from user you can convert it to seconds using this function
var hms = '02:04:33'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
This is to give you a start, you can change the data types and time format as per your requirements..
| {
"pile_set_name": "StackExchange"
} |
Q:
how to send json data stream to multiple topics in kafka based on input fields
I have to consume json data coming to kafka stream and send to diffrent topics (distinct combination of app id and entity) for further consumption.
topic names :
app1.entity1
app1.entity2
app2.entity1
app2.entity2
Json Data
[
{
"appId": "app1",
"entity": "entity1",
"extractType": "txn",
"status": "success",
"fileId": "21151235"
},
{
"appId": "app1",
"entity": "entity2",
"extractType": "txn",
"status": "fail",
"fileId": "2134234123"
},
{
"appId": "app2",
"entity": "entity3",
"extractType": "payment",
"status": "success",
"fileId": "2312de23e"
},
{
"appId": "app2",
"entity": "entity3",
"extractType": "txn",
"status": "fail",
"fileId": "asxs3434"
}
]
TestInput.java
private String appId;
private String entity ;
private String extractType;
private String status;
private String fileId;
setter/gtter
SpringBootConfig.java
@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs(KafkaProperties kafkaProperties) {
Map<String, Object> config = new HashMap<>();
config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers());
config.put(StreamsConfig.APPLICATION_ID_CONFIG, kafkaProperties.getClientId());
config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, new JsonSerde<>(TestInput.class).getClass());
config.put(JsonDeserializer.DEFAULT_KEY_TYPE, String.class);
config.put(JsonDeserializer.DEFAULT_VALUE_TYPE, TestInput.class);
return new KafkaStreamsConfiguration(config);
}
@Bean
public KStream<String, TestInput> kStream(StreamsBuilder kStreamBuilder) {
KStream<String, TestInput> stream = kStreamBuilder.stream(inputTopic);
// how to form key , group records and send to different topics
return stream;
}
I searched a lot but didnt find anything near which publishes data to topics dynamically. Please help experts
A:
Use stream.branch()
See https://www.confluent.io/blog/putting-events-in-their-place-with-dynamic-routing/
Next, let’s modify the requirement. Instead of processing all events in the stream, each microservice should take action only on a subset of relevant events. One way to handle this requirement is to have a microservice that subscribes to the original stream with all the events, examines each record and then takes action only on the events it cares about while discarding the rest. However, depending on the application, this may be undesirable or resource intensive.
A cleaner way is to provide the service with a separate stream that contains only the relevant subset of events that the microservice cares about. To achieve this, a streaming application can branch the original event stream into different substreams using the method KStream#branch(). This results in new Kafka topics, so then the microservice can subscribe to one of the branched streams directly.
...
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I ask a teller for money at the bank?
I need to go to the bank and withdraw some money. I need to withdraw $30, $22 to pay my roommate for the internet and $8 for laundry. Since neither of these can make change, I need my $30 to be split into two partitions of the two sizes. That means when the teller asks me how I want my $30 I am going to have to make a request. I could tell them I want it in a twenty, a fiver, and five ones. But I want to make my request as simple as possible as to avoid having to repeat myself. To make my request simpler I could ask that my cash contain a twenty and at least 2 ones because the 8 is implied by the total, but better yet I could simply request that one of the bills I receive be a one dollar bill (If you are not convinced of this just try to make 29 dollars without making 8).
So that's all fine and dandy but I need to do this calculation every time I go to the bank so I thought I would write a program to do this (have you write a program to do this for me).
Your program or function should take a list of integers representing all the payments I need to make and a set of integers representing the denominations of bills available at the bank, and you must output the smallest list of denominations such that every way to make the total that includes that list of denominations can be cleanly divided into the list of payments.
Extra rules
You may assume that the denomination list will always contain a 1 or you may add it to each list yourself.
Some inputs will have multiple minimal solutions. In these cases you may output either one.
This is code-golf so answers will be scored in bytes with less bytes being better.
Test Cases
Payments, denominations -> requests
{22,8} {1,2,5,10,20,50} -> {1} or {2}
{2,1,2} {1,5} -> {1}
{20,10} {1,2,5,10,20,50} -> {}
{1,1,1,1} {1,2} -> {1,1,1}
{20,6} {1,4,5} -> {1}
{2,6} {1,2,7} -> {2}
{22, 11} {1, 3, 30, 50} -> {1, 3}
{44, 22} {1, 3, 30, 50} -> {1, 3, 3, 30}
A:
JavaScript (ES6), 485 476 bytes
Alright ... this is a monster. :-(
But it's a rather fast monster that solves all test cases almost instantly.
I may attempt some more advanced golfing later, but I've already spent far too much time on it.
f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L])
Test cases
f=(b,a,L=[...a])=>L.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).sort((a,b)=>a[b.length]||-1).find(L=>(Y=G(U(b)-U(L),L.sort((a,b)=>a-b)),Y[0]&&!Y.some(a=>P(b.map(a=>G(a,[]))).every(b=>b+''!=a))),U=a=>~~eval(a.join`+`),P=(e,C=[],R=[])=>e[0].map(v=>R=(c=v.map((x,i)=>x+(C[i]|0)),e[1])?[...P(e.slice(1),c),...R]:[c,...R])&&R,G=(n,l)=>(S=[],g=(n,l)=>n?a.map(x=>x<l[0]|x>n||g(n-x,[x,...l])):S=[l.map(v=>s[a.indexOf(v)]++,s=[...a].fill(0))&&s,...S])(n,l)&&S)||f(b,a,[...a,...L])
console.log(JSON.stringify(f([22,8], [1,2,5,10,20,50])))
console.log(JSON.stringify(f([2,1,2], [1,5])))
console.log(JSON.stringify(f([20,10], [1,2,5,10,20,50])))
console.log(JSON.stringify(f([1,1,1,1], [1,2])))
console.log(JSON.stringify(f([20,6], [1,4,5])))
console.log(JSON.stringify(f([2,6], [1,2,7])))
console.log(JSON.stringify(f([22,11], [1,3,30,50])))
console.log(JSON.stringify(f([44,22], [1,3,30,50])))
How?
NB: This is not matching the current version anymore, but is much easier to read that way.
// b = list of payments, a = list of bills,
// L = list from which the requested bills are chosen
f = (b, a, L = [...a]) => (
// U = helper function that computes the sum of an array
U = a => ~~eval(a.join`+`),
// P = function that computes the summed Cartesian products of arrays of integers
// e.g. P([[[1,2],[3,4]], [[10,20],[30,40]]]) --> [[33,44], [13,24], [31,42], [11,22]]
P = (e, C = [], R = []) => e[0].map(v => R =
(c = v.map((x, i) => x + (C[i] | 0)), e[1]) ? [...P(e.slice(1), c), ...R] : [c, ...R]
) && R,
// G = function that takes a target amount and a list of requested bills and returns
// all combinations that contain the requested bills and add up to this amount;
// each combination is translated into a list of number of bills such as [2,0,0,1,0]
G = (n, l) => (
S = [],
g = (n, l) => n ?
a.map(x => x < l[0] | x > n || g(n - x, [x, ...l])) :
S = [l.map(v => s[a.indexOf(v)]++, s = [...a].fill(0)) && s, ...S]
)(n, l) && S,
// compute X = list of possible bill combinations to process all payments
X = P(b.map(a => G(a, []))),
// compute the powerset of L and sort it from shortest to longest list
L.reduce((a, x) => [...a, ...a.map(y => [x, ...y])], [[]])
.sort((a, b) => a[b.length] || -1)
.find(L => (
// compute Y = list of possible combinations to reach the total amount,
// using the requested bills
Y = G(U(b) - U(L), L.sort((a, b) => a - b)),
// exit if Y is not empty and all combinations in Y allow to generate all payments
Y[0] && !Y.some(a => X.every(b => b + '' != a)))
)
// if no solution was found, enlarge the set of requested bills and try again
|| f(b, a, [...a, ...L])
)
A:
Python 2, 456 455 bytes
Extremely, extremely, extremely slow!!!!
Should work correctly on all the input examples given enough time
Edit: Saved 1 byte thanks to @Jonathan Frech
def F(p,d):v=sum(p);E=enumerate;l=lambda x,y:y[1:]and(x>=y[-1]and[k+[y[-1]]for k in l(x-y[-1],y)]+l(x,y[:-1])or l(x,y[:-1]))or[[1]*x];Q=l(v,d);m=lambda x,y=[0]*len(p):x and max(m(x[1:],[a+x[0]*(i==j)for i,a in E(y)])for j,_ in E(y))or y==p;f=lambda x,h=[]:x and min([S for i,s in E(x)for S in h+[s],f(x[:i]+x[i+1:],h+[s])if all(map(m,filter(lambda k:all(k.count(j)>=S.count(j)for j in S),Q)))],key=len)or[1]*v;print-(all(map(m,Q))-1)*min(map(f,Q),key=len)
Try it online!
Explanation
p,d=input() # Read input
v=sum(p) # Save a byte by keeping track of the total money withdrawn
E=enumerate # We use enumerate a lot
# Generates the possible combinations of denominators that add up to the withdrawn amount
l=lambda x,y:y[1:]and(x>=y[-1]and[k+[y[-1]]for k in l(x-y[-1],y)]+l(x,y[:-1])or l(x,y[:-1]))or[[1]*x]
# We use the list generated by l quite a few times
Q=l(v,d)
# Checks if we can divide a list of denominators x in such a way that we get the wished division of the money
m=lambda x,y=[0]*len(p):x and max(m(x[1:],[a+x[0]*(i==j)for i,a in E(y)])for j,_ in E(y))or y==p
# For a list of denominators, it tries all possible combinations of the denominators as input to the teller, selecting the one with minimum length
f=lambda x,h=[]:x and min([S for i,s in E(x)for S in h+[s],f(x[:i]+x[i+1:],h+[s])if all(map(m,filter(lambda k:all(k.count(j)>=S.count(j)for j in S),Q)))],key=len)or[1]*v
# Call f with all possible lists of denominators, and check if saying nothing to the teller will work
print-(all(map(m,Q))-1)*min(map(f,Q),key=len)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a more efficient query for specific, non-consecutive dates in mysql?
I am trying to query a table for all rows that match a few specific dates. The dates are not consecutive and returning data for the entire date range is not desired. The number of specific dates can be quite large, a couple of hundred. The Date field is indexed, so I'd like to make use of it.
Converting the Date field into a string and querying on string comparison feels a bit lazy/non-performant and discards any indexing. Something like this (below) works correctly but I am concerned about performance and scanning the table:
SELECT Date,Time,Open,High,Low,Close,Volume FROM minuteBarTable
WHERE DATE(Date) IN ('2004-07-13','2011-09-01','2007-12-12');
Using a block of 'OR's has the right effect and correct result, but I'd like to find a more elegant/scalable approach. It can become a bit unwieldy with hundreds of dates:
SELECT Date,Time,Open,High,Low,Close,Volume FROM minuteBarTable
WHERE Date='2004-07-13' OR Date='2011-09-01' OR Date='2007-12-12';
Is the block of 'OR's the more efficient approach here?
A:
Combine the two SQLs above:
SELECT Date,Time,Open,High,Low,Close,Volume FROM minuteBarTable
WHERE Date IN ('2004-07-13','2011-09-01','2007-12-12');
This way MySQL can use the index on Date. And (according to O'Reilly's High Performance MySQL) IN is usually better than multiple ORs, because the query optimizer sorts the arguments in the IN list, so it will be faster to find the results in the index (which is sorted as well).
| {
"pile_set_name": "StackExchange"
} |
Q:
Need to make a url query string persist across a link
So, I found this similar request, but the poster answered himself with going into details:
Persistent URL query string throughout the entire site?
Essentially, I have an event management website where I can edit html and javascript, but not php. I am trying to setup passing a discount code through a link to use for affiliate tracking. The system already allows for the code to be passed in a query in the form of:
https://www.example.com/reg/newreg.php?eventid=89335&discountcode=code
BUT
The caveat is that the system only allows that when linking the person directly into the registration process as shown above. Since no one is going to want to buy a ticket without seeing the event details, this is all but useless. The address of the homepage is in the form of:
https://www.example.com/home/89335
But when I try appending &discountcode=code to the address, the query string is lost upon clicking the registration link and going to the registration page.
Any suggestions on how to handle this?
Thanks!
A:
You could try to parse all a-tags containing a href and update the href using javascript.
If you can use jQuery, you could do it that way (completely untested, so this could not work directly, but you should get the way to the solution :))
To get the url param, you could use the solution from here: https://stackoverflow.com/a/5158301/2753126
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
jQuery(document).ready(function ($) {
var persistedQueryParam = getParameterByName('discountcode');
if (persistedQueryParam && persistedQueryParam.length > 0) {
$('a[href]').each(function () {
var elem = $(this);
var href = elem.attr('href');
elem.attr('href', href + (href.indexOf('?') != -1 ? '&' : '?') + 'discountcode=' + persistedQueryParam);
});
}
});
Just replace the 'discountcode' strings with your real parameter name.
Hope that helps.
Best regards,
Chris
Update: added querystring and '?' / '&' handling.
Update 2: changed from prop to attr.
Update 3: changed from 'param' name to 'discountcode'.
Uüdate 4: added length check @ persistedQueryParam and finally got the chance of testing the script :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot read data into colab
I've mounted my Google Drive folder using code
from google.colab import drive
drive.mount("gdrive", force_remount=True)
as my data files are all under gdrive/My Drive.
Then I want to concat all the files ended with "_1m." using code
import os
import glob
path ='/gdrive'
allFiles = glob.glob(path + "/*_1m.*")
df_tmv_report = pd.DataFrame()
for file_ in allFiles:
df = pd.read_csv(file_, sep=',')
list_.append(df)
df_data = pd.concat(list_).iloc[:,1:].reset_index()
Colab returned
ValueError Traceback (most recent call last)
<ipython-input-13-ec891ccb4282> in <module>()
----> 1 df_data = pd.concat(list_).iloc[:,1:].reset_index()
1 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/reshape/concat.py in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy, sort)
260
261 if len(objs) == 0:
--> 262 raise ValueError('No objects to concatenate')
263
264 if keys is None:
ValueError: No objects to concatenate
I am not sure how to read the files correctly. Please help, thanks.
A:
If you executed drive.mount("gdrive"), your Drive files will be present in /content/gdrive rather than /gdrive. (The default working directory is /content.)
Try adjusting your path to /content/gdrive. You can use the file browser in the left hand panel to ensure your Drive is mounted where you expect.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I cycle a WiFi transmitter through all modes, for FCC intentional radiator EMC testing?
I'm integrating a WiFi/Bluetooth module into a consumer product, however
the module does not have a modular grant, will not have a modular grant, and is anyway getting paired with a unique internal antenna.
Per https://apps.fcc.gov/eas/comments/GetPublishedDocument.html?id=50&tn=916170 (FCC publication 996369 Section 15.212), that means certification as an intentional radiator.
I have also read http://www.emcfastpass.com/rf-modules/ on the benefits of single-modular and limited single-modular certification.
The question is: if I must certify as an intentional radiator, how is the WiFi module cycled through testing modes? My testing lab says we must do low, and mid on each band, plus each modulation mode and speed, for each regulatory region. The permutations are huge:
Two bands (2.4Ghz and 5Ghz)
Eight protocols (802.11a, 802.11b, 802.11g, 802.11n, 802.11ac, Bluetooth, BTLE)
Six modulation techniques (FHSS DSSS OFDM HR-DSSS 256-QUAM CKM) at various data rates from 1 to 54 Mbps.
Two channel pairings (20 Mhz, 40 Mhz)
Three regulatory regions (US/Canada, Japan, Europe).
A few of the above are documented at http://www.intel.com/content/www/us/en/support/network-and-i-o/wireless-networking/000005725.html
Perhaps this is why I was quoted $50k and up for the testing, and 12 weeks, with 10 days of lab time at 8 hours of chamber time per day.
Is this really what's done?
And how are those modes set anyway? I can imagine:
Load special software into the Linux driver which runs through test modes. This requires cooperation with the chip vendor (internal chip is Broadcom BCM43341). However, this is not representative of the product in real use. The WiFi driver is not fully under my control, so running software from the module maker may be difficult or impossible.
Have a trick Access Point, that can cycle through the modes. Each time have the product connect to the AP and stream data until the test data is collected.
The device pre-tests perfectly for unintentional radiation: passing with flying colors, even with an active AP co-resident in the chamber.
It's an IoT kind of device, so has no way to hook to a Windows PC for testing.
A:
In my experience, the WiFi module supplier will have programmed test modes into the module that support the testing that is required for product certification. Hopefully your supplier has done so as well.
The problem I've seen is that the documentation for these modes is not publicly available, so we have to call and establish an engineering relationship to get it. Often times it is not as stable as we'd like (meaning: we've seen "undocumented features" in test modes).
My group had to hound a very large and well known silicon manufacturer to get their certification documentation (which we found was incomplete and nudged them to get it up to date) and information on how the test API worked. Once we got it, we wrote custom test software packages to set up the proper transmission for the proper test.
We included a user interface since fiddling with software configurations at a test lab is the wrong place to be doing that - better to make it quick, easy and foolproof.
When we started with WiFi modules, we thought that it was super easy - simply put the module into the product and use it in the way that it was certified by the manufacturer, put their FCC ID on the sticker and done. Not so. WiFi module manufacturers may not certify to all product applications - or in fact only a few generic ones - and so you may find yourself having to go to the lab for a wireless cert because you put it in a product whose application didn't conform to the FCC cert the module manufacturer did.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to decrease font size in jqgrid treegrid leaf rows
jqGrid treegrid all rows have same font size. How to decrease font size of rows which does not have any children ?
I tried to use Oleg great answer in How to make jqgrid treegrid first row text bold to use rowattr for this.
I havent found a way how to dedect in rowattr that row does not have children.
I current specific case all leafs are in third level. So in this case it is possible to decrease font size for whole third level. How to find treegrid nesting level in rowattr ?
Treegrid is defined as
var treegrid = $("#tree-grid");
treegrid.jqGrid({
url: '/Store/GridData',
datatype: "json",
mtype: "POST",
height: "auto",
loadui: "disable",
treeGridModel: "adjacency",
colModel: [
{ name: "id", width: 1, hidden: true, key: true },
{ name: "menu", classes: "treegrid-column", label: "Product tree" },
{ name: "url", width: 1, hidden: true }
],
gridview: true,
rowattr: function (rd) {
// todo: decrease font size for leaf rows.
if (rd.parent === "-1" ) {
return {"class": "no-parent"};
}
},
autowidth: true,
treeGrid: true,
ExpandColumn: "menu",
rowNum: 2000,
ExpandColClick: true,
onSelectRow: function (rowid) {
var treedata = treegrid.jqGrid('getRowData', rowid);
window.location = treedata.url;
}
}
);
A:
I have never used treegrid, from the sample provided by Oleg it seems to be that in grid data there is an item isLeaf. I think you have to check for rd.isLeaf See the demo here the data used there is (first row)
{id: "1", name: "Cash", num: "100", debit: "400.00", credit: "250.00", balance: "150.00", enbl: "1", level: "0", parent: "null", isLeaf: false, expanded: true, loaded: true, icon: "ui-icon-carat-1-e,ui-icon-carat-1-s"},
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set user attribute using devise user_id before_create
Using devise, I'm trying to set a custom attribute automatically after a user is created.
Here is what I have in my User model.
after_save :set_attribute_to_devise_id
private
def set_attribute_to_devise_id
self.custom_attribute = self.id
end
When a user registers and an account is created, the custom_attribute is not saving the ID that devise generated. However, when testing in the console, running User.save on the user seems to update the custom_attribute, but does not persist or save to the database permanently.
I've tried after_commit as well as after_create without any luck. How do I save the user.id from Devise automatically to another attribute column on user creation?
A:
The callback should be before_save at max.
after_save is run when all the changes have been saved into the database, so in this case it is too late.
| {
"pile_set_name": "StackExchange"
} |
Q:
Output dynamic array from a function pointer
I'm very new to pointers so please bear with me...
My code defines a function for the multiplication of two matrices (matrixMultiplication). I have then defined a function pointer to this function.
#include <iostream>
void matrixMultiplication (const double A[3][3], const double B[3][3], double output[3][3])
{
int i, j, k;
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
output[i][j]+=A[i][k]*B[k][j];
}
}
}
}
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
int main ()
{
using namespace std;
double A[3][3]={{1,1,1},{1,1,1},{1,1,1}};
double B[3][3]={{1,1,1},{1,1,1},{1,1,1}};
cout<<"The function returns..."<<endl;
double print[3][3]=matrixMultiplication(A,B);
int i, j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
cout<<print[i][j]<<"\t";
}
cout<<"\n";
}
return 0;
}
What I want to do is output the array given by the pointer function, *matrixMultiplication, using a for loop (just for aesthetic purposes). I have played around with the code and ended up with initialiser or segmentation (11) errors. I feel like I'm missing something blatantly obvious given I'm new to C++...
Any ideas would be most welcome!
A:
The problem is with:
double (*matrixMultiplication (const double (*left)[3], const double (*right)[3]))[3]
{
double output[3][3];
matrixMultiplication(left, right, output);
}
I don't know what it is and neither does my compiler! ;)
Using functional, a matrixMultiplication function type can be defined and used, like so:
#include <functional> // or <tr1/functional>
// type
typedef function<void (const double[3][3], const double[3][3], double[3][3])> MatrixFunction;
// instance
MatrixFunction matrixFunctionPtr(&matrixMultiplication);
// call
matrixFunctionPtr(A,B,print);
Note: you also need to declare your output array double print[3][3]; * before* you call the matrixMultiplication function...
| {
"pile_set_name": "StackExchange"
} |
Q:
how pass TextField text from QString in C++?
Hi Guys, i need take the text of TextField QML then pass to QString in C++.
Firstpage.qml:
Component {
id: mainView
Row {
Image {
id: logo
anchors.fill: parent
source: "Imagens/jscalcadosLogo.png"
}
ColumnLayout {
id: layoutLogin
anchors.centerIn: parent
anchors.margins: 3
spacing: 3
TextField {
id: login
objectName: "login"
Layout.fillWidth: true
placeholderText: "Username"
}
Main.cpp:
int main(int argc, char *argv[]){
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QQuickView *view = new QQuickView;
view->setSource(QUrl::fromLocalFile("FirstPage.qml"));
QObject *object = view->rootObject();
QObject *textin = object->findChild<QObject*>("login");
//QString input = textin->Property("text").toString(); // crash the program
return app.exec();
}
When i try convert Textin to QString the program crash
any idea ? i'm sorry for my bad english.
A:
The general rule is: Don't read or write something in QML from C++
Instead, you shall create a QObject-derived instance in C++ that has a property for that text. You expose that QObject to QML, either by setting it as a context property or registering it as a singleton.
Then in QML you set afore-mentioned property - et voila - you have pushed the text from the QML world to the C++.
There are various questions on StackOverflow regarding the interaction of C++ and QML (I might search for them later, and probably flag your question as duplicate, for I am sure your question is not the first).
Also the documentation has more information on this.
| {
"pile_set_name": "StackExchange"
} |
Q:
How is average network hashrate determined?
ethstats has this statistic, currently at 48.3TH/s, but how do they determine it? Are hashrates reported by nodes added up and averaged over so many blocks?
A:
While I can't tell you how ethstats calculates the average network hash rate, I can tell you that they almost certainly don't use reported values from nodes. Firstly, it would be difficult for them to connect to all nodes. This would be okay if they were to connect to all the nodes with substantial mining capacity, but I don't think all nodes report a speed.
More likely, and the way I would calculate it, is to look at the average difficulty (this is baked into the blocks themselves) and the average time to solve a block. Since the expected time to solve a block is difficulty / hash rate (this relationship can be derived from the Ethereum source code), one can solve, algebraically, and find that the network hash rate is the average difficulty divided by the average block time. Then you just need to pick your window in terms of number of blocks used for computing the average. For example, right now, the difficulty is ~1240TH - which means that one successful hash is expected to be found every 1240 trillion hashes. Since the average block time is roughly 18.9s, the current network hash rate is roughly 65TH/s.
| {
"pile_set_name": "StackExchange"
} |
Q:
Who do the job of ViewResolver in Spring4 Rest Controller? & who render views after request?
Simple Controller & Tiles View Resolver => it works
/**
* For Exple:
* Spring Controller
* & Tiles View Resolver
* It Works Well
*/
@Controller
public class Home {
@Autowired
private IManager<BaseObject> manager;
public void setManager(IManager<BaseObject> manager) {
this.manager = manager;
}
@RequestMapping(value = "/listprovider", method = RequestMethod.GET)
public String listProvider(ModelMap model) {
model.addAttribute("listprovider",this.manager.getAllProvider());
return "listProviderPage";
// listProviderPage ==> the name of the rendered (Tiles)View.
// it works well
}
}
But with RestController the render is only a JSON not a view page, I want to render the view page & JSON data both.
/**
* But with
* Spring4 RestController
*
*/
@RestController
public class Home {
@Autowired
private IManager<BaseObject> manager;
public void setManager(IManager<BaseObject> manager) {
this.manager = manager;
}
@RequestMapping(value = "/listprovider", method = RequestMethod.GET)
public String listProvider() {
return this.manager.getAllProvider(); // Message Converter To Json
// what about the view?
// what is the secret of view resolver in **Spring Rest**
}
}
A:
@RestController is the combination of @Controller and @ResponseBody.
When you use @RestController , response gets converted in Json format implicitly and there is no need to declare @ResponseBody explicitly.
It is defined to send only the data in defined formats and retrieval of any view is not possible using it.
If you want to retrieve page from @restcontroller , you need to use ModelandView or
write a new controller and annotate with @Controller and return view name so it will look for view resolver and render the appropriate page.
You need to configure view resolver like below in spring configuration file
@Bean
public UrlBasedViewResolver urlBasedViewResolver()
{
UrlBasedViewResolver res = new InternalResourceViewResolver();
res.setViewClass(JstlView.class);
res.setPrefix("/WEB-INF/");
res.setSuffix(".jsp");
return res;
}
So when you return page name from controller, view resolver look for appropriate jsp page in WEB-INF folder and return view.
Below link for reference
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ViewResolver.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Access property/constant in extended classes
I'm trying to achieve the following:
I have a parent class, with some logic. In the child class, I "redefine" constants/properties. Is there any way to make the child properties accessible by methods defined in the parent class? Or to be more specific - is there any way to force the "out" method to write extended rather than base in the following example?
public class BaseTest {
public static final String x = "base";
public void out() {
System.out.println(x);
}
}
public class ExtendedTest extends BaseTest{
public static final String x = "extended";
}
public class Main {
public static void main(String[] args) {
BaseTest base = new BaseTest();
ExtendedTest extended = new ExtendedTest();
base.out(); // base (as expected)
extended.out(); // base (extended expected)
System.out.println(extended.x); // extended (as expected)
}
}
I come mainly from the world of PHP, where this approach works just fine. Dunno if I'm missing something or if the very design of Java does not allow this.
Thank you.
Note: This is not important whether the property is static or not. I just wanted to be able to override a property of any kind in a child class (just like I can override a method) which, on basis of the answers I've received so far, doesn't seem to be possible in Java. In PHP it is absolutely possible and that was why I asked the question.
A:
static fields are not subject to inheritance. The x in the body of the out() method refers to BaseTest.x. Since you are not overriding out(), the body of the out() method still prints the value of BaseTest.x.
A:
Static members are resolved at compile-time, and adding an ExtendedTest.x does not affect the also-existing BaseTest.x, which is what the BaseTest#out() method is linked to.
To accomplish what you're wanting, you need an overridden method:
public class BaseTest {
public String x() {
return "base";
}
public final void out() {
System.out.println(x());
}
}
public class ExtendedTest extends BaseTest {
@Override
public String x() {
return "extended";
}
}
This pattern is commonly used with an abstract method in the base class or interface to require the subclass to define an attribute such as a name or a key.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to queryselector a template object from javascript
Basically, I want to querySelect a <template> from javascript and I keep getting null.
JavaScript file:
class MyImportWebcomponent extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
const shadowRoot = this.attachShadow({ mode: "open" });
const template = document.querySelector("my-import-webcomponent-template");
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
}
customElements.define("my-import-webcomponent", MyImportWebcomponent);
Template object from my vanilla webcomponent
<template id="my-import-webcomponent-template">
<div id="mydiv" name="mydiv">
<p>Trying html importing another javascript file</p>
</div>
</template>
<script src="/to-try/my-import-webcomponent.js"></script>
index.html
<my-import-webcomponent></my-import-webcomponent>
<link rel="import" href="./to-try/my-import-webcomponent.html" />
The main issue is that document.querySelector("my-import-webcomponent-template") returns undefinied.
IN case it adds something usefull, if I try keep both javascript and html in same file and instead of querySelector I create straight the element, I successfully can do it.
All in a single file
const templateString = `<div id="mydiv" name="mydiv"><p>Trying html plus javascript in same file</p></div>`;
const template = document.createElement("template");
template.innerHTML = templateString;
export class MyCompleteWebcomponent extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define("my-complete-webcomponent", MyCompleteWebcomponent);
My question would be exact the same as queryselector if it wasn't for two reasons: (1) they seemed to rely on Polifys which it isn't my case and (2) the answer accepted is based on document.currentScript.ownerDocument which demands an old library as far as I know.
*** edited after suggestion to use instead of
<!-- <link rel="import" href="./to-try/my-import-webcomponent.html" /> -->
<script type="module" src="./to-try/my-import-webcomponent.js"></script>
<my-import-webcomponent></my-import-webcomponent>
Nothing changed at all
*** edited after recommended to add "#". No changes at all
A:
If you want to load HTML files with <link rel="import"> then you'll need to load the HTML Imports library before.
<script src="https://raw.githubusercontent.com/webcomponents/html-imports/master/html-imports.min.js"></script>
<link rel="import" href="./to-try/my-import-webcomponent.html">
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Which of the following sample spaces are uniform?
Which of the following sample spaces are uniform?
{land,sea} for a random point on a globe
{odd, even} for a random integer: $z \in \{1,2, \ldots ,100 \}$
{leap year, non-leap year} for a random year before $2019$
{two heads, two tails, one head and one tail} when flipping two fair coins
{distance to origin} for a random point in $\{−3, −1, 1, 3\} \times \{−4, −2, 2, 4\}$
I know that 2 is uniform as they have the same probability.
I like to think that 1 is also uniform as picking a random point on the globe will always have the same probability, the same with the leap year. But they do not have the same probability of occurring so I think they aren't uniform spaces.
I think not 4 as the probability of having two heads/tails varies from one head and one tail. However, a fair coin is uniform.
The last bit confuses me.
A:
Your answers for parts $1$ and $3$ are not correct.
The globe has more water area than land area.
There are also more normal years than leap years.
The last one is uniform because you have four possible results and each one occurs exactly four times.
The possible outcomes are $$\sqrt 5, \sqrt {17}, 5,\sqrt {13}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails: Faster way to perform updates on many records
In our Rails 3.2.13 app (Ruby 2.0.0 + Postgres on Heroku), we are often retreiving a large amount of Order data from an API, and then we need to update or create each order in our database, as well as the associations. A single order creates/updates itself plus approx. 10-15 associcated objects, and we are importing up to 500 orders at a time.
The below code works, but the problem is it's not at all efficient in terms of speed. Creating/updating 500 records takes approx. 1 minute and generates 6500+ db queries!
def add_details(shop, shopify_orders)
shopify_orders.each do |shopify_order|
order = Order.where(:order_id => shopify_order.id.to_s, :shop_id => shop.id).first_or_create
order.update_details(order,shopify_order,shop) #This calls update_attributes for the Order
ShippingLine.add_details(order, shopify_order.shipping_lines)
LineItem.add_details(order, shopify_order.line_items)
Taxline.add_details(order, shopify_order.tax_lines)
Fulfillment.add_details(order, shopify_order.fulfillments)
Note.add_details(order, shopify_order.note_attributes)
Discount.add_details(order, shopify_order.discount_codes)
billing_address = shopify_order.billing_address rescue nil
if !billing_address.blank?
BillingAddress.add_details(order, billing_address)
end
shipping_address = shopify_order.shipping_address rescue nil
if !shipping_address.blank?
ShippingAddress.add_details(order, shipping_address)
end
payment_details = shopify_order.payment_details rescue nil
if !payment_details.blank?
PaymentDetail.add_details(order, payment_details)
end
end
end
def update_details(order,shopify_order,shop)
order.update_attributes(
:order_name => shopify_order.name,
:order_created_at => shopify_order.created_at,
:order_updated_at => shopify_order.updated_at,
:status => Order.get_status(shopify_order),
:payment_status => shopify_order.financial_status,
:fulfillment_status => Order.get_fulfillment_status(shopify_order),
:payment_method => shopify_order.processing_method,
:gateway => shopify_order.gateway,
:currency => shopify_order.currency,
:subtotal_price => shopify_order.subtotal_price,
:subtotal_tax => shopify_order.total_tax,
:total_discounts => shopify_order.total_discounts,
:total_line_items_price => shopify_order.total_line_items_price,
:total_price => shopify_order.total_price,
:total_tax => shopify_order.total_tax,
:total_weight => shopify_order.total_weight,
:taxes_included => shopify_order.taxes_included,
:shop_id => shop.id,
:email => shopify_order.email,
:order_note => shopify_order.note
)
end
So as you can see, we are looping through each order, finding out if it exists or not (then either loading the existing Order or creating the new Order), and then calling update_attributes to pass in the details for the Order. After that we create or update each of the associations. Each associated model looks very similar to this:
class << self
def add_details(order, tax_lines)
tax_lines.each do |shopify_tax_line|
taxline = Taxline.find_or_create_by_order_id(:order_id => order.id)
taxline.update_details(shopify_tax_line)
end
end
end
def update_details(tax_line)
self.update_attributes(:price => tax_line.price, :rate => tax_line.rate, :title => tax_line.title)
end
I've looked into the activerecord-import gem but unfortunately it seems to be more geared towards creation of records in bulk and not update as we also require.
What is the best way that this can be improved for performance?
Many many thanks in advance.
UPDATE:
I came up with this slight improvement, which essentialy removes the call to update the newly created Orders (one query less per order).
def add_details(shop, shopify_orders)
shopify_orders.each do |shopify_order|
values = {:order_id => shopify_order.id.to_s, :shop_id => shop.id,
:order_name => shopify_order.name,
:order_created_at => shopify_order.created_at,
:order_updated_at => shopify_order.updated_at,
:status => Order.get_status(shopify_order),
:payment_status => shopify_order.financial_status,
:fulfillment_status => Order.get_fulfillment_status(shopify_order),
:payment_method => shopify_order.processing_method,
:gateway => shopify_order.gateway,
:currency => shopify_order.currency,
:subtotal_price => shopify_order.subtotal_price,
:subtotal_tax => shopify_order.total_tax,
:total_discounts => shopify_order.total_discounts,
:total_line_items_price => shopify_order.total_line_items_price,
:total_price => shopify_order.total_price,
:total_tax => shopify_order.total_tax,
:total_weight => shopify_order.total_weight,
:taxes_included => shopify_order.taxes_included,
:email => shopify_order.email,
:order_note => shopify_order.note}
get_order = Order.where(:order_id => shopify_order.id.to_s, :shop_id => shop.id)
if get_order.blank?
order = Order.create(values)
else
order = get_order.first
order.update_attributes(values)
end
ShippingLine.add_details(order, shopify_order.shipping_lines)
LineItem.add_details(order, shopify_order.line_items)
Taxline.add_details(order, shopify_order.tax_lines)
Fulfillment.add_details(order, shopify_order.fulfillments)
Note.add_details(order, shopify_order.note_attributes)
Discount.add_details(order, shopify_order.discount_codes)
billing_address = shopify_order.billing_address rescue nil
if !billing_address.blank?
BillingAddress.add_details(order, billing_address)
end
shipping_address = shopify_order.shipping_address rescue nil
if !shipping_address.blank?
ShippingAddress.add_details(order, shipping_address)
end
payment_details = shopify_order.payment_details rescue nil
if !payment_details.blank?
PaymentDetail.add_details(order, payment_details)
end
end
end
and for the associated objects:
class << self
def add_details(order, tax_lines)
tax_lines.each do |shopify_tax_line|
values = {:order_id => order.id,
:price => tax_line.price,
:rate => tax_line.rate,
:title => tax_line.title}
get_taxline = Taxline.where(:order_id => order.id)
if get_taxline.blank?
taxline = Taxline.create(values)
else
taxline = get_taxline.first
taxline.update_attributes(values)
end
end
end
end
Any better suggestions?
A:
Try wrapping your entire code into a single database transaction. Since you're on Heroku it'll be a Postgres bottom-end. With that many update statements, you can probably benefit greatly by transacting them all at once, so your code executes quicker and basically just leaves a "queue" of 6500 statements to run on Postgres side as the server is able to dequeue them. Depending on the bottom end, you might have to transact into smaller chunks - but even transacting 100 at a time (and then close and re-open the transaction) would greatly improve throughput into Pg.
http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
http://www.postgresql.org/docs/9.2/static/sql-set-transaction.html
So before line 2 you'd add something like:
def add_details(shop, shopify_orders)
Order.transaction do
shopify_orders.each do |shopify_order|
And then at the very end of your method add another end:
if !payment_details.blank?
PaymentDetail.add_details(order, payment_details)
end
end //shopify_orders.each..
end //Order.transaction..
end //method
| {
"pile_set_name": "StackExchange"
} |
Q:
Word file compatibility between mac and pc
I'm thinking of buying a mac but I am a bit worried about how mac will handle word files from a windows machine. I have a number of word files in both .doc and .docx format.
Does anyone know if there might be any problems opening these kind of files and, equally important, preserve the formatting and styles on a mac?
I will be using Microsoft word on the mac.
A:
Does anyone know if there might be any problems opening these kind of files?
You won't have any problems. With the pre-installed Pages app on Mac, you can easily open any .docx and .doc files. They will be converted to .pages documents that can't be opened on Windows PCs, but you can easily export any documents from Pages as .docx files that can be opened on PCs.
An easier solution is to use the web-based Google Drive (née Google Docs) that will let you natively open .docx, sync them to your Google account on all your computers, and edit them from anywhere, including your Mac. Or, if you'd prefer the Microsoft-based approach, you can download the Office suite onto your Mac, which works just how it does on PCs.
Can I preserve the formatting and styles on a mac?
I've had no problems preserving format and styling of a .docx document on Mac, using Pages or Google Drive. You will have no problems with a modern program like the ones I've suggested above.
tl;dr: You can totally use Pages, Google Drive, or Word on your Mac to open, edit, and export documents without losing any formatting.
| {
"pile_set_name": "StackExchange"
} |
Q:
how come my delete statement in pdo php crud doen't work
I've have followed a number of tutorials, read many questions in a number of forums about the delete statement and how to use it in pdo php. I have binded parameters, not binded parameters, used prepared functions, defined my variables and indexes. When I click the delete link on the index page the program redirects to the delete page with no errors but it doesn't delete the row from the table. I have made my program small with only two columns to make it as simple as possible. And I have used the exact syntax with each tutorial and example I followed until I'm exhausted over three day period. If anybody can show me what I'm not doing right I'd appreciate it. I'm going to post code from the index page with the link and the delete.php page. In all due respect Fred-ii- I have read all the answers. Truncate doesn't apply to me because I don't want to delete a table, only a row. I don't want to delete all the rows so I use the WHERE clause. Unlike other questions that are similar I am not getting any errors. I rewrote my code to what has been suggested but my delete syntax is still not deleting the row in my index page. My WHERE clause points to name_id which is a Primary key in my database.
<p><td><a href="delete.php?name_id=<?php echo $row['name_id']; ?>">Delete</a></td></p>
And here is the code from the delete page.
require_once 'debase.php';
// Get the name to delete
if(isset($_GET['name_id'])){
$name_id = $_GET['name_id'];
try{
//$dns ="mysql:host=localhost;dbname=$db;charset=$charset";
$conn = new PDO($dsn,$user,$pass);
$stmt = $conn->prepare("DELETE * FROM student WHERE name_id=':name_id'");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->bindValue(':name_id',$name_id, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e){
$error_message = $e->getMessage();
$conn = null;
}
}
A:
Your SQL syntax is incorrect.
You just DELETE FROM ... and not DELETE * FROM...
and remove the quotes round the ':name_id'
| {
"pile_set_name": "StackExchange"
} |
Q:
Smalltalk, newline character
Does anybody know what's the newline delimiter for a string in smalltalk?
I'm trying to split a string in separate lines, but I cannot figure out what's the newline character in smalltalk.
ie.
string := 'smalltalk is
a lot of fun.
ok, it's not.'
I need to split it in:
line1: smalltalk is
line2: a lot of fun.
line3: ok, it's not.
I can split a line based on any letter or symbol, but I can't figure out what the newline delimter is.
OK here is how I'm splitting the string based on commas, but I cannot do it based on a new line.
A:
The newline delimiter is typically the carriage return, i.e., Character cr, or as others mentioned, in a string, String cr. If you wanted to support all standard newline formats, just include both standard delimiters, for example:
string := 'smalltalk is
a lot of fun.'.
string findTokens: String cr, String lf.
Since you now mention you're using VisualWorks, the above won't work unless you have the "squeak-accessing" category loaded (which you probably won't unless you're using Seaside). You could use a regular expression match instead:
'foo
bar' allRegexMatches: '[^', (String with: Character cr), ']+'
| {
"pile_set_name": "StackExchange"
} |
Q:
Excel Compute LTV Lifetime Value
I have a simple spreadsheet of transactions that contains ONE common field: email address.
How could I create a pivot table or something that has a Total of all the transactions under an email address?
(some contacts have 3 or 4 transactions all with the same email address.)
the two columns are:
email | price
I'd like the output to be email | Total (sum of all transactions under a given email)
Thanks!
A:
Insert a pivot table and select your range.
Add email to rows and add price to values.
| {
"pile_set_name": "StackExchange"
} |
Q:
Вывод изображения из файла на PHP
Есть изображение: *.png, нужно вывести изображение с помощью PHP...
P.s. Не echo("<img src="*.png">");, А именно изображение, что-бы как-бы этот php файл как-бы был изображением...
A:
Рабочий вариант:
<?php
$image_url = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png';
$image_info = getimagesize($image_url);
header('Content-type: ' . $image_info['mime']);
readfile($image_url);
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails params not picking up Dynamic row values on GUI to controller
I am trying to pass values from GUI to rails controller where my GUI consists of table in which rows are generated dynamically by Javascript. I need two static rows and the rest should be generated on customer's demand.
Issue is only the values in static rows are sent in params, Dynamically generated row values are not sent.
Front end Code:
<%= render 'shared/page_title', title: "Order Details" %>
<br>
<table id="tabledata">
<thead>
<th>Item Name</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Tax</th>
<th>Discount</th>
<th>Item Total Price</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<%= form_for @order do |f| %>
<%= f.label :ordertype %>
<%= f.text_field :ordertype %>
<%= f.label :totalprice %>
<%= f.text_field :totalprice %>
<%= f.label :paymentmethod %>
<%= f.text_field :paymentmethod %>
<br>
<tr>
<td><input name="order[order_placed][][itemname]" type="text" /></td>
<td><input name="order[order_placed][][quantity]" type="text" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" /></td>
<td><input name="order[order_placed][][tax]" type="text" /></td>
<td><input name="order[order_placed][][discount]" type="text" /></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" /></td>
</tr>
<tr>
<td><input name="order[order_placed][][itemname]" type="text" /></td>
<td><input name="order[order_placed][][quantity]" type="text" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" /></td>
<td><input name="order[order_placed][][tax]" type="text" /></td>
<td><input name="order[order_placed][][discount]" type="text" /></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" /></td>
</tr>
</tbody>
</table>
<label id="ActionAddRow">Add Row</label>
<%= f.submit %>
<% end %>
JavaScript
$(function () {
var addInputRow = function () {
var tr = document.createElement("tr");
function callback(attribname){
nameAttributitemname =
"order[order_placed][][" + attribname + "]";
//create input for itemname, set it's type, id and name attribute
var inputitemname = document.createElement("INPUT");
inputitemname.setAttribute("type", "text");
inputitemname.setAttribute("name", nameAttributitemname);
//and append it to <td> element and then <tr>
var td = document.createElement("td");
td.appendChild(inputitemname);
tr.appendChild(td);
}
callback("itemname");
callback("quantity");
callback("unitprice");
callback("tax");
callback("discount");
callback("itemtotalprice");
document.getElementById("template").appendChild(tr);
};
var addAll = function (){
addInputRow();
};
$('#ActionAddRow').on('click', addAll);
});
Server side:
Started POST "/orders" for 127.0.0.1 at 2018-01-07 12:57:14 +0530
Processing by OrdersController#create as HTML
Parameters: {"order"=>{"ordertype"=>"", "totalprice"=>"", "paymentmethod"=>"", "order_placed"=>[{"itemname"=>"11", "quantity"=>"", "unitprice"=>"", "tax"=>"", "discount"=>"", "itemtotalprice"=>""}, {"itemname"=>"22", "quantity"=>"", "unitprice"=>"", "tax"=>"", "discount"=>"", "itemtotalprice"=>""}]}, "utf8"=>"Γ£ô", "authenticity_token"=>"/YfKgSt/lgDgC2L1Wa0fDdBjY+zTfEBcblp1rB/St89jsmU52pDnbTCwACyy+qiuZhxyVil63FMlOiq2YEUBhA==", "addresses"=>[{"line1"=>"", "line2"=>"", "city"=>""}, {"line1"=>"", "line2"=>"", "city"=>""}], "commit"=>"Create Order"}
Customer Load (1.0ms) SELECT "customers".* FROM "customers" ORDER BY "customers"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.0ms) BEGIN
SQL (2.0ms) INSERT INTO "orders" ("ordertype", "order_placed", "paymentmethod", "created_at", "updated_at", "customer_id") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["ordertype", ""], ["order_placed", "\"---\\n- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\\n itemname: '11'\\n quantity: ''\\n unitprice: ''\\n tax: ''\\n discount: ''\\n itemtotalprice: ''\\n- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\\n itemname: '22'\\n quantity: ''\\n unitprice: ''\\n tax: ''\\n discount: ''\\n itemtotalprice: ''\\n\""], ["paymentmethod", ""], ["created_at", "2018-01-07 07:27:14.631269"], ["updated_at", "2018-01-07 07:27:14.631269"], ["customer_id", 1]]
(1.0ms) COMMIT
GUI screenshot passing three rows.
A:
This is because when document.getElementById("template").appendChild(tr); is called, all those new tr and the containing inputs are appended under the <tbody id="template"></tbody>, causing the resulting HTML structure becoming something like this:
<tbody id="template">
<form ...>
<!-- Static rendered rows -->
<tr>
...
<input ... />
...
</tr>
</form>
<!-- Dynamically generated rows -->
<tr>
...
<input ... />
...
</tr>
</tbody>
And a reasonable behavior, those inputs outside the <form> tag will not be sent along with the submitted form. You can move the <%= form_for @order do |f| %> line, which generates the <form> tag, outside of your <tbody id="template">, so that the dynamically appended inputs will also be inside the form.
More things to be noted:
It seems you had mistakenly wrote an unmatched pair <%= form_for @order do |f| %> and <% end %> tags, which you placed the start tag inside tbody and the ending tag out of tbody:
...
<tbody>
<form>
...
</tbody>
</form>
...
This is invalid HTML and the browser might assume that you mean:
...
<tbody>
<form>
...
</form>
</tbody>
...
Which causes some unexpected behaviors. The start tag and the end tag should always be in the same level on an HTML document.
And some other issues:
For semantic correctness, you should consider using button instead of label for your ActionAddRow button, indicating that is something that users can click on.
The label and inputs should be placed outside the tbody and table since it isn't a part of the table.
Here is a nicely structured sample of your .html.erb code:
<%= render 'shared/page_title', title: "Order Details" %>
<br>
<%= form_for @order do |f| %>
<%= f.label :ordertype %>
<%= f.text_field :ordertype %>
<%= f.label :totalprice %>
<%= f.text_field :totalprice %>
<%= f.label :paymentmethod %>
<%= f.text_field :paymentmethod %>
<br>
<table id="tabledata">
<thead>
<th>Item Name</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Tax</th>
<th>Discount</th>
<th>Item Total Price</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<tr>
<td><input name="order[order_placed][][itemname]" type="text" /></td>
<td><input name="order[order_placed][][quantity]" type="text" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" /></td>
<td><input name="order[order_placed][][tax]" type="text" /></td>
<td><input name="order[order_placed][][discount]" type="text" /></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" /></td>
</tr>
<tr>
<td><input name="order[order_placed][][itemname]" type="text" /></td>
<td><input name="order[order_placed][][quantity]" type="text" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" /></td>
<td><input name="order[order_placed][][tax]" type="text" /></td>
<td><input name="order[order_placed][][discount]" type="text" /></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" /></td>
</tr>
</tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<%= f.submit %>
<% end %>
| {
"pile_set_name": "StackExchange"
} |
Q:
Refresh datagrid in UserControl
I learning about c# and wpf and i dont know how to deal with something like this:
I have 2 windows (one with usercontrol) and 1 class.
Window1
List<Reservation> reservationList = new List<Reservation>();
private void ToggleButton_Checked(object sender, RoutedEventArgs e)
{
var button = (ToggleButton)sender;
var item = button.DataContext as Hall;
Reservation nres = new Reservation();
nres.movieName = item.moviename;
nres.seat = item.number;
nres.rowID = item.row;
reservationList.Add(nres);
}
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
}
Class contains
class Reservation
{
public string movieName { get; set; }
public int seat { get; set; }
public string rowID { get; set; }
}
Window2 have UserControl with datagrid.
Could you give me some advices how to bind window2 usercontrol datagrid to list made in window1, and when i hit ADD button in window1 it refresh that usercontrol and display actual positions in window1 list.
I hope for your understanding and thank you in advance!
A:
I don't see why you need two windows, so I'm going to assume you can get by with one window. You don't say so, but I'm assuming that a user will input the movie name, seat number, and row Id into text boxes on the window.
To answer your first question, all you have to do to bind a list to a DataGrid is assign the list to the DataGrid ItemsSource property. For example (See the MainWindow method below):
dataGridReservations.ItemsSource = reservations.List;
I'm new to WPF, but is seems that the default behavior for a DataGrid is to create column names from the names of the variables in the list.
You want to implement your list of reservations as an ObservableCollection because an ObservableCollection automatically propagates changes to the datagrid when an item is added, deleted, or modified in the bound list. See How do I bind a List to a WPF DataGrid?
For your second question: Use the Add button click event to add movie name, seat number, and row Id from the text boxes to a new item in the list. Again, when the list is updated, the DataGrid is updated due to the action of the ObservableCollection
Here is the code that allows a user to input a movie name, seat number, and row id, and then click the Add button to add it to the DataGrid. More code is needed to allow the user to edit or delete an item in the grid.
XAML follows the code
See screen shot at the bottom for a demo
public partial class MainWindow : Window
{
Reservations reservations;
public MainWindow()
{
InitializeComponent();
reservations = new Reservations();
dataGridReservations.ItemsSource = reservations.List;
}
public class Reservations
{
public class Reservation
{
private string _movieName;
private string _seat;
private string _rowID;
public Reservation(string movieName, string seat, string rowID)
{
MovieName = movieName;
Seat = seat;
RowID = rowID;
}
public string MovieName { get => _movieName; set => _movieName = value; }
public string Seat { get => _seat; set => _seat = value; }
public string RowID { get => _rowID; set => _rowID = value; }
}
private ObservableCollection<Reservation> _list;
public ObservableCollection<Reservation> List { get => _list; set => _list = value; }
public Reservations()
{
List = new ObservableCollection<Reservation>();
}
public void AddReservationToList(string MovieName, string SeatNumber, string RowId)
{
Reservation reservation = new Reservation(MovieName, SeatNumber, RowId);
List.Add(reservation);
}
}
private void ButtonAddReservationToList(object sender, RoutedEventArgs e)
{
reservations.AddReservationToList(textBoxMovieName.Text, textBoxSeatNumber.Text, textBoxRowId.Text);
textBoxMovieName.Text = "";
textBoxSeatNumber.Text = "";
textBoxRowId.Text = "";
}
}
MainWindow XAML
<Window x:Class="SO_Refresh_datagrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SO_Refresh_datagrid"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Add" HorizontalAlignment="Left" Height="30" Margin="83,169,0,0" VerticalAlignment="Top" Width="64" Click="ButtonAddReservationToList"/>
<TextBox x:Name="textBoxMovieName" HorizontalAlignment="Left" Height="31" Margin="140,18,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="103"/>
<TextBox x:Name="textBoxSeatNumber" HorizontalAlignment="Left" Height="24" Margin="140,61,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="103"/>
<TextBox x:Name="textBoxRowId" HorizontalAlignment="Left" Height="24" Margin="140,100,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="103"/>
<Label Content="Movie Name" HorizontalAlignment="Left" Height="31" Margin="36,18,0,0" VerticalAlignment="Top" Width="71"/>
<Label Content="Seat Number" HorizontalAlignment="Left" Height="31" Margin="36,61,0,0" VerticalAlignment="Top" Width="90"/>
<Label Content="Row Id" HorizontalAlignment="Left" Height="31" Margin="36,100,0,0" VerticalAlignment="Top" Width="71"/>
<DataGrid x:Name="dataGridReservations" HorizontalAlignment="Left" Height="284" Margin="277,18,0,0" VerticalAlignment="Top" Width="209"/>
</Grid>
</Window>
Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Where do these margins come from?
I'm writing a proprietary PrintService and I encounter some problems on the received PDF file generated by the Android PrintManager.
I suppose some print attributes are not set correctly.
Here is the simple code I use to print something. It's my test application:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = new WebView(this);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// I also set padding to 0 in case....
webView.setPadding(0, 0, 0, 0);
// So I tried to set html margin/padding to 0 but it doesn't change the print preview
String summary = "<html><body style=\"margin: 0; padding: 0; width:100%; height: 100%;\">" +
"-------------------------------------<br/>" +
"I'm just printing something!<br/>" +
"-------------------------------------<br/>" +
"</body></html>";
webView.loadData(summary, "text/html; charset=utf-8", "utf-8");
}
public void createWebPrintJob(View view) {
PrintManager printManager = (PrintManager) this
.getSystemService(Context.PRINT_SERVICE);
if (printManager != null) {
String jobName = getString(R.string.app_name);
PrintJob job = null;
PrintDocumentAdapter printAdapter =
webView.createPrintDocumentAdapter(jobName);
if ((job = (printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build()))) != null) {
Toast.makeText(this, "Job succesfully created", Toast.LENGTH_SHORT).show();
}
}
}
Now on the PrintService side, below is how I initialize the printer capabilities:
@Override
public void onStartPrinterStateTracking(@NonNull PrinterId printerId) {
Log.d(TAG, "onStartPrinterStateTracking");
PrinterInfo printer = findPrinterInfo(printerId);
if (printer != null) {
PrintAttributes.MediaSize rollSize = new PrintAttributes.MediaSize("Roll58mm", "Roll58mm", 1892, 5676);
PrintAttributes.Margins rollMargins = new PrintAttributes.Margins(0, 0, 0, 0);
PrinterCapabilitiesInfo capabilities = new PrinterCapabilitiesInfo.Builder(printerId)
.addMediaSize(rollSize, true)
.setColorModes(PrintAttributes.COLOR_MODE_MONOCHROME, PrintAttributes.COLOR_MODE_MONOCHROME)
.addResolution(new PrintAttributes.Resolution("200dpi", "paperRoll", 203,203), true)
.setMinMargins(rollMargins)
.build();
printer = new PrinterInfo.Builder(printer)
.setCapabilities(capabilities)
.build();
List<PrinterInfo> printers = new Vector<>();
printers.add(printer);
addPrinters(printers);
} else {
Log.e(TAG, "Unable to find requested printer !");
}
}
Here is the printing preview and so I don't understand why I get margins or padding, around my text whereas I specified 0 for all.
So why do I see margins here as I specified 0 for all?
-EDIT-
I've updated my onCreate method according to some posts talking about similar problem bu without success!
A:
I solved it by adding css styles to HTML.
<style type="text/css" media="print">
@page
{
size: auto; /* auto is the initial value */
margin: 0mm; /* this affects the margin in the printer settings */
}
html
{
background-color: #FFFFFF;
margin: 0px; /* this affects the margin on the html before sending to printer */
}
body
{
margin: 0mm; /* margin you want for the content */
}
</style>
| {
"pile_set_name": "StackExchange"
} |
Q:
Difficulty mantaining value of a variable during Recursion
I am trying to count inversions in an array using divide and conquer methodology.However, I'm unable to mantain the Total of inversions .After the program is done it returns the number of inversions in the last step and not the sum of all the inversions done before it.
def mergesort(A):
if len(A) <2:
return A
mid = len(A)//2
lefthalf = A[:mid]
righthalf = A[mid:]
mergesort(lefthalf)
mergesort(righthalf)
Total= merge(lefthalf,righthalf,A)
return Total
def merge(left,right,A):
Total = 0
i,j,k = 0,0,0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
A[k] = left[i]
i+=1
k+=1
else:
A[k] = right[j]
j+=1
k+=1
Total+= len(left[i:])
while i < len(left):
A[k] = left[i]
i+=1
k+=1
while j < len(right):
A[k] = right[j]
j+=1
k+=1
return Total
print (mergesort([1,5,3,2,4]))
How can I mantain the Total ?
Please suggest neccesary changes to code with explanation.
Thanks.
A:
For completeness, here is an answer so this question doesn't remain in the unanswered section.
Your total needs to keep track of the number of inversions not just in the current stack frame, but also the stack frame of future recursive calls. To this end, either you need to add the return value of the recursive calls to Total, or declare Total as a global variable that will be shared amongst each recursive call as opposed to keeping a local variable as you have now.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to spread the input array into arguments?
So Promise.all passes an array as a value into the function, I would much rather it pass the array values as arguments.
Assume I have this function:
function printData(a,b,c){
console.log(a,b,c)
}
I would like
Promise.all([1,2,3]).then(printData)
>> [1,2,3] undefined undefined
To print this instead
>> 1 2 3
Is there a better way of doing this:
Promise.all([1,2,3,4]).then(function(values){printData.apply(null, values)})
using the spread operator?
I also tried
Promise.all([1,2,3]).then(printData.apply)
But it returns an error
A:
One way using ES 6 Destructuring
function printData(a,b,c){
console.log(a,b,c)
}
Promise.all([1,2,3]).then( data => {var [a,b,c] = data;
printData(a,b,c);});
Using ES 6 Spread Syntax
function printData(a,b,c){
console.log(a,b,c)
}
Promise.all([1,2,3]).then(data => printData(...data))
A:
Trying to use the spread operator technically has you nesting functions, which works, but there is another way
Promise.all([1,2,3]).then(printData.apply)
Doesn't work because this is equal to:
printData.apply.call(undefined, [1,2,3])
which returns the same error
>>Uncaught TypeError: Function.prototype.apply was called on undefined,
which is a undefined and not a function
Promise passes this in to call and it loses track of what it should be.
What you want is:
test.apply.call(test,[null,1,2,3])
which equals:
test.apply(null,[1,2,3])
which equals
test(1,2,3)
because you don't have control over Promise using call, use bind to determine the arguments
printData.apply.bind(printData, null)
which when called equals
printData.apply.bind(printData, null).call(undefined, [1,2,3])
>> 1 2 3
so Finally:
Promise.all([1,2,3]).then(printData.apply.bind(printData,null))
>> 1 2 3
Here's a related question about combining apply and call
Why can I not call a function.apply?
| {
"pile_set_name": "StackExchange"
} |
Q:
Matrix calculus - computing the Hessian of a vector-Matrix equation.
Let $\vec{b}=\langle b_1,\dots,b_n\rangle ^T$ be an n-dimensional vector of coefficients. Let $\vec{x}_1,\dots,\vec{x}_n$ be $n$ $p$-dimensional vectors. Let $G(\vec{b})=\log\det\left( \sum_{i=1}^n b_i \vec{x}_i\vec{x}_i^T\right)$.
Let $A=\sum_{i=1}^n b_i \vec{x}_i\vec{x}_i^T$. If one wants to compute the $i$-th component of the gradient, we get
\begin{eqnarray}
\nabla_i G(\vec{b}) &=& \text{Tr}\left(\partial_i A \right) \\
&=& \text{Tr}\left( A^{-1} \vec{x}_i\vec{x}_i^T \right) \\
&=& \text{Tr}\left(\vec{x}_i^T A^{-1} \vec{x}_i \right) \\
&=& x_i^T A^{-1} x_i
\end{eqnarray}
I am filling in the details so far of this paper (page 19, before equation (33)). So far I agree with their calculation. However, I do not understand their calculation of the line (33) and (34) in which they calculate the Hessian.
They claim that
$$
\nabla^2_{ij} (G(\vec{b})) = -(\vec{x}_i^T A^{-1}\vec{x}_j)^2. \tag1
$$
I get something different. Using the Matrix Cookbook (equation (61)), I see that
\begin{eqnarray}
\partial_j(\vec{x}_i^T A^{-1} \vec{x}_i) &=& -A^{-1}\vec{x}_i\vec{x}_i^T A^{-1}\cdot\partial_i(A) \tag2\\
&=& -A^{-1}\vec{x}_i\vec{x}_i^T A^{-1} \vec{x}_j\vec{x}_j^T,
\end{eqnarray}
which is a matrix and not a scalar!
I know I must be making a mistake somewhere. I am still not quite comfortable with matrix calculus.
Can someone help me figure out where I'm going wrong?
A:
The derivation in (2) is wrong. You apply the formula (61) from the Matrix Cookbook, but this formula is for the derivative of the quadratic form with respect to the whole matrix. That's why it is a matrix. You need to calculate the derivative of $G_i'$ with respect of the variable $b_j$ only, so you are rather to use the equation (59) in the Cookbook. Here how it goes
$$
G_{ij}''=[G_i']_j'=\frac{\partial x_i^TA^{-1}x_i}{\partial b_j}=
x_i^T\frac{\partial A^{-1}}{\partial b_j}x_i\stackrel{\text{Eq.(59)}}{=}
x_i^T\Bigl(-A^{-1}\underbrace{\frac{\partial A}{\partial b_j}}_{x_jx_j^T}A^{-1}\Bigr)x_i=\\=-x_i^TA^{-1}x_j\cdot x_j^TA^{-1}x_i
$$
which is exactly their expression (1).
UPDATE explaining the formula (61) in the Matrix Cookbook.
In one dimensional calculus we have $f\colon\mathbb{R}\to\mathbb{R}$ and differentiating according to
$$
f(x+h)-f(x)=\underbrace{f'(x)\cdot h}_{\partial_x f}+o(|h|).\tag{*}
$$
When $x$ becomes a vector and $f\colon\mathbb{R}^n\to\mathbb{R}$, the derivative becomes a vector of partial derivatives (gradient) which normally has the same size as the vector $x$ so that on the place for $x_k$ one gets the partial derivative $\frac{\partial f}{\partial x_k}$
$$
x=\left[\matrix{x_1\\x_2\\\vdots\\x_n}\right]\qquad\Rightarrow\qquad\frac{\partial f}{\partial x}=
\left[\matrix{\frac{\partial f}{\partial x_1}\\\frac{\partial f}{\partial x_2}\\\vdots\\\frac{\partial f}{\partial x_n}}\right].
$$
The differential in (*) is then no longer a multiplication, it becomes the scalar product, i.e. the sum of pointwise multiplications between the gradient and the variable $h$
$$
f(x+h)-f(h)=\langle\frac{\partial f}{\partial x},h\rangle+o(\|h\|).
$$
When one has a function $f\colon\mathbb{R}^{m\times n}\to \mathbb{R}$, for example, $f(X)=a^TX^{-1}b$ as in (61), it is also convenient to organize the matrix of partial derivatives in the same way that on the position for $x_{ij}$ we get $\frac{\partial f}{\partial x_{ij}}$, and this matrix is denoted by $\frac{\partial f}{\partial X}$, however, the differential is not $\partial f=\frac{\partial f}{\partial X}\partial X$ as you wrote in (2), but as in the vector case the scalar product, i.e.
$$
\partial f=\langle\frac{\partial f}{\partial x},\partial X\rangle=
\text{tr}\Bigl(\biggl(\frac{\partial f}{\partial x}\biggr)^T\partial X\Bigr).
$$
So the corrected version of (2) would be
$$
\text{tr}(-A^{-1}x_ix_i^TA^{-1}x_jx_j^T)=-(x_j^TA^{-1}x_i)^2.
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Inequality for the gradient of a power of absolute value
Let $U \subset \mathbb{R}^2$ be open, and let $f : U \to \mathbb{C}$ be a smooth complex-valued function which does not vanish anywhere on $U$. Let $r > 0$ be a real constant.
Does the inequality $$\left| \nabla (|f|^r) \right| \le r |f|^{r-1} |\nabla f|$$
hold pointwise? Is there a nice elegant proof?
For $f > 0$ the inequality is an equality, since $\nabla (f^r) = r f^{r-1} \nabla f$ by the chain rule. If we identify $\mathbb{R}^2$ with $\mathbb{C}$ and take $f$ holomorphic, it is not hard to show that $\left| \nabla (|f|^r) \right| = \frac{1}{\sqrt{2}} r |f|^{r-1} |\nabla f|$ so the inequality can be strict.
For the general case, I am getting bogged down in real and imaginary parts - there must be a better way.
If there is a proof that works for $\mathbb{R}^d$ instead of $\mathbb{R}^2$ that is even better.
Notation, as requested: $\nabla f : U \to \mathbb{C}^2$ is, as usual, the function $\nabla f = ( \partial_x f, \partial_y f)$. The partial derivatives $\partial_x f, \partial_y f$ are defined by taking the partial derivatives of the real and imaginary parts of $f$ separately. So if $f = u+iv$ where $u,v : U \to \mathbb{R}$ are the real and imaginary parts, we have $\partial_x f = \partial_x u + i \partial_x v$, etc. In particular, we have
$$|\nabla f| = \sqrt{(\partial_x u)^2 + (\partial_y u)^2 + (\partial_x v)^2 + (\partial_y v)^2}.$$
A:
Write $|f|^r$ as $(f \bar f)^{r/2}$. Then by the chain rule and the product rule (valid for complex-valued functions),
$$\begin{align*}
\partial_x |f|^r &= \partial_x (f \bar f)^{r/2} \\
&= \frac{r}{2} (f \bar f)^{\frac{r}{2}-1}(\bar{f} \partial_x f + f \partial_x \bar f) \\
&= \frac{r}{2} |f|^{r-2} (\bar f \partial_x f + f \overline{\partial_x f} ) \\
&= r |f|^{r-2} \operatorname{Re}(f \partial_x f).\end{align*}$$
Hence
$$\begin{align*} \left| \left(\partial_x |f|^r\right) \right| \le r |f|^{r-2} |f \partial_x f| = r |f|^{r-1} |\partial_x f|.\end{align*}$$
Doing the same for $\partial_y$ and summing the squares gives
$$\begin{align*}|\nabla (|f|^r)|^2 &= \left| \left(\partial_x |f|^r\right) \right|^2 + \left| \left(\partial_y |f|^r\right) \right|^2 \\ &\le r^2 |f|^{2r-2} (|\partial_x f|^2 + |\partial_y f|^2)\\ &= r^2 |f|^{2r-2} |\nabla f|^2 \end{align*}$$
which is the square of the desired inequality. This immediately generalizes to any number of variables.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I reverse an IRA contribution and re-make it later on?
Early this year, I made $5,000 in prior-year contributions to a Roth IRA. (I didn't make any IRA contributions last year.)
Some time later, I withdrew $3,000 from the IRA, intending to take advantage of the provision described in the following paragraph of IRS Publication 590-B:
Withdrawals of contributions by due date. If you withdraw contributions (including any net earnings on the contributions) by the due date of your return for the year in which you made the contribution, the contributions are treated as if you never made them. If you have an extension of time to file your return, you can withdraw the contributions and earnings by the extended due date. The withdrawal of contributions is tax free, but you must include the earnings on the contributions in income for the year in which you made the contributions.
I figured that by the above, $3,000 of my contributions would be "treated as if you never made them", meaning I would be able to contribute another $4,000 in order to reach the $6,000 contribution limit.
However, after I contributed another $1,000, the IRA custodian (TD Ameritrade) informed me that I have reached the contribution limit and I can no longer make regular contributions for the year 2019. (They did say I could put the money back in as a 60-day rollover, but I don't think I want to do that.)
Am I, in fact, permitted to make another $3,000 in regular contributions for the year 2019, or is it time for me to move on to the next option?
A:
If you request a return of contribution, they'll return the requested contribution amount along with any earnings associated with that amount. This basically is a reversal of the contribution and allows you to re-contribute for same year to get back to max contribution.
If you just request a normal distribution they will just distribute that amount and not the earnings associated and you will not be able to contribute more. Since they are claiming you can't contribute more this is probably what happened, but it's worth following up with them to see if they can walk it back and re-process as you intended.
| {
"pile_set_name": "StackExchange"
} |
Q:
List of files committed as part of merge from master in git
I'm working on a branch and recently I did a merge from master.
I want to know which files were modified as part of that commit? Any handy commands in GIT?
I do have the commit hash and when I'm trying to do
git diff-tree --no-commit-id --name-only -r f313111ecdbd9e8292ef1db51ea31d47c9a93202 it's returning nothing/
Thanks.
A:
First retrieve the SHA1 values of your last two commits using the following command:
git log -n 2
The top commit would be the merge commit, and second would be the commit before the merge commit. Then run the following command:
git diff --name-only <SHA1 value of merge commit> <SHA1 value of previous commit>
| {
"pile_set_name": "StackExchange"
} |
Q:
Would chocolate liqueur cherries be allowed through Australian customs?
If the liqueur cherries have a stem and seeds will they be allowed into Australia through Australian customs?
A:
Probably yes, but you must declare it.
Commercially processed and packaged foods that have low risk of carrying pests or pathogens can generally be brought into Australia.
However, if in doubt, you should declare it. The worst thing that can happen is that it will be confiscated. If you do not declare and get caught, you may be subject to heavy penalties, including an appearance on a TV show.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# callback requires object to be referenced as UInt32?
I need to be able to pass a context object when i register a call back using the following method, which is linked to a C++ DLL file so cant change the method parameters. The callback returns this as one of the arguments when the callback method is executed.
public static void RegisterCallback(UInt32 instance, CALLBACK callbackFunction, UInt32 context)
The last argument is the only one I'm having trouble with. I'm assuming that its meant to be the memory address (or a reference) of the object.
The C++ code has this argument as void*
Any ideas?
A:
This is very common in a C-style api that permits registering a callback. It plays the exact same role as, say, IAsyncResult.AsyncState in managed code for example. The callback gets the value back, it can use it for any purpose it likes. Could be an index in an array of objects for example. Could be a state variable. In the case of C++, it very commonly is the this pointer of the C++ object. Very handy, permits calling an instance function of the C++ object. Anything goes.
Do note that it is pretty unlikely that you need it. First hint that you don't is that you just don't know what to use it for. And that's pretty likely in C# because you already have context. The delegate you use for the callbackFunction argument already captures the this object reference. So any state you need in the callback method can already be provided by fields of the class. Just like C++, minus the extra call.
So don't worry about it, pass 0. Or really, fix the declaration, the parameter should be IntPtr, pass IntPtr.Zero. Probably also what you should do for the instance argument, it quacks like a "handle". A pointer under the hood.
And be careful with the callbackFunction argument, you need to make sure that the garbage collector does not destroy the delegate object. It does not know that the native code is using it. You have to store it in a static variable or call GCHandle.Alloc() so it is always referenced.
| {
"pile_set_name": "StackExchange"
} |
Q:
Import/convert list of space separated numbers to list of arrays in Matlab
I'm new to Matlab and I want to convert a column with space separated numbers (source is an Excel file) to a list of arrays.
In a first step I want to create a list of arrays like this:
Then I want to transpose the list like this:
Whats the correct command for this conversion?
I know it's a simple question, but I couldn't find a similar one.
A:
First use xlsread to read in the raw text. The text will be read in as a cell array where each row of text is placed in a cell. Once you do this, it's a matter of splitting up the strings by spaces to create an additional cell array of cells per row, then inputting these cells into a function that creates an array of numbers. You can use cellfun combined with strsplit and str2double. Assuming your Excel file is called list.xls, do something like this:
[~,~,RAW] = xlsread('list.xls');
list = cellfun(@str2double, cellfun(@strsplit, RAW, 'uni', 0), 'uni', 0).';
list contains the desired output. I've also transposed the result as this is what you desire. I created an Excel file that's in the same fashion as how you've mentioned in your post. This is what I get when I run the code. First I'll show what list looks like, then we'll examine what the actual contents are:
>> list
list =
[1x4 double] [1x5 double] [1x6 double]
>> celldisp(list)
list{1} =
5405 5414 5420 9999
list{2} =
5405 5414 5430 5341 9999
list{3} =
5405 5419 5419 5419 5412 9999
Here's also what the MATLAB Variable Editor looks like:
| {
"pile_set_name": "StackExchange"
} |
Q:
How to efficiently store DOM elements in association with their corresponding objects?
I am delegating a key input event from the document onto the several textareas on the page. Because the operations I need to perform on the key input are complex, repetitive, and tied to the text contents of that textarea - I find it better to cache that information in a TextareaState object (something like {wasChanged: true, penultimateTextContents: "string", etc.}) for each <textarea>. It would also make sense to store this object permanently, rather than recomputing it every time an input event was fired (recomputing would erase the important previous results anyway).
At first I thought of using a key-value pair object, but DOM elements cannot be substituted as object keys. I could instead try to generate a unique CSS selector for each DOM element and then use that selector as the object key, but this approach seems very expensive.
My third and final approach was to use two arrays (var textareaElements = [], TextareaStateObjects = []) and then every time an input handler was fired, I could do TextareaStateObjects[textareaElements.indexOf(event.target)] to get the corresponding cached object. However, that still seems pretty expensive, considering that .indexOf runs at every input event, and is going to be very costly for larger array lengths.
Is there a more efficient solution here?
A:
Is there a more efficient solution here?
Yes, either of your first two solutions. :-) Details:
At first I thought of using a key-value pair object, but DOM elements cannot be substituted as object keys.
That's true, but they can be Map object keys. They can even be WeakMap object keys if you need to prevent the Map from keeping the element in memory.
You do need to target environments that have Map and WeakMap (all current major ones do), although there are some really powerful polyfills out there doing cool things to emulate Map behavior in a clever, well-performing way.
Example:
// See https://stackoverflow.com/questions/46929157/foreach-on-queryselectorall-not-working-in-recent-microsoft-browsers/46929259#46929259
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
// Yes, there's really no need for `Object.defineProperty` here
NodeList.prototype.forEach = Array.prototype.forEach;
}
const map = new WeakMap();
document.querySelectorAll("textarea").forEach((element, index) => {
++index;
map.set(element, {name: "TextArea #" + index});
});
document.addEventListener("click", event => {
const entry = map.get(event.target);
if (entry) {
console.log("The name for the textarea you clicked is " + entry.name);
}
});
<div>Click in each of these text areas:</div>
<textarea>one</textarea>
<textarea>two</textarea>
I could instead try to generate a unique CSS selector for each DOM element and then use that selector as the object key, but this approach seems very expensive.
It isn't if you use id for that: Give yourself a unique prefix and then following it with an ever-increasing number. (And if you need to go from the ID to the element, getElementById is blindingly fast.)
Example:
// See https://stackoverflow.com/questions/46929157/foreach-on-queryselectorall-not-working-in-recent-microsoft-browsers/46929259#46929259
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
// Yes, there's really no need for `Object.defineProperty` here
NodeList.prototype.forEach = Array.prototype.forEach;
}
let nextIdNum = 1;
const pseudoMap = Object.create(null);
document.querySelectorAll("textarea").forEach((element, index) => {
if (!element.id) {
element.id = "__x_" + nextIdNum++;
}
++index;
pseudoMap[element.id] = {name: "TextArea #" + index};
});
document.addEventListener("click", event => {
const entry = pseudoMap[event.target.id];
if (entry) {
console.log("The name for the textarea you clicked is " + entry.name);
}
});
<div>Click in each of these text areas:</div>
<textarea>one</textarea>
<textarea>two</textarea>
If you use id for other purposes, it can be a data-* attribute instead. (And if you need to go from the data-* attribute value to the element, querySelector on a data-* attribute isn't all that expensive.)
Example:
// See https://stackoverflow.com/questions/46929157/foreach-on-queryselectorall-not-working-in-recent-microsoft-browsers/46929259#46929259
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
// Yes, there's really no need for `Object.defineProperty` here
NodeList.prototype.forEach = Array.prototype.forEach;
}
let nextIdNum = 1;
const pseudoMap = Object.create(null);
document.querySelectorAll("textarea").forEach((element, index) => {
const id = "__x_" + nextIdNum++;
element.setAttribute("data-id", id);
pseudoMap[id] = {name: "TextArea #" + index};
});
document.addEventListener("click", event => {
const entry = pseudoMap[event.target.getAttribute("data-id")];
if (entry) {
console.log("The name for the textarea you clicked is " + entry.name);
}
});
<div>Click in each of these text areas:</div>
<textarea>one</textarea>
<textarea>two</textarea>
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Warlock with the Polearm Master and War Caster Feats cast Eldritch Blast as an Opportunity Attack while wearing a shield, RAW?
I realize there is the RAI note out there that indicates Polearm Master's opportunity attack is only intended to work with the polearm that you're wielding, but some DMs accept the RAW interpretation which allows casting Eldritch Blast as an opportunity attack if the player has both Polearm Master and War Caster feats, AND is wielding a weapon specified in PAM's description.
Polearms are Two-Handed weapons, but that only applies when attacking with it from what I understand. Does the RAW interpretation of this combo also allow wearing a shield + one handing the polearm at the cost of being unable to attack with said polearm?
A:
RAW: Yes, that would work!
You can wield a two-handed weapon in addition to a shield.
Two-Handed. This weapon requires two hands when you attack with it
(PHB p.147, emphasis mine)
So you can wield a two-handed weapon correctly, but cannot attack with it, if your other hand is occupied.
Shields. A shield [...] is carried in one hand.
(PHB p.133, emphasis mine)
So, you can carry the shield in one hand, while holding your weapon in the other hand.
The opportunity attack would be triggered
By your definition, you are wielding a weapon specified in the Polearm Master feat. So you would get the opportunity attack, which you cannot perform (due to the shield), but replace by a spell (due to War Caster).
You could cast eldritch blast
You can cast a spell as an OA using the War Caster feat, you have to fulfill the components of the spell. For Eldritch Blast those are verbal (no problem) and somatic, which "you can perform even when you have weapons or a shield in one or both hands" (PHB, p.170, War Caster feat). You would also have to target all individual beams at the creature, which triggered the AoO!
So, all conditions required for this technique are met, but as you said, you wouldn't be able to use your two-handed weapon!
Unless your two-handed weapon gives you a relevant bonus I would suggest using a Quarterstaff or a magical staff you might find as your weapon; they fulfill the requirements of Polearm Master and you would be able to use them one-handed because Staffs are (unless stated otherwise) quarterstaffs. (DMG, p.140)
A:
Yes, but not at 10'
From the SRD (emphasis mine):
Reach: This weapon adds 5 feet to your reach when you attack with it, as well as when determining your reach for opportunity attacks with it.
A polearm only grants 10' reach for attacks made with the weapon. Since you need both hands to attack with the weapon, you cannot attack with the weapon, and your reach is not 10'. The opportunity attack is not triggered until the creature approaches to within 5' (your natural reach).
| {
"pile_set_name": "StackExchange"
} |
Q:
why is $1.class generated?
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
class Enum1 {
public static void main(String args[]) {
Day day=Day.MONDAY;
switch(day) {
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday");
break;
default:
System.out.println("other day");
}
}
}
I see that Enum1.class ,Day.class, and Enum1$1.class when I compile this code. When I comment out the switchcase part only Enum1.class and Day.class are generated.
What in the switchcase is the cause of generating an extra Enum1$1.class file?
A:
Using javap on classes in the package de.lhorn:
Day.class
public final class de.lhorn.so.Day extends java.lang.Enum<de.lhorn.so.Day> {
public static final de.lhorn.so.Day SUNDAY;
public static final de.lhorn.so.Day MONDAY;
public static final de.lhorn.so.Day TUESDAY;
public static final de.lhorn.so.Day WEDNESDAY;
public static final de.lhorn.so.Day THURSDAY;
public static final de.lhorn.so.Day FRIDAY;
public static final de.lhorn.so.Day SATURDAY;
public static de.lhorn.so.Day[] values();
public static de.lhorn.so.Day valueOf(java.lang.String);
static {};
}
Enum1.class
public class de.lhorn.so.Enum1 {
public de.lhorn.so.Enum1();
public static void main(java.lang.String[]);
}
Enum$1.class
class de.lhorn.so.Enum1$1 {
static final int[] $SwitchMap$de$lhorn$so$Day;
static {};
}
So the switch causes javac to generate the additional static final int[] $SwitchMap$de$lhorn$so$Day;.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the benefits of registering an event handler implicitly
What's the benefits of registering an event as:
void MyMethod()
{
button1.Click += delegate (object sender, EventArgs e)
{
..
}
}
in comparison with:
void MyMethod()
{
button1.Click += new System.EventHandler(this.button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
..
}
UPDATE:
And what about unsubscribing it?
A:
The benefit is that you don't have to come up with a name and a place in your class.
For a light function, tightly coupled to the code that register the event, the short version is more convenient.
Note that you can also exchange delegate for a =>
button1.Click += (object sender, EventArgs e) =>
{
..
}
A:
You can be even more concise:
button1.Click += ( sender, e ) =>
{
};
Syntactically it's cleaner (as long as it doesn't lead to long blocks of code which would be better broken up into named methods).
The inline declaration is a closure, which gives you access to the variables adjacent to the anonymous method.
From: What are 'closures' in .NET?
In essence, a closure is a block of code which can be executed at a
later time, but which maintains the environment in which it was first
created - i.e. it can still use the local variables etc of the method
which created it, even after that method has finished executing.
See also: http://csharpindepth.com/articles/chapter5/closures.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving the existence and uniqueness of an operator over a Hilbert space
Let $H$ be a Hilbert space and let $f \colon H \times H \to \mathbb C$ be a
sesquilinear map such that
$$ M = \sup \{ |f(x, y)| \mid x, y \in H, \|x\| = \|y\| = 1 \} < \infty$$
Prove that there exists a unique operator $S \in B(H)$, such that
$$ f(x, y) = \langle Sx, y \rangle,\qquad\forall x, y \in H.$$
Finally, prove that $\|S\| = M$.
My incomplete attempt
Fix $x \in H$ and consider the functional
\begin{align*}
\Phi_x \colon H &\to \mathbb C\\
y &\mapsto \overline{f(x, y)}
\end{align*}
$\Phi_x \in H^\star$ is well-defined by construction, since by
hypothesis $f(x, y) \in \mathbb C$.
$\Phi_x$ is linear.
Let $y, z \in H$ and $\alpha, \beta \in \mathbb C$. Then
$$\Phi_x(\alpha y + \beta z) = \overline{f(x, \alpha y + \beta z)} =
\alpha \overline{f(x, y)} + \beta \overline{f(x, z)} = \alpha
\Phi_x(y) + \beta \Phi_x(z).$$
$\Phi_x$ is bounded. Let $y \in H$. We have to prove that there
exists a constant $c \in \mathbb R$ such that $|\Phi_x(y)| \leq
c\|y\|$. If $y = 0$, the inequality is trivially true. Therefore,
suppose $y \neq 0$. Using the bilinearity of $f$ we have that
$$|\Phi_x(y)| = |\overline{f(x, y)}| = |f(x, y)| =
\|x\|\cdot\|y\|\left|f\left(\frac{x}{\|x\|},
\frac{y}{\|y\|}\right)\right| \leq M\|x\| \cdot \|y\|$$
Therefore we can take $c = M\|x\| \in \mathbb R$, since $x$ is fixed.
We also observe that $\|\Phi_x\| \leq M\|x\|$.
By Riesz's representation theorem, there exists a unique element in $H$, which we call $Sx \in H$, such that $\Phi_x(y) = \overline{f(x, y)} = \langle y, Sx \rangle$.
We will now prove that $S \in B(H)$.
$S$ is linear. Let $x, z \in H$ and $\alpha, \beta \in \mathbb C$.
For all $y \in H$, we have that
$$\langle y, S(\alpha x + \beta z) \rangle = \overline{f(\alpha x +
\beta z, y)} = \overline{\alpha f(x, y) + \beta f(z, y)} =
\bar\alpha \langle y, Sx \rangle + \bar\beta \langle y, Sz \rangle
= \langle y, \alpha Sx + \beta Sz \rangle$$
From the arbitrariness of $y$, it follows that $S(\alpha x + \beta z) =
\alpha Sx + \beta Sz$.
$S$ is bounded. From Riesz's theorem, we have that $\|Sx\| =
\|\Phi_x\|$, and at point $3.$ above we proved that $\|\Phi_x\| \leq
M\|x\|$. So $\|S\| \leq M \in \mathbb R$ and $S$ is bounded.
Finally, we use the definition of operator's norm:
$$\|S\| = \sup \{ \|Sx\| \mid x \in H, \|x\| = 1 \} = {\large\textbf{?}}$$
Questions
1. Is the proof correct up to the last point? I'm particularly interested in the second part, where I applied Riesz's theorem.
2. How should I conclude it? I know it must be related to the definition of $M$, probably I'm just missing something simple.
A:
Your proof looks fine. What you have to use is
$$
\|S\|=\sup\{|\langle Sx,y\rangle|:\ \|x\|=\|y\|=1\}.
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
ESP8266 Connection to Arduino Mega 2560
Im trying to connect my esp8266-01 to my arduino mega 2560 to get the code working from the following video tutorial found on youtube:
https://www.youtube.com/watch?v=zGgUfAB4m24
This is the code Im using from the youtube video:
#include <SoftwareSerial.h>
#define ESP8266_rxPin 4
#define ESP8266_txPin 5
//SSID + KEY
const char SSID_ESP[] = "SSID";
const char SSID_KEY[] = "PASSWORD";
// URLs
const char URL_youtube[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";
const char URL_current_temp[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";
//MODES
const char CWMODE = '1';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
const char CIPMUX = '1';//CWMODE 0=Single Connection, 1=Multiple Connections
SoftwareSerial ESP8266(ESP8266_rxPin, ESP8266_txPin);// rx tx
//DEFINE ALL FUNCTIONS HERE
boolean setup_ESP();
boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
void timeout_start();
boolean timeout_check(int timeout_ms);
void serial_dump_ESP();
boolean connect_ESP();
void get_youtube();
void get_current_temp();
void get_hilo_temp();
//DEFINE ALL GLOBAL VAARIABLES HERE
unsigned long timeout_start_val;
char scratch_data_from_ESP[20];//first byte is the length of bytes
char payload[150];
byte payload_size=0, counter=0;
char ip_address[16];
char youtube_subs[10];
char youtube_views[13];
char current_temp[5];
char hi_temp[5];
char lo_temp[5];
//DEFINE KEYWORDS HERE
const char keyword_OK[] = "OK";
const char keyword_Ready[] = "Ready";
const char keyword_no_change[] = "no change";
const char keyword_blank[] = "#&";
const char keyword_ip[] = "192.";
const char keyword_rn[] = "\r\n";
const char keyword_quote[] = "\"";
const char keyword_carrot[] = ">";
const char keyword_sendok[] = "SEND OK";
const char keyword_linkdisc[] = "Unlink";
//keywords for youtube
const char keyword_html_start_b[] = "b>";
const char keyword_html_end_b[] = "</b";
//keywords for current temp
const char keyword_html_start_temp[] = "p\">";
const char keyword_html_end_temp[] = "<s";
const char keyword_html_start_body = "<body>";
const char keyword_html_end_body = "</body>";
void setup(){// SETUP START
//Pin Modes for ESP TX/RX
pinMode(ESP8266_rxPin, INPUT);
pinMode(ESP8266_txPin, OUTPUT);
ESP8266.begin(9600);//default baudrate for ESP
ESP8266.listen();//not needed unless using other software serial instances
Serial.begin(115200); //for status and debug
delay(5000);//delay before kicking things off
setup_ESP();//go setup the ESP
}// SETUP END
void loop(){// LOOP START
//get_youtube(); // get youtube views and subs
//delay(15000);//thingspeak needs ~12 secs before next connection
get_current_temp();//current temperature
delay(15000);
}// LOOP END
Whenever I run the code everything just fails and Im not able to send AT commands from my arduino to the ESP.
Im using the following connection between the arduino and the ESP:
**ESP <---------------------> ARDUINO
GND -------------------------- GND
GP2 -------------------------- Not connected
GP0 -------------------------- Not connected
RXD -------------------------- DIGITAL PIN 4
TXD -------------------------- DIGITAL PIN 5
CHPD ------------------------ 3.3V
RST -------------------------- Not connected
VCC -------------------------- 3.3V**
If I connect RESET pin on the arduino to GND and the RX and TX pins on the ESP to digital pins 1 and 0 on the arduino and run the serial monitor and try the AT commands they work fine.
But when I try to run the AT commands by sending them from the arduino to the ESP (by running the code) I get the failed every time. What am I doing wrong?
Here is the link to the full code:
http://www.kevindarrah.com/wp-content/uploads/2015/01/ESP8266_BASE_01_28_15.zip
A:
I fixed it by changing everything on the code from SoftwareSerial ESP8266 to the hardware serial: Serial1.
I used the pins 18 and 19 of the hardware serial. I also made sure connect the RX pin of the ESP to the TX pin of the Arduino and do the same with the TX pin.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between these Pentium Extreme Edition CPUs?
The CPU in question is the Pentium Extreme Edition 955.
Intel's website shows four "versions", but for the most part they all look identical. They even share the same set of ordering codes.
But one of them has a substantially lower TDP, which is seemingly unexplainable - since everything else is the same. Two of them say "LGA775, Tray" and I have no idea what "Tray" means either. Also, two of them have a different SPEC code.
What I need to know is:
What does "LGA775, Tray" mean?
Why does the one CPU have a lower TDP? And what does that mean for me? Does that mean lower maximum power consumption? Does it mean the CPU may be more stable/endurant, because of a lower heat output?
Why do two of them have a different SPEC code, and what does this mean?
Finally, what does PLGA775 (as opposed to LGA775) mean, and do I need to be worried about that?
Information from Intel's wbsite:
Intel® Pentium® Processor Extreme Edition 955 (4M Cache, 3.46 GHz, 1066 MHz FSB) with SPEC Code
1
Boxed Intel® Pentium® Processor Extreme Edition 955
4M Cache, 3.46 GHz, 1066 MHz FSB
LGA775
PLGA775
B1
95 Watts
BX80553955
SL94N
2
Intel® Pentium® Processor Extreme Edition 955
4M Cache, 3.46 GHz, 1066 MHz FSB
LGA775, Tray
PLGA775
B1
130 Watts
HH80553PH0994M
SL94N
3
Boxed Intel® Pentium® Processor Extreme Edition 955
4M Cache, 3.46 GHz, 1066 MHz FSB
LGA775
PLGA775
B1
130 Watts
BX80553955
SL8WM
4
Intel® Pentium® Processor Extreme Edition 955
4M Cache, 3.46 GHz, 1066 MHz FSB
LGA775, Tray
PLGA775
B1
130 Watts
HH80553PH0994M
SL8WM
A:
First of all I would STRONGLY discourage you from getting that CPU at all costs. They are overpriced (still) and extremely obsolete.
LGA stands for Land Grid Array and refers to the socket type. LGA has the pins on the motherboard not the CPU.
PLGA is Plastic Land Grid Array and refers to how the core is integrated into the rest of the CPU. You don't need to worry about this.
Tray means that the processors are OEM and are purchased by the tray, usually in multiples of 100. You cannot buy just one of them from Intel directly, but they are resold as OEM chips by some vendors. They do not include a heatsink/fan and usually carry a lesser warranty.
As for the 95W chip, it looks like it is the same stepping and revision as another model, so barring a typo it is possible through quality control to bin out the chips that require a lower power consumption but I don't think I've seen this before without it carrying a separate revision number.
Edit:
Forgot to answer one thing - The different spec codes refer to different revisions of the processor. Sometimes a newer version of the same processor is released with minor tweaks and changes. These are not usually apparent to end users, though the revision does make a difference to heavy overclockers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passbook web service URL can't be recognized by PKPass
I am building a passbook web service and backend. I use PHP-Passbook to generate the pass file. The created pass can then be added to Passbook. However, it won't call my web service. I checked my code and found that it's because when I use the following code to create a PKPass object, anything except webserviceUrl can be imported in object, pass.webserviceUrl is always nil.
PKPass *pass = [[PKPass alloc] initWithData:responseObject error:&error];
here is my pass.json file
{
"serialNumber": "90f9f133-cbd7-47b3-9b04-8a443f488495",
"description": "Event",
"formatVersion": 1,
"eventTicket": {
"primaryFields": [
{
"key": "event",
"label": "Event",
"value": "Test Event"
}
],
"secondaryFields": [
{
"key": "location",
"label": "Location",
"value": "Moscone West"
}
],
"auxiliaryFields": [
{
"key": "datetime",
"label": "Date & Time",
"value": "Tuesday 30th of July 2013 11:30:26 AM'"
}
]
},
"relevantDate": "2013-07-24T14:25-08:00",
"barcode": {
"format": "PKBarcodeFormatQR",
"message": "hello world",
"messageEncoding": "iso-8859-1"
},
"backgroundColor": "rgb(253,229,47)",
"logoText": "FDJ Event",
"authenticationToken": "72aa48d08db9a379f147e38fb23a3901",
"webServiceUrl": "http://www.test.com/passbook/index.php",
"passTypeIdentifier": "pass.test.passbooktest",
"teamIdentifier": "XXXXXXX",
"organizationName": "TEST"
}
I also enabled 'Allow HTTP Services' in Developer menu. It doesn't work either.
Any solutions?
A:
The key that you are looking for is webServiceURL (URL is capitalised).
PKPass Class Reference
| {
"pile_set_name": "StackExchange"
} |
Q:
Why aren't different coordinate systems of interest in linear algebra?
In linear algebra we used the standard basis and talked about vector spaces. But we never mentioned coordinate systems.
In physics we made it clear which coordinate system we were using (cartesian, cylindrical, spherical).
Why aren't different coordinate systems of interest in linear algebra?
A:
(Note: this answer is not particularly well-written and is just meant to expand somewhat on my terse comment above, as was requested by others.)
The whole point of linear algebra is to consider transformations between different affine coordinate systems.
Cylindrical/spherical etc. coordinate systems are not linear or affine.
affine transformation
linear map
affine coordinate system
Specifically, a coordinate system is determined by a set of coordinate functions. Linear algebra can be considered to include the study of linear coordinate functions (see linear functional and dual space), while the study of more general coordinate systems (i.e. ones whose coordinate functions are not necessarily linear) requires techniques of differential geometry.
For example, given two vectors in $\mathbb{R}^2$, $x, y$, we can consider their polar coordinates $r, \theta$ to be two functions $\mathbb{R}^2 \to \mathbb{R}$. When I say that polar coordinates aren't "linear" or "affine", I just mean that we do not necessarily have that $r(x + y) = r(x) + r(y)$ or that $\theta(x+y) = \theta(x) + \theta(y)$.
The study of non-linear coordinate systems and the transformations between them is part of the field of differential geometry.
Describing how to change and move between arbitrary coordinate systems, not just ones whose coordinate functions are linear, are historically what motivated Riemann to develop the concept of "chart" and "atlas", and thus ultimately of manifold.
The key idea to remember here is that any Euclidean space is a manifold, and that considering more general types of coordinate systems besides linear ones requires more and different techniques besides just those offered by linear algebra. It turns out that a lot of these techniques are unchanged when considering objects which look "locally" like Euclidean space, called manifolds. So a lot of the motivations for the concepts of differential geometry can be found and studied in surprising depth just by considering non-linear coordinate systems for Euclidean spaces.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why did the release statement here crashes the app?
NSError *theError = nil;
NSArray *keys = [NSArray arrayWithObjects:@"password", @"userId", nil];
NSArray *objects = [NSArray arrayWithObjects:passwordTextField.text, userNameTextField.text, nil];
NSDictionary *requestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *JSONString =[requestDictionary JSONRepresentation];
NSData *JSONData =[JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"JSONString :%@", JSONString);
NSLog(@"JSONData :%@", JSONData);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://153.20.32.74/11AprP306/passenger/jsonitem"]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:JSONData];
[request setHTTPMethod:@"POST"];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSLog(@"response : %@", theResponse);
NSLog(@"error : %@", theError);
NSLog(@"data : %@", data);
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string: %@", string);
[string release];
//[theResponse release]; // this statement crashes the app
Has it got something with to do with this statement :NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
I see a & symbol used. What does it means?
A:
I'll post this as a new answer as you edited your question.
You are doing it the wrong way.
It is the responsability of sendSynchronousRequest:returningResponse:error: to create the response for you (or the error if something went wrong)
This is why you need to pass a pointer to theResponse and a pointer to theError
When the call to sendSynchronousRequest:returningResponse:error: is done, theResponse will be created and most importantly autoreleased (by sendSynchronousRequest:returningResponse:error) !!
So in the end you are back to the autorelease/over release issue.
The correct code is:
NSURLResponse *theResponse = nil; // no need to init it will be done later on
NSError *theError = nil; // no need to init either
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&theError];
if (aError != nil) { } // handle error
else {} // handle your response data
//no need to release theResponse
| {
"pile_set_name": "StackExchange"
} |
Q:
How to avoid printing exception and assign another action when exception was encountered? My attempt don't work right
I am encountering an error when user doesn't type anything into input statement. I thought of using Try/Catch blocks to instead throw exception to set boolAskRepeat to true which should skip to the end of the code and repeat the loop.
This doesn't work, and I believe I'm missing something but I'm not sure what... It still throws exception saying:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at ITSLab03.main(ITSLab03.java:34)
Which is this line of code: inputStatus = input.readLine().toLowerCase().charAt(0);
What am I doing wrong here?
while (boolAskStatus == true)
{
System.out.print("Employment Status (F or P): ");
try
{
inputStatus = input.readLine().toLowerCase().charAt(0);
if (inputStatus == "f".charAt(0))
{
boolAskStatus = false;
String stringCheckSalary = null;
boolean boolCheckSalary = true;
while (boolCheckSalary == true)
{
// some code
}
outputData(inputName, inputStatus, calculateFullTimePay(inputSalary));
}
else if (inputStatus == "p".charAt(0))
{
// some code
outputData(inputName, inputStatus, calculatePartTimePay(inputRate, inputHours));
}
else boolAskStatus = true;
}
catch (IOException e) { boolAskStatus = true; }
}
A:
You need to catch StringIndexOutOfBoundsException as well (If you observe the stack trace properly this is the exception you are getting)
catch (StringIndexOutOfBoundsException e) {
boolAskStatus = true;
}
(or)
catch Exception which catches all runtime exceptions
catch (Exception e) {
boolAskStatus = true;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Display div on hover with CSS selector "+" combinater
I am trying to get a div to show on hover using the "+" combinater and it's not working. Here is my code:
HTML
<div class="about-team">
<div class="client">
<div class="about-team-left"> <a href="#"><img src="http://placehold.it/150x150"></a>
</div>
<div class="about-team-right">
<p>Just writing a quick note to tell you how very happy we are with our new addition to our family... Our "Molly" is such an adorable puppy... <a id="rm">READ MORE</a>
</p>
</div>
<div class="readmore1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, qui est quo consequuntur esse iure tempora. Hic tenetur nemo repudiandae quae unde sed aliquid deleniti ad! Facilis, reprehenderit culpa mollitia.</div>
CSS
.readmore1 {
display: none;
}
#rm:hover + .readmore1 {
display: block;
height: 100px;
width: 200px;
}
JSfiddle:
http://jsfiddle.net/9zDEp/3/
Thanks!
A:
Your html structure didn't work with the anchor and div inside the p but you can switch the text to be inside a span so they wrap:
<div class="about-team">
<div class="client">
<div class="about-team-left"> <a href="#">
<img src="http://placehold.it/150x150" /></a>
</div>
<div class="about-team-right">
<span>Just writing a quick note to tell you how very happy we are with our new addition to our family... Our "Molly" is such an adorable puppy...</span>
<a id="rm">READ MORE</a>
<div class="readmore">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, qui est quo consequuntur esse iure tempora. Hic tenetur nemo repudiandae quae unde sed aliquid deleniti ad! Facilis, reprehenderit culpa mollitia.</div>
</div>
</div>
Also, I would consider using a more generalized CSS that doesn't rely on ID fields, like this:
.readmore {
display: none;
}
a:hover + div.readmore {
display: block;
height: 100px;
width: 200px;
}
http://jsfiddle.net/9zDEp/15/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use query where using CASE in oracle
Hi I am trying to run this query, but the in the where statement the Case is giving an error. What I am trying to do is, if i_id is >= 284 then append cnint <=65 to the query after the and else append the other one. This query is in a stored procedure.
Select cnint as Id, cnabbv as Code, rtrim(cnname) as Name, i_id as CId, cntry as CCode
from money.country where cntype = 1 and (CASE
WHEN i_id = 284 THEN cnint <= 65
ELSE cnint > 65
END)
order by cnname;
This query is in a stored procedure.
A:
It isn't supported there. Try this:
Select cnint as Id, cnabbv as Code, rtrim(cnname) as Name, i_id as CId, cntry as CCode
from money.country where cntype = 1 and
((i_id = 284 AND cnint <= 65) OR (coalesce(i_id, 0) != 284 and cnint > 65))
order by cnname;
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the metal sheath surrounding a USB connector, and is it commonly connected?
I was tearing apart a mouse for repairs and noticed that the small plug for the USB connection had a fifth connection. This connection had a much thicker wire than the other four.
I assume it is connected to the metal sheath on the male end of the connector, but what does it actually do?
A:
It's a shielding ground, usually made of copper braid. It stops stray signals from leaking in or out of the cable.
It should usually be connected at at least one end. I've seen conflicting advice over exactly how it should be connected to minimise noise and avoid ground loops.
| {
"pile_set_name": "StackExchange"
} |
Q:
Construction of Grassmannian
I am trying to understand what is a Grassmannian.
Starting with the projective space $\mathbb{R}P^n$ = {lines in $\mathbb{R}^{n+1}$} and the grassmannian $G_r(k,n)$ = {$k-dimentional\space subspace\space E \subseteq\mathbb{R}^n$}. Moreover I am told that $\mathbb{R}P^n = G_r(1,n+1)$ which implies that {lines} compose a 1-dimentional subspace. So here is my first question although elementary:
1) How does one prove that the set of lines is a 1-dimensional subspace? (just a hint/idea) (I know how to prove that lines in $\mathbb{R}^2$ are a subspace but do not understand why they are 1-dimentional say in $\mathbb{R}^n$)
2) What are examples of k-dimentional subspaces in $\mathbb{R}^n$ with $k\le n$, how many are there (in $\mathbb{R}^2$ there are 3)
3) Can we define the grassmannian as the quotient space of some manifold? Such as $S^n/\sim \space with\space x\sim\pm x$ for $\mathbb{R}P^n$
4) How do we explain $dim(G_r(k,n))=k(n-k)$? would it be linked with the set of linear maps $L(\mathbb{R}^k,\mathbb{R}^{n-k})$
Thank you for any insight, somehow i did not find projective spaces too hard to understand but this is not breaking through...
A:
$\DeclareMathOperator{\Gr}{Gr}\newcommand{\Reals}{\mathbf{R}}\newcommand{\Cpx}{\mathbf{C}}\newcommand{\Proj}{\mathbf{P}}$In the context of projective space, a line in $\Reals^{n+1}$ is precisely a one-dimensional subspace. That's why the real projective space $\Reals\Proj^{n}$, the set of "lines" in $\Reals^{n+1}$, is effectively the Grassmannian $G(1, n+1)$. As for your numbered questions:
"Subspace" is meant in the sense of elementary linear algebra, a non-empty subset of a vector space that is closed under addition and under scalar multiplication. A line through the origin is a one-dimensional subspace.
(Incidentally, the Grassmannian you ask about is the unoriented Grassmannian. There is also an oriented Grassmannian, whose elements are oriented subspaces of fixed dimension. The oriented Grassmannian of lines in $\Reals^{n+1}$ is the $n$-sphere: Each oriented line through the origin contains a unique "positive" unit vector, and conversely each unit vector determines a unique oriented line through the origin.)
If $n \leq 3$, the only proper, non-trivial subspaces of $\Reals^{n}$ have dimension $1$ (i.e., are lines) or codimension $1$ (i.e., are planes in $\Reals^{3}$).
The "smallest" Grassmannian that is not (effectively) a projective space is the Grassmannian $\Gr(2, 4)$ of planes in $\Reals^{4}$.
As a homogeneous space, $\Gr(k, n) \simeq O(n)/O(k) \times O(n-k)$. Each orthonormal frame in $\Reals^{n}$ (i.e., each element of the orthogonal group $O(n)$) determines the $k$-plane spanned by (say) its first $k$ elements. The isotropy group of $\Reals^{k} \simeq \Reals^{k} \times \{0\} \subset \Reals^{n}$ is $O(k) \times O(n-k)$.
Alternatively, there is a bundle over $\Gr(k, n)$, called a Stiefel manifold, whose fibre over a $k$-plane is the set of orthonormal bases of that subspace. The Grassmannian $\Gr(k, n)$ may be viewed as the quotient of the bundle of orthonormal $k$-frames (a Stiefel manifold) obtained by mapping an orthonormal frame to its linear span.
As you say, the dimension of $\Gr(k, n)$ may be linked with the set of linear maps $L(\Reals^{k}, \Reals^{n-k})$. Geometrically, a curve through $\Reals^{k} \subset \Reals^{n}$ is a "smooth perturbation" of the standard $k$-plane in $\Reals^{n}$. Infinitesimally, a smooth perturbation amounts to a linear map $T$ from the standard $k$-plane to its orthogonal complement (via the graph of $T$).
All these constructions can be carried out using general linear frames rather than orthonormal frames. Symbolically, replace each $O$ with $GL$. (One advantage of using orthonormal frames is that compactness of the Grassmannians follows from compactness of the orthogonal group. One advantage of working in the general linear setting is that the complex Grassmannians are easily seen to be holomorphic manifolds, not merely smooth manifolds.)
If you need more detailed information, e.g., the cohomology ring, Milnor and Stasheff's Characteristic Classes is (for good reason) a standard reference.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create a Dictionary as a optional property using Swift
I created a swift class to test Dictionaries. So, I wrote the code below:
import Foundation
class MyClass {
var myFirstDictionary:[String :String]
var myThirdDictionary:[String :String]?
init(){
var mySecondDictionary:[String :String] = [String :String]()
mySecondDictionary["animal"] = "Monkey"
mySecondDictionary.updateValue("something", forKey: "SomeKey")
self.myFirstDictionary = [String :String]()
addOneThingToSecondDictionary()
addAnotherThingToSecondDictionary()
self.myThirdDictionary! = [String :String]()
addOneThingToThirdDictionary()
addAnotherThingToThirdDictionary()
}
func addOneThingToSecondDictionary(){
self.myFirstDictionary["animal"] = "Monkey"
}
func addAnotherThingToSecondDictionary(){
self.myFirstDictionary.updateValue("Superman", forKey: "hero")
}
func addOneThingToThirdDictionary(){
self.myThirdDictionary["animal"]! = "Monkey"
}
func addAnotherThingToThirdDictionary(){
self.myThirdDictionary!.updateValue("Superman", forKey: "hero")
}
}
So, I got 3 errors referring to "myThirdDictionary" :
In the Dictionary initialization compiler said: Could not find an overload for 'init' that accepts the supplied arguments
When I tried to add a Key/value pair in addOneThingToThirdDictionary() : '[String : String]?' does not have a member named 'subscript'
When I tried to add a Key/value pair in addAnotherThingToThirdDictionary() : Immutable value of type '[String : String]' only has mutating members named 'updateValue'
Any thoughts ?
A:
Some of these issues are conceptual errors, and some of them have to do with behaviors that changed in today's Xcode 6 beta 5 release. Running through them all:
This line compiles, but has a superfluous !:
self.myThirdDictionary! = [String :String]()
You don't need to unwrap an optional to assign to it -- it doesn't matter if its current contents are nil if you're providing new contents. Instead, just assign:
self.myThirdDictionary = [String :String]()
Similarly, this line fails because you're subscripting before unwrapping:
self.myThirdDictionary["animal"]! = "Monkey"
This is a problem because you could be subscripting nil if myThirdDictionary has not been initialized. Instead, subscript after checking/unwrapping the optional. As of beta 5, you can use mutating operators or methods through an optional check/unwrap, so the shortest and safest way to do this is:
self.myThirdDictionary?["animal"] = "Monkey"
If myThirdDictionary is nil, this line has no effect. If myThirdDictionary has been initialized, the subscript-set operation succeeds.
This line failed on previous betas because force-unwrapping produced an immutable value:
self.myThirdDictionary!.updateValue("Superman", forKey: "hero")
Now, it works -- sort of -- because you can mutate the result of a force-unwrap. However, force unwrapping will crash if the optional is nil. Instead, it's better to use the optional-chaining operator (which, again, you can now mutate through):
self.myThirdDictionary?.updateValue("Superman", forKey: "hero")
Finally, you have a lot of things in this code that can be slimmed down due to type and scope inference. Here it is with all the issues fixed and superfluous bits removed:
class MyClass {
var myFirstDictionary: [String: String]
var myThirdDictionary: [String: String]?
init(){
var mySecondDictionary: [String: String] = [:]
mySecondDictionary["animal"] = "Monkey"
mySecondDictionary.updateValue("something", forKey: "SomeKey")
myFirstDictionary = [:]
addOneThingToSecondDictionary()
addAnotherThingToSecondDictionary()
// uncomment to see what happens when nil
myThirdDictionary = [:]
addOneThingToThirdDictionary()
addAnotherThingToThirdDictionary()
}
func addOneThingToSecondDictionary(){
myFirstDictionary["animal"] = "Monkey"
}
func addAnotherThingToSecondDictionary(){
myFirstDictionary.updateValue("Superman", forKey: "hero")
}
func addOneThingToThirdDictionary(){
myThirdDictionary?["animal"] = "Monkey"
}
func addAnotherThingToThirdDictionary(){
myThirdDictionary?.updateValue("Superman", forKey: "hero")
}
}
(Changes: Foundation import unused, empty dictionary literal instead of repeated type info)
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL query which reformats results
Here is the example 'sales' table of data
Here is the desired output Result Set
Here is an example of the undesired Result Set that would be generated from this SQL statement.
SELECT Vendor, SUM(Markdown), SUM(Regular), SUM(Promotion), SUM(Returned)
FROM sales
GROUP BY Vendor, Date
Is there a way to get the desired result set through just SQL?
We are running a SQL DB2 database on an IBM iSeries.
I do realize this is a very odd way to try to do this... we are just trying to find a way to get the result set back as needed, without having to do any manual conversion of the results through code.
A:
you need to use UNION statement
try,
SELECT Vendor, 'Markdown' as Type, SUM(Markdown) as Amount
FROM sales
GROUP BY Vendor, Date
UNION
SELECT Vendor, 'Regular' as Type, SUM(Regular) as Amount
FROM sales
GROUP BY Vendor, Date
UNION
SELECT Vendor, 'Promotion' as Type, SUM(Promotion) as Amount
FROM sales
GROUP BY Vendor, Date
UNION
SELECT Vendor, 'Returned' as Type, SUM(Returned) as Amount
FROM sales
GROUP BY Vendor, Date
| {
"pile_set_name": "StackExchange"
} |
Q:
Return value from function to Cell
I am trying to return a value from a function and not sure how to go about this. The location I want to return it to is a merged cell from "G22:I26" on worksheets(1) and the original function is being done on worksheets(3).
Sub CountBlank()
Dim xxEmpty As Long
Dim LastRow As Long
LastRow = Worksheets(3).Cells(Rows.Count, 3).End(xlUp).Row
xxEmpty = Worksheets(3).CountBlank(Range("CY2:CY" & LastRow))
Return xxEmpty = Worksheets(1).Cells("G22:I26") 'Syntax Error
End Sub
A:
How to return a function result
Basically you return results to a function and not to a sub procedure (leave aside direct changes to parameters passed by reference - ByRef). Return is no valid method to return such function results as in other programming languages, you have to assign a value to the function itself.
Furthermore you have to use the Worksheetfunction.CountBlank function (or Application.CountBlank), CountBlank itself is no function or method related to a worksheet as you tried by xxEmpty = Worksheets(3).CountBlank(…).
Eventually avoid to overload procedures with existing names, so call your function e.g. getBlanks(), but not CountBlank().
a) Example call showing the result in VB Editor's immediate window:
Sub Test()
Dim LastRow As Long
LastRow = Worksheets(3).Cells(Rows.Count, 3).End(xlUp).Row
Debug.Print getBlanks(Worksheets(3).Range("CY2:CY" & LastRow)) & " blank rows counted"
End Sub
Function getBlanks(rng As Range) As Long
' Help:
' Return xxEmpty = Worksheets(1).Cells("G22:I26") 'Syntax Error
getBlanks = WorksheetFunction.CountBlank(rng)
End Function
If you want to return the function result directly to a cell, you could either just enter the function name choosing a precise range as argument:
=getBlanks(CY2:CY4711)
or you'd have to modify the function a little bit if you want to count only blanks from say row 2 up to the last entry.
| {
"pile_set_name": "StackExchange"
} |
Q:
I am having trouble with every Android graphics/SurfaceView tutorial
I'm trying to learn how to make video games on Android, and therefore I'm needing to get some decent tutorials going on how to make graphics on Android using the SurfaceView object. However every single graphics tutorial I've tried (mainly SurfaceView stuff) has failed. Please note that I don't want to use XML, as it is out of my element, and Google just wants to sell that technique on the advertisement of neatness, which I can do programmatically.
One major problem I've run into is that there are many tutorials, both from Google and from third parties, with code that uses the import android.opengl.GLSurfaceView command, or either imports a subset GLSurfaceView, and that never works on my IDE. Every time I try to import either one of those, Eclipse wants to say that it basically doesn't recognize that package. The strange thing is that I CAN import android.opengl.*, although that still causes some of the code in those packages to be referring to unrecognized types and/or methods.
After trying to fool around with the first problem for a while, I noticed that the Lunar Lander example didn't try to import either one of those two problem libraries. So I pulled the code and referenced resources for that into one of my infant projects, leaving everything else in that project unused. Of course I did change which package the Lunar Lander code was in and changed the class name in LunarLander.java or whatever, but that should not matter. I was able to get the thing to build in Eclipse. However when I went to run it, it would do nothing but crash. Without showing any Lunar Lander graphics or anything, the emulator would just give me this error message basically saying that my App has stopped working unexpectedly and makes me close the App.
1) What's the deal with the issues with the opengl.GLSurfaceView package?
2) What's the deal with the Lunar Lander example?
3) Where's a good, firm tutorial on how to make video games for Android
Thanks.
A:
Are you building games in 2D or 3D? I can't speak for 3D, but I've built some simple 2D games and SurfaceView was more a hindrance than a help. The emulator only simulates one core, so you don't really get a performance benefit on the drawing. Furthermore, the thread overhead and maintenance is a pain to deal with and prevents many capabilities (I spent a few hours just trying to launch a GameOver dialog from various configurations, and the extra thread prevented this from happening).
An alternative to SurfaceView would be to implement your own class that extends View, and override onDraw(Canvas) to draw whatever you like (this is what me and my friends did).
To answer your points:
I've never worked in 3D or used Android's OpenGL, but Eclipse (if that's what you're using) can be a bit temperamental with locating Android resources. Do the rest of your classes load?
Lunar Lander shows you how to create and destroy a view extending SurfaceView and SurfaceHandler. Again, there may be contexts for which SurfaceView is a great choice, but if you're just starting with Android and building simple 2D games, I don't think it's essential.
Good tutorials are hard to find. I learned enough to make this 2D game from spending a few hours with the e-book version of Hello Android.
Some buddies of mine and I are working on games for Android this semester, we've also set up a blog that we hope to make a resource to others as the semester goes on. Sadly, there's not much on it at the moment.
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make Maps (Key / Value) in Latex?
Looking to create a Image with a kind of Map with key/value in LaTeX like the one below:
I tried to make the image with TikZ and I got to the following script:
\begin{tikzpicture}
\tikzset{
block/.style = {draw, minimum width=1.0cm, minimum height=0.7cm, node distance=3cm},
down/.style={yshift=-4em}
}
\node[block] (4) at (0,0) {4};
\node[block,right of=4] (3) {3};
\node[block,right of=3] (7) {7};
\node[block] (A1) at ([down] 4) {A1};
\node[block] (A3) at ([down] 3) {A3};
\node[block] (A4) at ([down] 7) {A4};
\draw[->] (4) -- (3);
\draw[->] (3) -- (7);
\draw[->] (4) -- (A1);
\draw[->] (3) -- (A3);
\draw[->] (7) -- (A4);
\end{tikzpicture}
but how can I modify the lower nodes (A1, A3, A4) to make them look like tables?
A:
You could also use a tikz matrix:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,positioning}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\tikzset{
block/.style = {draw, minimum width=1.0cm, minimum height=0.7cm, rounded corners, node distance=3cm},
mymatrix/.style = {matrix of nodes, nodes={draw, text width=4em, minimum height=4ex, inner xsep=6pt},
row sep=-\pgflinewidth, column sep=-\pgflinewidth, inner sep=0pt},
}
\node[block] (4) at (0,0) {4};
\node[block,right= of 4] (3) {3};
\node[block,right= of 3] (7) {7};
\matrix[mymatrix, below= of 4] (A1) {%
order 5\\
main 4\\
net 3\\
};
\matrix[mymatrix, below= of 3] (A3) {%
order 7 \\
main 4 \\
net 1 \\
};
\matrix[mymatrix, below= of 7] (A4) {%
order 8 \\
main 9 \\
net 7 \\
};
\draw[->] (4) -- (3);
\draw[->] (3) -- (7);
\draw[->] (4) -- (A1);
\draw[->] (3) -- (A3);
\draw[->] (7) -- (A4);
\end{tikzpicture}
\caption{Maps\label{fig:M1}}
\end{figure}
\end{document}
A:
Finally, I have solved it using TikZ, attached scripts, thank you all.
\begin{figure}
\centering
\begin{tikzpicture}
\tikzstyle{block} = [draw, line width=0.25mm, minimum width=1.0cm, minimum height=0.7cm, node distance=3cm]
\tikzstyle{down} = [yshift=-4em]
\node[block, rounded corners] (4) at (0,0) {4};
\node[block,right of=4, rounded corners] (3) {3};
\node[block,right of=3, rounded corners] (7) {7};
\node[block] (A1) at ([down] 4)
{
\begin{tabular}{ l }
order 5 \\ \hline
main 4 \\ \hline
net 3 \\
\end{tabular}
};
\node[block] (A3) at ([down] 3)
{
\begin{tabular}{ l }
order 7 \\ \hline
main 4 \\ \hline
net 1 \\
\end{tabular}
};
\node[block] (A4) at ([down] 7)
{
\begin{tabular}{ l }
order 8 \\ \hline
main 9 \\ \hline
net 7 \\
\end{tabular}
};
\draw[->] (4) -- (3);
\draw[->] (3) -- (7);
\draw[->] (4) -- (A1);
\draw[->] (3) -- (A3);
\draw[->] (7) -- (A4);
\end{tikzpicture}
\caption{Maps} \label{fig:M1}
\end{figure}
| {
"pile_set_name": "StackExchange"
} |
Q:
Measuring clearance height for dishwasher
I am purchasing an 18" dishwasher but not installing it. I have to make sure it is the right size so that there are no issues when the installer comes. I have no idea how to install appliances. My existing cabinets have a base a few inches high under them. Where should I measure the clearance height from in order to get an appropriately sized dishwasher? The dishwasher will be replacing the cabinet and drawer here:
Should I go all the way to the floor, or to the top of the base? Also, should I go all the way up to the underside of the white counter top, or just up to the bottom of the horizontal wood panel right underneath it?
I don't have a picture of the inside, and not sure if this matters, but the inner floor of the cabinet is at the top of the base (i.e. it's more of a "platform" that the cabinet sits on, sorry I don't know the right terminology).
Also (again, not sure if this matters), much to my pleasant surprise I am getting new counter tops at the same time, if that affects the available options.
A:
The clearance is the space you have to insert the dishwasher...so that would be from your floor, to the underside of the counter's front lip. Nothing bigger can fit through that space.
New counter tops can help if you have to make the clearance taller than what's currently there, but that will introduce other issues (like having to raise the rest of the cabinets to match).
Finally, do the installers know they are pulling out existing cabinets? Typically an installer just inserts it into an existing opening. You may have to bring in a carpenter or cabinetmaker as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a custom post type plugin - wordpress
I am trying to create a custom type plugin. And I am not really sure what is wrong with my code since there is no errors but the plugin is not working even tho I already activate it. Thanks in advanced for the help.
defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); // copied in codex
class LouisPlugin
{
function __contruct() {
add_action ('init',array($this, 'custom_post_type'));
}
function activate(){
}
function deactivate(){
}
function unsintall(){
}
function custom_post_type(){
register_post_type('job_list',['public' => true, 'label'=>'job_list']);
}
}
if (class_exists('LouisPlugin')){
$louisPlugin = new LouisPlugin();
}
register_activation_hook( __FILE__, array($louisPlugin, 'activate' ) );
register_deactivation_hook(__FILE__, array($louisPlugin,'deactivate'));
A:
please check your code
function __contruct() {
add_action ('init',array($this, 'custom_post_type'));
}
the __construct method name was incorrect I think this can be one reason
function __construct() {
add_action ('init',array($this, 'custom_post_type'));
}
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I spelunk CloudObjects?
I want to dig through the structure of a cloud directory to enumerate what's in it and figure out what objects I can work with.
How can I do this?
A:
I just wrote a little chunk of code to do this in a semi-clumsy fashion:
Options[getCloudObjectPath] =
{
"Username" -> None
};
getCloudObjectPath[path_String, ops : OptionsPattern[]] :=
URLBuild@Flatten@{
Replace[OptionValue["Username"],
{
s_String?(StringLength[#] > 0 &) :>
"user:" <> StringSplit[s, "@"][[1]],
_ -> ""
}
],
URLParse[path, "Path"]
};
Options[getCloudObjectList] =
{
"Iterations" -> None
};
getCloudObjectList[copath_, ops : OptionsPattern[]] :=
If[IntegerQ@OptionValue["Iterations"],
Nest[
Sort@DeleteDuplicates@
Flatten[{Map[Quiet@Check[CloudObjects@#, {}] &, #], #}] &,
CloudObjects[copath],
OptionValue["Iterations"]
],
Quiet@Check[CloudObjects@copath, $Failed]
];
formatCloudObjectDS[cloudObjData_Association] :=
Association@
KeyValueMap[
StringReplace[First@#,
"https://www.wolframcloud.com/objects/" -> "user:"] ->
Association@Prepend[#2, CloudObject -> #] &,
cloudObjData
] // Dataset;
Options[getCloudObjectDS] =
Join[
{
"CheckPrivate" -> False
},
Options[getCloudObjectList],
Options[getCloudObjectPath]
];
getCloudObjectDS[cpath_String, ops : OptionsPattern[]] :=
Replace[
getCloudObjectList[
getCloudObjectPath[cpath,
FilterRules[{ops}, Options[getCloudObjectPath]]],
FilterRules[{ops}, Options[getCloudObjectList]]
],
l_List :>
formatCloudObjectDS[
l // If[TrueQ@OptionValue["CheckPrivate"],
Map[# -> Quiet@Check[Options[#], $Failed] &],
Map[# -> {} &]
] // Association // Select[Not@*FailureQ]
]
];
getCloudObjectDS[ops : OptionsPattern[]] :=
getCloudObjectDS["", ops]
We can use it like:
getCloudObjectDS["Username" -> "b3m2a1", "Iterations" -> 1]
to look at some of the stuff I have lying around up there.
Or we can plumb a cloud account that I saw in a URL in one of those Live CEOing videos:
getCloudObjectDS["Username" -> "ResourceSystem"]
If we want to only get the non-private resources and their options (note that this adds a bunch of time to the requests) relating to the DataRepository resources:
getCloudObjectDS["published/DataRepository", "Username" -> "ResourceSystem",
"CheckPrivate" -> True]
Hopefully this makes working with the cloud a bit easier.
| {
"pile_set_name": "StackExchange"
} |
Q:
apply custom function to a particular column rowise by group in data.table
I had a function to find the max value until current row number.
dt<- setDT(copy(mtcars),keep.rownames = TRUE)
apply(as.matrix(dt$rn), 1, function(x) {
index = as.numeric(ifelse(match(x, dt$rn) == 1, 2, match(x, dt$rn)))
max(dt[1:index-1,"mpg",with = FALSE])
})
# [1] 21.0 21.0 21.0 22.8 22.8 22.8 22.8 22.8 24.4 24.4 24.4 24.4 24.4 24.4 24.4 24.4 24.4 24.4 32.4 32.4 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9
# [32] 33.9
However, I would like to repeat the same based on a particular group say 'gear'. How would I modify the code. I feel it has to do with something like this.
dt[,max:=lapply(.SD,function(x){
index = as.numeric(ifelse(match(x,dt$rn) == 1, 2, match(x, dt$rn)))
return(max(dt[1:index-1,"mpg",with = FALSE]))
}),by = gear,.SDcols = "rn"]
I feel I may be missing something..
A:
a data.table solution
dt[, currMax := cummax(shift(mpg, fill = -Inf)), by = gear],
head(dt)
# rn mpg cyl disp hp drat wt qsec vs am gear carb currMax
# 1: Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 -Inf
# 2: Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 21.0
# 3: Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 21.0
# 4: Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 -Inf
# 5: Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 21.4
# 6: Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 21.4
Thanks @DavidArenburg for the edit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Popper.js not working if bootstrap CSS is imported?
I've run into a really unusual issue wherein Popper.js and Tooltip.js are refusing to work if I'm using the Bootstrap CSS.
Here is the code I'm using to test this:
<script src="https://unpkg.com/popper.js/dist/umd/popper.min.js"></script>
<script src="https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js"></script>
<span id="test-tooltip" data-tooltip="Testing tooltips!">Hover over me, I dare you.</span>
<script>
document.addEventListener('DOMContentLoaded', function() {
var referenceElement = document.getElementById("test-tooltip");
var instance = new Tooltip(referenceElement, {
title: referenceElement.getAttribute('data-tooltip'),
placement: "bottom",
});
});
</script>
There's also some CSS, but it's quite long, so I'll leave that at the bottom.
If I include Bootstrap anywhere, the whole thing just stops working. Nothing shows up at all when hovering.
<link rel="stylesheet" href="CSS/bootstrap.css">
I am using the latest version of bootstrap, and I've even tried a few older versions as well.
Here's the CSS that's being used to style the tooltips:
.popper,
.tooltip {
position: absolute;
background: rgb(75, 75, 75);
color: white;
min-width: 80px;
border-radius: 3px;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
padding: 12px;
text-align: center;
}
.popper .popper__arrow,
.tooltip .tooltip-arrow {
width: 0;
height: 0;
border-style: solid;
position: absolute;
margin: 5px;
}
.tooltip .tooltip-arrow,
.popper .popper__arrow {
border-color: rgb(75, 75, 75);
}
.popper[x-placement^="top"],
.tooltip[x-placement^="top"] {
margin-bottom: 6px;
}
.popper[x-placement^="top"] .popper__arrow,
.tooltip[x-placement^="top"] .tooltip-arrow {
border-width: 5px 5px 0 5px;
border-left-color: transparent;
border-right-color: transparent;
border-bottom-color: transparent;
bottom: -5px;
left: calc(50% - 5px);
margin-top: 0;
margin-bottom: 0;
}
.popper[x-placement^="bottom"],
.tooltip[x-placement^="bottom"] {
margin-top: 6px;
}
.tooltip[x-placement^="bottom"] .tooltip-arrow,
.popper[x-placement^="bottom"] .popper__arrow {
border-width: 0 5px 5px 5px;
border-left-color: transparent;
border-right-color: transparent;
border-top-color: transparent;
top: -5px;
left: calc(50% - 5px);
margin-top: 0;
margin-bottom: 0;
}
.tooltip[x-placement^="right"],
.popper[x-placement^="right"] {
margin-left: 6px;
}
.popper[x-placement^="right"] .popper__arrow,
.tooltip[x-placement^="right"] .tooltip-arrow {
border-width: 5px 5px 5px 0;
border-left-color: transparent;
border-top-color: transparent;
border-bottom-color: transparent;
left: -5px;
top: calc(50% - 5px);
margin-left: 0;
margin-right: 0;
}
.popper[x-placement^="left"],
.tooltip[x-placement^="left"] {
margin-right: 6px;
}
.popper[x-placement^="left"] .popper__arrow,
.tooltip[x-placement^="left"] .tooltip-arrow {
border-width: 5px 0 5px 5px;
border-top-color: transparent;
border-right-color: transparent;
border-bottom-color: transparent;
right: -6px;
top: calc(50% - 5px);
margin-left: 0;
margin-right: 0;
}
Does anyone know why something this unusual might be happening?
Things I have tried:
Removing everything related to tooltips from bootstrap.css
Importing bootstrap before/after the Popper.js related stuff in the code.
Placing the custom CSS into bootstrap.css.
And many other things, all of which I have forgotten while trying to figure this out.
A:
I have gone through your code and it's working perfectly, the issue is only with the opacity of tooltip.
Add this code to show your tooltip
.tooltip[aria-hidden="false"]{
opacity:1;
}
Link to working fiddle here
| {
"pile_set_name": "StackExchange"
} |
Q:
Else statement fails to work within a while loop
Below is my code to connect to the database using MySqlDataReader. Now the if statement is working fine but the else statement doesnt. When i use the debug function in VS it kept skipping the else statement and jump to the reader.Close();.
Any idea. Thanks
private void db()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
MySqlConnection connection = new MySqlConnection(constr);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM user Where user_id ='" + Userid.Text + "'" + "And password='" + Password.Text + "'";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
Label1.Text = reader["user_id"].ToString();
}
else
{
Label1.Text = "nodata";
}
reader.Close();
}
}
A:
First of all: Don't use string concatenation for building queries, but use parameterized queries!
As for your problem: I assume this query will only return either 1 or 0 rows, so you don't need the loop but just check
if (reader.Read()) {
//...
}
Using SELECT * with column indexes is potentially dangerous, because you may not know what the "first" column returned is. I would suggest name your desired columns in the query
SELECT user_id, user_name ... FROM ...
What is the value of the first column returned? I assume, it's the user_id. Thus, this can never fulfill the condition IsDBNull(0) because user_id is your matching criterion in the WHERE clause. If your WHERE clause does not match any record in the table, reader.Read() will already fail, so you'll never get to your else branch.
Furthermore, I would suggest a using clause, which will dispose the reader automatically, so you don't have to care about closing it.
command.CommandText = "SELECT user_id, foo, bar from user where user_id = @userid and password = @password";
command.Parameters.AddWithValue("@user_id", UserId.Text);
command.Parameters.AddWithValue("@password", Passowrd.Text);
using (MySqlDataReader reader = command.ExecuteReader()) {
if (reader.Read()) {
Label1.Text = reader["user_id"].ToString();
} else {
Label1.Text ="nodata";
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Java URL encoding
From my web application I am doing a redirect to an external URL which has some credentials as a part of the URL string. I would like to encode the credential part alone before redirection. I have the following URL:
String url1 = "http://servername:7778/reports/rwservlet?server=server1&ORACLE_SHUTDOWN=YES&PARAMFORM=no&report=test.rdf&desformat=pdf&desname=test.pdf&destype=cache¶m1=56738&faces-redirect=true&";
I am encoding it as:
String URL = "userid=username/passwd@DBname";
encodedURL = URLEncoder.encode(URL, "UTF-8");
String redirectURL = url1 + encodedURL1;
The URL generated by this code is
http://servername:7778/reports/rwservlet?server=server1&ORACLE_SHUTDOWN=YES&PARAMFORM=no&report=test.rdf&desformat=pdf&desname=test.pdf&destype=cache¶m1=56738&faces-redirect=true&userid=%3Dusername%2Fpasswd%40DBname
As we can see towards the end of the encoded URL, only the special characters like / have been encoded. i.e. userid=username/passwd@DBname has become userid=%3Dusername%2Fpasswd%40DBname
I want to generate a URL which will have the the entire string "username/passwd@DBname" encoded . Something like :
userid=%61%62
How can I achieve this?
A:
So in fact you want the url to become somewhat unreadable, without the need for decoding, Decoding would be needed for a Base64 encoding (with replacing / and -).
Yes you may abuse the URL encoding.
String encodeURL(String s) {
byte[] bytes = s.getBytes("UTF-8");
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
String hex = String.format("%%%02X", ((int)b) & 0xFF);
sb.append(hex);
}
return sb.toString();
}
%% being the percentage sign itself, and %02X hex, 2 digits, zero-filled, capitals.
Mind that some browsers will display such links decoded, on mouse-over. But you are just redirecting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Map Shiro's AuthenticationException with Jersey's ExceptionMapper
Preface
First of all, my sincerest apologies for this question being extremely long, but I honestly have no idea on how to shorten it, since each part is kind of a special case. Admittedly, I may be blind on this since I am banging my head against the wall for a couple of days now and I am starting to get desperate.
My utmost respect and thankfulness to all of you who read through it.
The aim
I would like to be able to map Shiro's AuthenticationException and it's subclasses to JAX-RS Responses by using Jersey ExceptionMappers, set up using a Guice 3.0 Injector which creates an embedded Jetty.
The environment
Guice 3.0
Jetty 9.2.12.v20150709
Jersey 1.19.1
Shiro 1.2.4
The setup
The embedded Jetty is created using a Guice Injector
// imports omitted for brevity
public class Bootstrap {
public static void main(String[] args) throws Exception {
/*
* The ShiroWebModule is passed as a class
* since it needs a ServletContext to be initialized
*/
Injector injector = Guice.createInjector(new ServerModule(MyShiroWebModule.class));
Server server = injector.getInstance(Server.class);
server.start();
server.join();
}
}
The ServerModule binds a Provider for the Jetty Server:
public class ServerModule extends AbstractModule {
Class<? extends ShiroWebModule> clazz;
public ServerModule(Class <?extends ShiroWebModule> clazz) {
this.clazz = clazz;
}
@Override
protected void configure() {
bind(Server.class)
.toProvider(JettyProvider.withShiroWebModule(clazz))
.in(Singleton.class);
}
}
The JettyProvider sets up a Jetty WebApplicationContext, registers the ServletContextListener necessary for Guice and a few things more, which I left in to make sure no "side effects" may be hidden:
public class JettyProvider implements Provider<Server>{
@Inject
Injector injector;
@Inject
@Named("server.Port")
Integer port;
@Inject
@Named("server.Host")
String host;
private Class<? extends ShiroWebModule> clazz;
private static Server server;
private JettyProvider(Class<? extends ShiroWebModule> clazz){
this.clazz = clazz;
}
public static JettyProvider withShiroWebModule(Class<? extends ShiroWebModule> clazz){
return new JettyProvider(clazz);
}
public Server get() {
WebAppContext webAppContext = new WebAppContext();
webAppContext.setContextPath("/");
// Set during testing only
webAppContext.setResourceBase("src/main/webapp/");
webAppContext.setParentLoaderPriority(true);
webAppContext.addEventListener(
new MyServletContextListener(injector,clazz)
);
webAppContext.addFilter(
GuiceFilter.class, "/*",
EnumSet.allOf(DispatcherType.class)
);
webAppContext.setThrowUnavailableOnStartupException(true);
QueuedThreadPool threadPool = new QueuedThreadPool(500, 10);
server = new Server(threadPool);
ServerConnector connector = new ServerConnector(server);
connector.setHost(this.host);
connector.setPort(this.port);
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(new NCSARequestLog());
HandlerCollection handlers = new HandlerCollection(true);
handlers.addHandler(webAppContext);
handlers.addHandler(requestLogHandler);
server.addConnector(connector);
server.setStopAtShutdown(true);
server.setHandler(handlers);
return server;
}
}
In MyServletContextListener, I created a child injector, which gets initialized with the JerseyServletModule:
public class MyServletContextListener extends GuiceServletContextListener {
private ServletContext servletContext;
private Injector injector;
private Class<? extends ShiroWebModule> shiroModuleClass;
private ShiroWebModule module;
public ServletContextListener(Injector injector,
Class<? extends ShiroWebModule> clazz) {
this.injector = injector;
this.shiroModuleClass = clazz;
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
this.servletContext = servletContextEvent.getServletContext();
super.contextInitialized(servletContextEvent);
}
@Override
protected Injector getInjector() {
/*
* Since we finally have our ServletContext
* we can now instantiate our ShiroWebModule
*/
try {
module = shiroModuleClass.getConstructor(ServletContext.class)
.newInstance(this.servletContext);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
/*
* Now, we create a child injector with the JerseyModule
*/
Injector child = injector.createChildInjector(module,
new JerseyModule());
SecurityManager securityManager = child
.getInstance(SecurityManager.class);
SecurityUtils.setSecurityManager(securityManager);
return child;
}
}
The JerseyModule, a subclass of JerseyServletModule now put everything together:
public class JerseyModule extends JerseyServletModule {
@Override
protected void configureServlets() {
bindings();
filters();
}
private void bindings() {
bind(DefaultServlet.class).asEagerSingleton();
bind(GuiceContainer.class).asEagerSingleton();
serve("/*").with(DefaultServlet.class);
}
private void filters() {
Map<String, String> params = new HashMap<String, String>();
// Make sure Jersey scans the package
params.put("com.sun.jersey.config.property.packages",
"com.example.webapp");
params.put("com.sun.jersey.config.feature.Trace", "true");
filter("/*").through(GuiceShiroFilter.class,params);
filter("/*").through(GuiceContainer.class, params);
/*
* Although the ExceptionHandler is already found by Jersey
* I bound it manually to be sure
*/
bind(ExceptionHandler.class);
bind(MyService.class);
}
}
The ExceptionHandler is extremely straightforward and looks like this:
@Provider
@Singleton
public class ExceptionHandler implements
ExceptionMapper<AuthenticationException> {
public Response toResponse(AuthenticationException exception) {
return Response
.status(Status.UNAUTHORIZED)
.entity("auth exception handled")
.build();
}
}
The problem
Now everything works fine when I want to access a restricted resource and enter correct principal/credential combinations. But as soon as enter a non-existing user or a wrong password, I want an AuthenticationException to be thrown by Shiro and I want it to be handled by the above ExceptionHandler.
Utilizing the default AUTHC filter provided by Shiro in the beginning, I noticed that AuthenticationExceptions are silently swallowed and the user is redirected to the login page again.
So I subclassed Shiro's FormAuthenticationFilter to throw an AuthenticationException if there is one:
public class MyFormAutheticationFilter extends FormAuthenticationFilter {
@Override
protected boolean onLoginFailure(AuthenticationToken token,
AuthenticationException e, ServletRequest request,
ServletResponse response) {
if(e != null){
throw e;
}
return super.onLoginFailure(token, e, request, response);
}
}
And I also tried it with throwing the exception e wrapped in a MappableContainerException.
Both approaches cause the same problem: Instead of the exception being handled by the defined ExceptionHandler, a javax.servlet.ServletException is thrown:
javax.servlet.ServletException: org.apache.shiro.authc.AuthenticationException: Unknown Account!
at org.apache.shiro.web.servlet.AdviceFilter.cleanup(AdviceFilter.java:196)
at org.apache.shiro.web.filter.authc.AuthenticatingFilter.cleanup(AuthenticatingFilter.java:155)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:148)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.shiro.guice.web.SimpleFilterChain.doFilter(SimpleFilterChain.java:41)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:163)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:58)
at com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:118)
at com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:113)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.apache.shiro.authc.AuthenticationException: Unknown Account!
at com.example.webapp.security.MyAuthorizingRealm.doGetAuthenticationInfo(MyAuthorizingRealm.java:27)
at org.apache.shiro.realm.AuthenticatingRealm.getAuthenticationInfo(AuthenticatingRealm.java:568)
at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doSingleRealmAuthentication(ModularRealmAuthenticator.java:180)
at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doAuthenticate(ModularRealmAuthenticator.java:267)
at org.apache.shiro.authc.AbstractAuthenticator.authenticate(AbstractAuthenticator.java:198)
at org.apache.shiro.mgt.AuthenticatingSecurityManager.authenticate(AuthenticatingSecurityManager.java:106)
at org.apache.shiro.mgt.DefaultSecurityManager.login(DefaultSecurityManager.java:270)
at org.apache.shiro.subject.support.DelegatingSubject.login(DelegatingSubject.java:256)
at org.apache.shiro.web.filter.authc.AuthenticatingFilter.executeLogin(AuthenticatingFilter.java:53)
at org.apache.shiro.web.filter.authc.FormAuthenticationFilter.onAccessDenied(FormAuthenticationFilter.java:154)
at org.apache.shiro.web.filter.AccessControlFilter.onAccessDenied(AccessControlFilter.java:133)
at org.apache.shiro.web.filter.AccessControlFilter.onPreHandle(AccessControlFilter.java:162)
at org.apache.shiro.web.filter.PathMatchingFilter.isFilterChainContinued(PathMatchingFilter.java:203)
at org.apache.shiro.web.filter.PathMatchingFilter.preHandle(PathMatchingFilter.java:178)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:131)
... 32 more
The question, after all
Given that the environment can't be changed, how can I achieve that a server instance still can be requested via Guice, while Shiro's exceptions are handled with Jersey's auto discovered ExceptionMappers?
A:
This question is much too complicated for me to reproduce on my side, but I saw a problem that I think is the answer and I'll delete this answer if I turn out to be wrong.
You do this:
@Provider
@Singleton
public class ExceptionHandler implements
ExceptionMapper<AuthenticationException> {
Which is correct, you are supposed to bind with both of those annotations as in this question. However, what you do differently is this:
/*
* Although the ExceptionHandler is already found by Jersey
* I bound it manually to be sure
*/
bind(ExceptionHandler.class);
The annotations in a class definition have lower priority than that in a module's configure() method, meaning you are erasing the annotations when you bind "it manually just to be sure". Try erasing that line of code and see if that fixes your problem. If it doesn't fix the problem, leave it deleted anyway, because I am certain that it is at least part of the problem - that statement erases those essential annotations.
| {
"pile_set_name": "StackExchange"
} |
Q:
Good ways to implement cutscenes in 2d RPG
I want to know of some different ways to implement cutscenes in a 2D RPG game with SDL2 and C++.
My current idea is creating different functions in different files for different cutscenes and running them whenever I need to show a cutscene.
However, this doesn't seem like a very easy or simple way to render cutscenes. How would I effeciently implement cutscenes?
A:
I personally implemented a cutscene "scripting" language for my cutscenes using XML. XML isn't necessarily the best choice, and since it's not a real scripting language with programming language features, it can be a little limiting, but for my needs it worked just fine.
My cutscene definition files look like this:
<CutScene disableBars="1" replayOnRestart="1">
<Parallel>
<CameraTarget tag="Bomb" time="1.0"/>
<DelayExecution time="0.4">
<CameraZoom zoom="4.0" time="0.6"/>
</DelayExecution>
</Parallel>
<Wait time="5.0"/>
<WaitForKey/>
</CutScene>
When I want to display a cutscene, I create a cutscene object, that is updated and rendered from my level class.
The cutscene object loads the file, and converts each XML element into an instruction, that gets updated. Only the current instruction gets executed, which is why a Parallel instruction exists. The instructions let the cutscene object know when the next instruction can be executed.
The instruction loading might look something like this (pseudo-C++):
void CutScene::Load()
{
XMLFile* file = new XMLFile(...);
for (XMLElement* element : file->GetElement("CutScene")->Children)
{
m_Instructions.push_back(InstructionFactory::Create(element));
}
}
Instruction* InstructionFactory::Create(XMLElement* element)
{
if (element->Name == "CameraTarget")
{
std::string tag = element->GetStringAttribute("tag");
float time = element->GetFloatAttribute("time");
return new CameraTargetInstruction(tag, time);
}
...
}
I use tags to reference entities in the level, so I have set the name of the bomb-entity in the level editor to "Bomb", and I use that same string to tell the camera zoom target instruction to center on the correct entity.
Creating cutscenes in a neat way can be a pain and a lot of work, but with a data-based approach like mine, you can improve your content interation speed, since you don't have to recompile every time you want to change the way a cutscene plays out.
You could of course look into integrating something like Lua into your framework/engine, but that can be a lot of work too.
The fastest approach to code might be just pure C++ code, but you'll get faster iteration speed with a data-based approach, and using a full-fledged scripting language will get you fast iteration speed and a lot of flexibility.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove an unwanted dynamic object from a dynamic footage
I need to remove an object (in my case - a newspaper) that is being hold by a man who moves it a bit from side to side and sometimes it is hidden behind some other objects. How do I do this?
My idea is to use rotobrush in After Effects and somehow fill it using 'content aware fill', but I cannot find anything like 'content aware fill' option. I have seen some tutorials on web about how to remove an object from a steady background, but this case is more complicated.
PS I don't want to mask it frame by frame in Photoshop.
A:
If the camera and background are both stationary (or perhaps very near stationary) you should be able to extrapolate a background plate from looking for frames where the man and paper are not blocking that part of the shot. Once you have that background plate, you can mask the newspaper and expose the appropriate portion of the background plate.
This works best if the camera isn't moving, though you may be able to do a camera tracking in the event of small camera movements and still get workable results by matching the position and angle of the background plate to the camera (though it will likely require far more advanced background plates to account for any perspective changes). With anything more than minimal movement of the camera though, the perspective changes will become too severe to compensate for and you won't be able to build a background plate from previous/future frames.
At that point, you would actually have to build a model of the scene in order to be able to render out the background to fill in with perspective adjustments and that would be far more complicated than re-shooting.
Note that this also does still require frame to frame adjustment of the mask and requires building the back plate by hand as well. It is still non-trivial, but isn't quite masking frame by frame in Photoshop since the rotoscope tool should work for it.
If shadows are visible on the background as well, then you may need to make some animated masks to emulate the shadows on the background plate as well. Either way, we're talking about a pretty elaborate operation most likely depending on the quality you need. If any shadows from the actor are visible though (particularly soft shadows against not flat objects) the quality level will drop like a rock and the complexity will go higher fast.
If you do get hit with shadow issues or background movement issues (and reshooting really isn't an option) you may actually be served best by replacing the background entirely). If you build a fixed background plate that doesn't have any shadows from the actors, people are not super likely to notice the lack of shadow compared to a gap in the shadow or a reconstructed shadow. It would involve even further rotoscoping, but might be easier than trying to build a believable shadow.
Reshooting really is the best option, even in the ideal case though.
| {
"pile_set_name": "StackExchange"
} |
Q:
what is the expected maximum number of balls in the same box
If I have $m$ distinct boxes, and $n$ distinct balls. I put all of these balls into the boxes with one box possibly containing more than one balls. What is the expected maximum number of balls in one box?
Appreciate your thoughts on solving this problem.
A:
This is answered in a paper by Raab and Steger (they switch your $n$ and $m$). The case $n=m$ is simpler and had been known before (see their introduction).
Intuitively, in order to find the "correct" answer, you calculate the expected number of bins $X_t$ which get at least $t$ balls; the value of $t$ such that $X_t \approx 1$ should be "close" to the expectation.
In order to make this rigorous, follow these steps:
Find a critical value $t_0$ such that if $t \ll t_0$ then the probability that a given box gets at least $t$ balls is very close to $1$, and if $t \gg t_0$ then it is very close to $0$.
When $t \gg t_0$, a union bound shows that with high probability no box gets at least $t$ balls.
When $t \ll t_0$, the expected number of boxes with at least $t$ balls is very close to $m$, and so the probability that no box gets at least $t$ balls is very small.
Deduce that most of the probability mass of the expectation is concentrated around $t_0$, and so the expectation itself is close to $t_0$.
When doing the calculations, we hit a problem in step 3: the number of expected boxes with at least $t$ balls is not $m$ but somewhat smaller. Raab and Steger show that the variable $X_t$ is concentrated around its expectation (using the "second moment method", i.e. Chebyshev's inequality), and so $\Pr[X_t = 0]$ is indeed small.
Most of the work is estimating the binomial distribution of the number of balls in each box, finding the correct $t_0$ for each case; the method fails when the number of balls is significantly smaller than the number of bins.
Here is some Sage code:
def analyze_partition(partition, bins):
last = partition[0]
counts = [1]
for part in partition[1:]:
if part != last:
last = part
counts += [1]
else:
counts[-1] += 1
counts.append(bins - sum(counts))
return multinomial(*partition) * multinomial(*counts)
def expected_max(balls, bins):
return sum([max(partition) * analyze_partition(partition, bins)
for partition in partitions(balls)
if len(partition) <= bins])/bins^balls
When plugging $10$ balls and $5$ bins, I get $$1467026/390625 \approx 3.76.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to initialize a multi-dimensional array in PHP presetting the keys
I have a constant defined as:
define('CONFIG_CODES', 'v1,v2,v3');
I want to initialize a multi-dimensional array using the config codes defined in my constant as the array keys. I have tried array_fill_keys() and a variety of other methods and I cannot get the array to initialize. The reason I want to initialize is to avoid Undefined index: v2 and Undefined offset: 0 in my PHP script results.
Here is what I want the initialization to look like:
Array
(
[v1] => Array
(
[0] =>
[1] =>
)
[v2] => Array
(
[0] =>
[1] =>
)
[v3] => Array
(
[0] =>
[1] =>
)
)
My Attempt:
$serviceTimes = array_fill_keys( array( CONFIG_CODES ), '' );
A:
Create an empty $initialized array, then loop through the exploded result of your constant value, using the exploded values as associative keys:
define('CONFIG_CODES', 'v1,v2,v3');
$initialized = array();
foreach(explode(',', CONFIG_CODES) as $val){
$initialized[$val] = array(
'val1',
'val2'
);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does networkx say my directed graph is disconnected when finding diameter?
I'm crawling slideshare.net graph, starting at my node and following all the users in BFS, until the number of visited nodes is 1000.
I perform BFS in the following way:
from urllib.request import urlopen
from collections import deque
import sys
import json
import codecs
import csv
import io
import hashlib
import time
import xml.etree.ElementTree as etree
queue = deque(["himanshutyagi11"])
while len_visitedset < 1ooo:
vertex = queue.pop()
if vertex in visited:
continue
visited.add(vertex)
length_visited = len(visited)
print(vertex,length_visited)
crawl(vertex)
crawl() is a function in which I make the slideshare api query as explained here create the query payload by using my shared_secret and api_key ( given at the time for api registration), send the query and parse the XML response stored in variable 'response'. After parsing, I add the contacts of the present node in the queue.
request_timestamp = int(time.time())
request_hash_string = shared_secret+str(request_timestamp)
request_hash_value = hashlib.sha1(request_hash_string.encode('utf-8')).hexdigest()
request_url = 'https://www.slideshare.net/api/2/get_user_contacts?username_for='+username+'&api_key='+api_key+'&hash='+request_hash_value+'&ts='+str(request_timestamp)
response = etree.parse(urlopen(request_url)).getroot()
# Append all the adjacent nodes of this user to the queue.
for child in response:
friend_name = child[0].text
queue.appendleft(friend_name)
edge_file = open('non_anonymized.csv','a')
for child in response:
f_name = child[0].text # Name of friend is stored in variable 'f_name'
edge_file.write(username+','+f_name+'\n') # username is the name of user currently being crawled
edge_file.close()
While crawling I also create a edgelist.csv file, that contains all the edges in the graph. This file seems to be fine.
Also other functions such as degree(), in_degree(), average_clustering() seem to be working fine.
Then I use networkx to create a graph, which has 1000 nodes. But if I try to find diameter of this graph using following function:
diameter = nx.diameter(graph)
With above code, I am not able to find the diameter of my graph, this doe not return anything and my program is stuck at this line. Any insights to what might be happening ?
Mine is a connected graph. I'm converting it to an undirected one using to_undirected() function. I tired running it with the directed graph, and I got the following error
networkx.exception.NetworkXError: Graph not connected: infinite path length
My question is how can it be disconnected since I am using BFS to crawl.
Python 3.4
Networkx 1.9.1
A:
The source code for diameter is here. It relies on eccentricity which is the function just above that in the source code. eccentricity finds the shortest path from a node to all other nodes. The error message you are getting comes from this part of the code:
if L != order:
msg = "Graph not connected: infinite path length"
raise networkx.NetworkXError(msg)
Here L is the number of nodes that were reachable from a given node and order is the number of nodes in the network. L != order means that there are nodes not reachable from the given node. In the case of an undirected network, this means the network is not connected. However in your case you have a directed network. For a directed network L != order means that the network is not "strongly-connected". It could actually be weakly-connected, and yours presumably is.
So you've hit an error message that is not quite accurate.
For the directed network you've created, the diameter is infinite: if there is a node u which has no path to v, this means an infinite diameter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a limit or max to the number of security rules in Firestore?
I need an application to support many users (>100,000). Each of those users will have access to a number of folders or paths. Each folder will need to be accessed by a number of users. (It is a many-to-many relationship.)
If I need to have 500,000+ security rules, will I run into a limit?
Thanks!
A:
There is a section under Firestore rules documentation which you can take a look, the recommendations you basically need to look at are:
Maximum number of expressions in a ruleset 10,000
Maximum size of a ruleset 64 KB
| {
"pile_set_name": "StackExchange"
} |
Q:
find an approximate solution, up to the order of epsilon
The question is to find an approximate solution, up to the order of epsilon of following problem.
$$y'' + y+\epsilon y^3 = 0$$
$$y(0) = a$$
$$y'(0) = 0$$
I tried to solve the given problem using perturbation theory.
$$y(t) = y_0(t) + \epsilon y_1(t) + \epsilon^2 y_2(t) + \cdots$$
$$t = w(\epsilon)t = (1 + \epsilon w_1 + \epsilon^2 w_2 + \cdots )t$$
However, i failed to find an appropriate approximate solution... help me!!
A:
You don't need a series for $t$, only $y$. So substitute $y=y_0+\epsilon y_1+\epsilon^2 y_2+\ldots$ into the equation:
$$ y_0''+\epsilon y_1''+\epsilon^2 y_2''+y_0+\epsilon y_1+\epsilon^2 y_2+\epsilon\left(y_0+\epsilon y_1+\epsilon^2 y_2\right)^3+O(\epsilon^3)=0. $$
You also have to expand the boundary conditions, which will give $y_0(0)=a$, and all other $y_i(0)=0$, and all $y_i'(0)=0$.
Now look at the equations for each magnitude of $\epsilon$. Firstly, the largest term is $O(1)$, and the equation is
$$ y_0''+y_0=0 $$
so $y_0=A\sin(t)+B\cos(t)$, and the boundary condition gives $y_0=a\cos(t)$. Then the $O(\epsilon)$ equation is
$$ y_1''+y_1+y_0^3=0,\ y_1(0)=y_1'(0)=0 $$
and the $O(\epsilon^2)$ equation is
$$ y_2''+y_2+3y_0^2y_1=0,\ y_2(0)=y_2'(0)=0, $$
at $O(\epsilon^3)$,
$$y_3''+y_3+3y_0^2y_2+3y_0y_1^2=0,\ y_3(0)=y_3'(0)=0 $$
and so on. You can solve these (remember $\cos(x)^3=3/4(\cos(3x)+3\cos(x))$) to give a series for $y$.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits