_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d6701 | train | All you need is to change the NumberFormatInfo.CurrencyPositivePattern and NumberFormatInfo.CurrencyNegativePattern properties for the culture.
Just clone the original culture:
CultureInfo swedish = new CultureInfo("sv-SE");
swedish = (CultureInfo)swedish.Clone();
swedish.NumberFormat.CurrencyPositivePattern = 3;
swedish.NumberFormat.CurrencyNegativePattern = 3;
and then
var value = 123.99M;
var result = value.ToString("C", swedish);
should give you desired result. This should get you:
123,99 kr
A: Be careful about the CurrencyNegativePattern
This code
CultureInfo swedish = new CultureInfo("sv-SE");
swedish = (CultureInfo)swedish.Clone();
swedish.NumberFormat.CurrencyPositivePattern = 3;
swedish.NumberFormat.CurrencyNegativePattern = 3;
Will give you
134,99 kr.
kr.134,99kr.-
Changing CurrencyNegativePattern to 8
swedish.NumberFormat.CurrencyNegativePattern = 8;
Will give you
134,99 kr.
-134,99 kr.
More info https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern(v=vs.110).aspx
A: string.Format(CultureInfo.CurrentCulture, "{0:C}", moneyValue.DataAmount) | unknown | |
d6702 | train | I'm not sure if this helpful for you but in java you can use the FindBy annotation like this
@FindBy (id="metrics-selector-container")
public WebElement DimensionPanel; | unknown | |
d6703 | train | You need import this:
from django.template import RequestContext
and then use it like so:
def example():
# Some code
return render_to_response('my_example.html', {
'Example_var':my_var
}, context_instance=RequestContext(request))
This will force a {% csrf_token %} to appear. | unknown | |
d6704 | train | Below is from the Net::FTP man page
new ([ HOST ] [, OPTIONS ])
This is the constructor for a new Net::FTP object. "HOST" is the
name of the remote host to which an FTP connection is required.
The string "x.x.x.x/newDirectory/" is not a valid host name.
You need to log into the FTP server, then change directory to newDirectory. The cwd method is what you need to use.
cwd ( [ DIR ] )
Attempt to change directory to the directory given in $dir. If
$dir is "..", the FTP "CDUP" command is used to attempt to move up
one directory. If no directory is given then an attempt is made to
change the directory to the root directory.
Try doing something like this (untested)
use Net::FTP;
my $host="x.x.x.x";
$ftp = Net::FTP->new->($host,Debug => 0) or die;
$ftp->login("username2",'password2') or die;
$ftp->cwd("newDirectory"); | unknown | |
d6705 | train | Please find a simple set of configurations on setting up multiple API Manager nodes with a single IS as Key Manager. It is required to front the API Manager nodes with a load balancer (with sticky sessions enabled & data-sources are shared among all the nodes) and configure the API Manager nodes as follows
API Manager Nodes: api-manager.xml (assumption IS-KM port offset 1, therefore 9444)
<AuthManager>
<!-- Server URL of the Authentication service -->
<ServerURL>https://localhost:9444/services/</ServerURL>
...
</AuthManager>
...
<APIKeyValidator>
<!-- Server URL of the API key manager -->
<ServerURL>https://localhost:9444/services/</ServerURL>
...
</APIKeyValidator>
IS Key Manager Node: api-manager.xml
<APIGateway>
<Environments>
<Environment type="hybrid" api-console="true">
...
<!-- Server URL of the API gateway -->
<ServerURL>https://loadbalancer/services/</ServerURL>
...
</APIGateway>
Sample NGINX
upstream mgtnode {
server localhost:9443; # api manager node 01
server localhost:9443; # api manager node 02
}
server {
listen 443;
server_name mgtgw.am.wso2.com;
proxy_set_header X-Forwarded-Port 443;
...
location / {
...
proxy_pass https://mgtnode;
}
}
References
*
*Configuring IS as Key Manager | unknown | |
d6706 | train | I have tested this and it works for me but your mileage may vary.
import sys, locale
Gr_text = raw_input('Type your message below:\n').decode(sys.stdin.encoding or locale.getpreferredencoding(True))
Gr = Gr_text.split()
print Gr
“Full Disclosure” credit goes to https://stackoverflow.com/a/477496/1427800 | unknown | |
d6707 | train | First off, the Windows path separator is \ but not /.
Then you need to get aware that there is a current directory for every drive to fully understand what is going on.
But anyway, here is an adapted version of your code with some explanations:
rem /* This changes to the root directory of the drive you are working on (say `C:`);
rem note that I replaced `/` by `\`, which is the correct path separator: */
cd \
rem /* This changes the current directory of drive `D:` to the current directory of drive `D:`,
rem note that this does NOT switch to the specified drive as there is no `/D` option: */
cd D:
rem /* This is actually the same as `cd programming` and changes to the sub-directory
rem `programming` of your current working directory: */
cd programming\
rem /* The final working directory is now `C:\programming`, assuming that the original
rem working drive was `C:`. */
However, what I think you are trying to achieve is the following:
rem // This switches to the drive `D:`; regard that there is NO `cd` command:
D:
rem // This changes to the root directory of the drive you are working on, which is `D:`:
cd \
rem // This changes into the directory `programming`:
cd programming
rem // The final working directory is now `D:\programming`.
This can be shortened to:
D:
cd \programming
Or even this:
rem // Note the `/D` option that is required to also switch to the given drive:
cd /D D:\programming
A: When you use
cd d:
the current directory of D: may not be D:\
To set the root you need to use CD D:\
In Windows, use backslashes | unknown | |
d6708 | train | this is how I do it. I had to go a level deeper than _app.tsx because I'm using NextJS ISR and needed data that is accessible at build time.
My useSettings hook is simply reading from localstorage, but you could use redux or whatever to get your settings.
import React, { ReactNode } from 'react';
import { ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import buildTheme from '../../theme';
import useSettings from '../../hooks/useSettings';
interface DisplayProps {
children: ReactNode;
}
export const Display: React.FC<DisplayProps> = ({ children }) => {
let prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const { settings } = useSettings();
const theme = React.useMemo(() => {
if (settings.theme && settings.theme!=='system') {
prefersDarkMode = settings.theme === 'dark';
}
return buildTheme(prefersDarkMode, {
direction: settings.direction,
responsiveFontSizes: settings.responsiveFontSizes,
theme: settings.theme,
});
}, [prefersDarkMode, settings]);
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
);
};
export default Display;
theme.ts
import { createTheme, responsiveFontSizes } from '@material-ui/core';
export const commonThemeSettings = {
breakpoints: {
keys: ['xs', 'sm', 'md', 'lg', 'xl'],
values: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920 },
},
direction: 'ltr',
mixins: {
toolbar: {
minHeight: 56,
'@media (min-width:0px) and (orientation: landscape)': {
minHeight: 48,
},
'@media (min-width:600px)': { minHeight: 64 },
},
},
typography: {
htmlFontSize: 16,
fontFamily: '"SharpBook19", "Helvetica", "Arial", sans-serif',
fontSize: 14,
fontWeightLight: 400,
fontWeightRegular: 400,
fontWeightMedium: 400,
fontWeightBold: 400,
h1: {
fontSize: '3rem',
},
h2: {
fontSize: '2.5rem',
},
h3: {
fontSize: '2.25rem',
},
h4: {
fontSize: '2rem',
},
h5: {
fontSize: '1.5rem',
},
shape: { borderRadius: 0 },
},
palette: {
primary: {
light: '#7986cb',
main: '#3f51b5',
dark: '#303f9f',
contrastText: '#fff',
},
secondary: {
light: '#ff4081',
main: '#f50057',
dark: '#c51162',
contrastText: '#fff',
},
error: {
light: '#e57373',
main: '#f44336',
dark: '#d32f2f',
contrastText: '#fff',
},
warning: {
light: '#ffb74d',
main: '#ff9800',
dark: '#f57c00',
contrastText: 'rgba(0, 0, 0, 0.87)',
},
info: {
light: '#64b5f6',
main: '#2196f3',
dark: '#1976d2',
contrastText: '#fff',
},
success: {
light: '#81c784',
main: '#4caf50',
dark: '#388e3c',
contrastText: 'rgba(0, 0, 0, 0.87)',
},
grey: {
50: '#fafafa',
100: '#f5f5f5',
200: '#eeeeee',
300: '#e0e0e0',
400: '#bdbdbd',
500: '#9e9e9e',
600: '#757575',
700: '#616161',
800: '#424242',
900: '#212121',
A100: '#d5d5d5',
A200: '#aaaaaa',
A400: '#303030',
A700: '#616161',
},
contrastThreshold: 3,
tonalOffset: 0.2,
action: {
disabledOpacity: 0.38,
focusOpacity: 0.12,
},
},
};
export const lightPalette = {
type: 'light',
text: {
primary: 'rgba(0, 0, 0, 0.87)',
secondary: 'rgba(0, 0, 0, 0.54)',
disabled: 'rgba(0, 0, 0, 0.38)',
hint: 'rgba(0, 0, 0, 0.38)',
},
divider: 'rgba(0, 0, 0, 0.12)',
background: { paper: '#fff', default: '#fafafa' },
action: {
active: 'rgba(0, 0, 0, 0.54)',
hover: 'rgba(0, 0, 0, 0.04)',
hoverOpacity: 0.04,
selected: 'rgba(0, 0, 0, 0.08)',
selectedOpacity: 0.08,
disabled: 'rgba(0, 0, 0, 0.26)',
disabledBackground: 'rgba(0, 0, 0, 0.12)',
focus: 'rgba(0, 0, 0, 0.12)',
activatedOpacity: 0.12,
},
};
export const darkPalette = {
type: 'dark',
text: {
primary: '#fff',
secondary: 'rgba(255, 255, 255, 0.7)',
disabled: 'rgba(255, 255, 255, 0.5)',
hint: 'rgba(255, 255, 255, 0.5)',
icon: 'rgba(255, 255, 255, 0.5)',
},
divider: 'rgba(255, 255, 255, 0.12)',
background: { paper: '#424242', default: '#303030' },
action: {
active: '#fff',
hover: 'rgba(255, 255, 255, 0.08)',
hoverOpacity: 0.08,
selected: 'rgba(255, 255, 255, 0.16)',
selectedOpacity: 0.16,
disabled: 'rgba(255, 255, 255, 0.3)',
disabledBackground: 'rgba(255, 255, 255, 0.12)',
focus: 'rgba(255, 255, 255, 0.12)',
activatedOpacity: 0.24,
},
};
const theme = (preferDark, additionalOptions) => {
let theme = createTheme({
...commonThemeSettings,
palette: preferDark
? { ...darkPalette, ...commonThemeSettings.palette }
: { ...lightPalette, ...commonThemeSettings.palette },
...additionalOptions,
});
if (additionalOptions && additionalOptions.responsiveFontSizes) {
theme = responsiveFontSizes(theme);
}
return theme;
};
export default theme; | unknown | |
d6709 | train | I would suggest two optimizations : 1) store the value of the set bit in the table instead. 2) Don't store each bit in an array but compute it on the fly instead. The result is the same, but it's probably a little bit faster.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define lutsize 8
static const uint8_t lutn[lutsize][4] = {
{1, 2, 4, 8},
{2, 1, 8, 4},
{4, 8, 1, 2},
{8, 4, 2, 1},
{1, 4, 2, 8},
{2, 8, 1, 4},
{4, 1, 8, 2},
{8, 2, 4, 1}};
uint32_t getMin(uint32_t in, uint32_t* ptr)
{
uint32_t pos, i, tmp, min;
uint8_t bits[expn];
tmp = in;
min = in;
for (pos = 0; pos < lutsize; ++pos){
tmp = 0;
for (i = 0; i < expn; ++i) {
// If the bit is set
if (in & (1<<i))
// get the value of the permuted bit in the table
tmp = tmp | lutn[pos][i];
}
ptr[pos] = tmp;
//printf("%d: %d\n", pos, tmp);
if (tmp<min) { min = tmp; } // track minimum
}
//printf("min: %d\n", min);
return min;
}
void main(int argc, const char * argv[]) {
uint32_t *ptr;
ptr = (uint32_t*) malloc(lutsize * sizeof(uint32_t));
getMin(5, ptr);
}
A: It seems to me that, not having all the possible permutations, you need to check all of those you have. Calculating the best permutation is not fruitful if you aren't sure that permutation is available.
So, the two optimizations remaining you can hope for are:
*
*Stop the search if you achieve a minimum.
For example, if I have understood, you have the binary number 11001101. What is the minimum permutation value? Obviously 00011111, with all ones to the right. What exact permutation does this for you - whether the last 1 is the first, second, fifth, sixth or eight bit - matters not to you.
As soon as a permutation hits the magic value, that is the minimum and you know you can do no better, so you can just as well stop searching.
In your own example you hit the minimum value 3 (or 0011, which is the minimum from 1001 or 5) at iteration 4. You gained nothing from iterations five to seven.
*If you have 1101, Go from { 0, 1, 3, 2 } to the bit-permutated value "1110" as fast as possible.
Not sure about the performances, but you could try precalculating the values from the table, even if this requires a 32x32 = 1024 32-value table - 4M of memory.
Considering the first position (our number is 1101), the permutation can have in position 0 only these values: 0, 1, 2, or 3. These have a value of 1___, 1___, 0___ or 1___. So our position 0 table is { 1000, 1000, 0000, 1000 }.
The second position is identical: { 1_, 1_, 0_, 1_ } and so we have { 0100, 0100, 0000, 0100 }.
The next two rows are { 0010, 0010, 0000, 0010 }
{ 0001, 0001, 0000, 0001 }.
Now, you want to calculate the value if permutation { 3, 0, 1, 2 } is applied:
for (i = 0; i < 4; i++) {
value |= table[i][permutation[i]];
}
===
But (again, if I understood the problem), let us say that the number has one fourth zeroes (it is made up of 24 1's, 8 0's) and the table is sizeable enough.
There is a very significant chance that you very soon hit both a permutation that puts a bit 1 in the 31st position, yielding some 2 billion, and another that puts a 0 there, yielding one billion.
The minimum will then surely be below two billions, so from now on, as soon as you check the first permutated bit and find it is a 1, you can stop calculating, you won't get a better minimum out of that permutation. Skip immediately to the next.
If you do this check at every cycle instead of only the first,
for (i = 0; i < 4; i++) {
value |= table[i][permutation[i]];
if (value > minimum) {
break;
}
}
I fear that you might eat any gains, but on the other hand, since values are automatically ordered in descending order, the first bits would get eliminated the most, avoiding the subsequent checks. It might be worth checking.
Nothing stops you from doing the calculation in two steps:
for (i = 0; i < 8; i++) {
value |= table[i][permutation[i]];
if (value > minimum) {
break;
}
}
if (value < minimum) {
for (; i < 32; i++) {
value |= table[i][permutation[i]];
}
} | unknown | |
d6710 | train | If I change to driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password")) from driver = GraphDatabase.driver("bolt://192.168.1.90:7687", auth=("neo4j", "password")), then it works well. Who can explain WHY?
Debug Log changed TO
2018-03-09 12:55:47,944 ~~ [CONNECT] ('::1', 7687, 0, 0)
2018-03-09 12:55:47,945 ~~ [SECURE] ::1
2018-03-09 12:55:47,951 C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:55:47,953 S: [HANDSHAKE] 1
FROM
2018-03-09 12:40:56,212 ~~ [CONNECT] ('192.168.1.90', 7687)
2018-03-09 12:40:56,213 ~~ [SECURE] 192.168.1.90
018-03-09 12:40:56,221 C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:40:56,224 S: [HANDSHAKE] 1 | unknown | |
d6711 | train | Welcome to Asynchronous Javascript, friend!
All your connection.query methods are actually running at the same time, because they are asynchronous functions. This is something you're going to have to get used to, along with callbacks. As a result, none of your "check" queries have actually finished before the "insert" queries begin.
You will have to define the precise order which your functions have to follow, and then use the Async library accordingly (look for Async.series, Async.parallel and Async.waterfall).
Asynchronous JS can be tough to grasp at first, but can do wonders on your response time once you get the hang of it. | unknown | |
d6712 | train | Add calculated table:
Calendar =
GENERATE (
CALENDAR (
DATE ( 2016, 1, 1 ),
DATE ( 2020, 12, 31 )
),
VAR VarDates = [Date]
VAR VarDay = DAY ( VarDates )
VAR VarMonth = MONTH ( VarDates )
VAR VarYear = YEAR ( VarDates )
VAR YM_text = FORMAT ( [Date], "yyyy-MM" )
VAR Y_week = YEAR ( VarDates ) & "." & WEEKNUM(VarDates)
RETURN
ROW (
"day" , VarDay,
"month" , VarMonth,
"year" , VarYear,
"YM_text" , YM_text,
"Y_week" , Y_week
)
)
You can customize it. In relation pane connect your Date field of FactTable (which is by week, as you say. This table can have missing dates and duplicate dates, to be precise) to the field Date of the Calendar table (which has unique Date, by day). Then, in all your visuals or measures always use the the Date field of the Calendar table. It is a good practice to hide the field Date in your FactTable.
More explanations here https://stackoverflow.com/a/54980662/1903793 | unknown | |
d6713 | train | myProg<-function(code) db$city[db$code==code]
A: This is a filtering question. There are a number of ways to filter data in R. Here's what you need to do:
*
*Put your data in a data.frame
*Try filtering it:
*Now make it a function (this is your program)
*Use the function
postal_codes <- data.frame(code = c(78754, 84606), location = c("Austin", "Provo"))
postal_codes[postal_codes$code %in% 78754, ]
postal_finder <- function(mycode) {
postal_codes$location[postal_codes$code %in% mycode]
}
postal_finder(78754) | unknown | |
d6714 | train | Get the text of label when checkbox .is(':checked')
var text = null;
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
var text = $(this).next('label').text();
alert(text);
} else {
alert(text);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-cell col1 row1 component-sortable component-droppable ui-block-a" style="width:48%; text-align: left; vertical-align: top;" data-col="1" data-row="1">
<style>
label[for="checkbox-1"].ui-checkbox-on {}
label[for="checkbox-1"].ui-checkbox-off {}
</style>
<div data-control-type="checkbox" data-control-id="checkbox-1" data-control-name="checkbox-1" data-object-column="A">
<input type="checkbox" name="checkbox-1" id="checkbox-1" data-theme="a">
<label for="checkbox-1" data-translatable="Noise [A]">Noise [A]</label>
</div>
Second Example:
You can store name if checked or unchecked in an array:
var store = new Array();
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
var text = $(this).next('label').text();
store.push(text);
} else {
var removeItem = $(this).next('label').text();
store = $.grep(store, function(value) {
return value != removeItem;
});
}
console.log(store);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-cell col1 row1 component-sortable component-droppable ui-block-a" style="width:48%; text-align: left; vertical-align: top;" data-col="1" data-row="1">
<style>
label[for="checkbox-1"].ui-checkbox-on {}
label[for="checkbox-1"].ui-checkbox-off {}
</style>
<div data-control-type="checkbox" data-control-id="checkbox-1" data-control-name="checkbox-1" data-object-column="A">
<input type="checkbox" name="checkbox-1" id="checkbox-1" data-theme="a">
<label for="checkbox-1" data-translatable="Noise [A]">Noise [A]</label>
</div>
A: You can try below code
var test = "";
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
test = $(this).next('label').text();
console.log("test value: " + test)
} else {
test = "";
console.log("test value: " + test)
}
});
body {
font: 13px Verdana;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-cell col1 row1 component-sortable component-droppable ui-block-a" style="width:48%; text-align: left; vertical-align: top;" data-col="1" data-row="1">
<div data-control-type="checkbox" data-control-id="checkbox-1" data-control-name="checkbox-1" data-object-column="A">
<input type="checkbox" name="checkbox-1" id="checkbox-1" data-theme="a">
<label for="checkbox-1" data-translatable="Noise [A]">Noise [A]</label>
</div>
</div> | unknown | |
d6715 | train | You simply need to create a repository, service and controller.
1. First, let's create repositories for our models.
public interface CustomerRepository extends JpaRepository<Customer, Long> {}
public interface ProductRepository extends JpaRepository<Product, Long> {}
public interface OrderRepository extends JpaRepository<Order, Long> {}
2. Second, let's create our service layer.
(Note: I gathered all the functionality here for an example.You can distribute it to different layers.)
public interface OrderService {
List<Customer> findAllCustomers();
List<Product> findAllProducts();
List<Order> findAllOrders();
}
@Service
public class OrderServiceImpl implements OrderService {
private final CustomerRepository customerRepository;
private final ProductRepository productRepository;
private final OrderRepository orderRepository;
public OrderServiceImpl(CustomerRepository customerRepository,
ProductRepository productRepository,
OrderRepository orderRepository) {
this.customerRepository = customerRepository;
this.productRepository = productRepository;
this.orderRepository = orderRepository;
}
@Override
public List<Customer> findAllCustomers() {
return customerRepository.findAll();
}
@Override
public List<Product> findAllProducts() {
return productRepository.findAll();
}
@Override
public List<Order> findAllOrders() {
return orderRepository.findAll();
}
}
3. Now add a controller layer, this will reply to your urls. (Note: here are simple examples just to help you understand the operation. You can come up with many different solutions.)
@Controller
@RequestMapping("/order")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping("/create")
public String createOrder(Model model) {
model.addAttribute("customers", orderService.findAllCustomers());
model.addAttribute("products", orderService.findAllProducts());
model.addAttribute("order", new Order());
return "order-form";
}
@PostMapping("/insert")
public String insertOrder(Model model, Order order) {
// Save operations ..
return "order-view";
}
}
4. Here, customers and products come from your database.
The 'Submit Form' button will be sending the entity id's of the selections here to the insertOrder method. (You can duplicate your other fields in a similar way and I recommend you to examine the example in this link to dynamically duplicate this product selection area.)
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div>
<form action="/order/insert" method="post" th:object="${order}">
<p>
<label>Select Customer</label>
</p>
<p>
<select name="customer.id">
<option th:each="customer : ${customers}"
th:value="${customer.id}"
th:text="${customer.name}">Customer Name</option>
</select>
</p>
<p>
<label>Select Product</label>
</p>
<p>
<select name="orderItems[0].product.id">
<option th:each="product : ${products}"
th:value="${product.id}"
th:text="${product.name}">Product Name</option>
</select>
<input type="text" name="orderItems[0].quantity" />
</p>
<button type="submit">Submit Form</button>
</form>
</div>
</body>
</html>
I recommend you to read this example, which has scope for necessary library and spring settings. | unknown | |
d6716 | train | You could have a temporary variable which will count the time using dt, and when it exceeds the time limit (5s ?) then set it back to 0;
AFRAME.registerComponent("foo", {
init: function() {
this.timer = 0
this.flip = false
},
tick(function(time, dt) {
this.timer += dt
if (this.timer > 1000) {
console.log("second has passed")
if (flip)
//fadein
else
//fadeout
this.flip = !this.flip
this.timer = 0
}
}
}
live fiddle here | unknown | |
d6717 | train | I just answered on another similar question, link here. Any improvements to this will be made for the linked answer, so check there first.
GitHub link of this (but more advanced) in a Swift Package here
However, here is the answer with the same TupleView extension, but different view code.
Usage:
struct ContentView: View {
var body: some View {
BoxWithDividerView {
Text("Something 1")
Text("Something 2")
Text("Something 3")
Image(systemName: "circle") // Different view types work!
}
}
}
Your BoxWithDividerView:
struct BoxWithDividerView: View {
let content: [AnyView]
init<Views>(@ViewBuilder content: @escaping () -> TupleView<Views>) {
self.content = content().getViews
}
var body: some View {
VStack(alignment: .center, spacing: 0) {
ForEach(content.indices, id: \.self) { index in
if index != 0 {
Divider()
}
content[index]
}
}
// .background(Color.black)
.cornerRadius(14)
}
}
And finally the main thing, the TupleView extension:
extension TupleView {
var getViews: [AnyView] {
makeArray(from: value)
}
private struct GenericView {
let body: Any
var anyView: AnyView? {
AnyView(_fromValue: body)
}
}
private func makeArray<Tuple>(from tuple: Tuple) -> [AnyView] {
func convert(child: Mirror.Child) -> AnyView? {
withUnsafeBytes(of: child.value) { ptr -> AnyView? in
let binded = ptr.bindMemory(to: GenericView.self)
return binded.first?.anyView
}
}
let tupleMirror = Mirror(reflecting: tuple)
return tupleMirror.children.compactMap(convert)
}
}
Result:
A: So I ended up doing this
@_functionBuilder
struct UIViewFunctionBuilder {
static func buildBlock<V: View>(_ view: V) -> some View {
return view
}
static func buildBlock<A: View, B: View>(
_ viewA: A,
_ viewB: B
) -> some View {
return TupleView((viewA, Divider(), viewB))
}
}
Then I used my function builder like this
struct BoxWithDividerView<Content: View>: View {
let content: () -> Content
init(@UIViewFunctionBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack(spacing: 0.0) {
content()
}
.background(Color(UIColor.AdUp.carbonGrey))
.cornerRadius(14)
}
}
But the problem is this only works for up to 2 expression views. I’m gonna post a separate question for how to be able to pass it an array | unknown | |
d6718 | train | You can use Regex to get different data from MongoDB. To get model AXXX and A_status is VALID you can use this query.
{
device_model: { $regex :/^A/},
A_status: 'VALID'
}
To get BXXX and B_status is VALID you can use:
{
device_model: { $regex :/^B/},
B_status: 'VALID'
}
It may be useful to take a look into mongo regex documentation.
A: Use $or
db.collection.find({
$or: [
{
A_status: "VALID",
device_model: {
$in: [
"A001",
"A003"
]
}
},
{
B_status: "VALID",
device_model: {
$in: [
"B001",
"B002"
]
}
}
]
})
mongoplayground | unknown | |
d6719 | train | I found the solution for this question. We need to use filter in screen in top corner | unknown | |
d6720 | train | You have two options:
*
*Make two overloads of the Validate method. One that is synchronous and one that is asynchronous and cancellable.
*Change your Validate method so that the calling code is responsible for looping over the files (consider an iterator method, using yield)
I'd go with option 1 as it is a smaller change. | unknown | |
d6721 | train | When you want to inject the session into the HTTP request, you must mimic the standard behavior. Depending on how your session works, this means either adding the session cookie or the session get parameter.
drupal_http_request()Docs allows you to specify headers. You can for example build the cookie header for your session and then send it with the request.
To see how the cookie header is build, analyse the request-headers your browser sends to your drupal site, you can do that with firebug. Look for the Cookie: header in the request headers. Note that it can differ depending on server configuration.
You then can add the cookie information to the $headers parameter:
$headers = array('Cookie' => 'your sessionid cookie data');
drupal_http_request($url, $headers); | unknown | |
d6722 | train | I think you want
list.stream().collect(groupingBy(Foo::getBar,
mapping(Foo::getBaz, toList())));
Where getBaz is the "downstream collector" which transforms the grouped Foos, then yet another which creates the list.
A: You're close, you'll need to supply a "downstream" collector to further refine your criteria. in this case the groupingBy approach along with a mapping downstream collector is the idiomatic approach i.e.
list.stream().collect(groupingBy(Foo::getBar, mapping(Foo::getBaz, toList())));
This essentially works by applying a mapping downstream collector to the results of the classification (Foo::getBar) function.
basically what we've done is map each Foo object to Baz and puts this into a list.
Just wanted to show another variant here, although not as readable as the groupingBy approach:
foos.stream()
.collect(toMap(Foo::getBar, v -> new ArrayList<>(singletonList(v.getBaz())),
(l, r) -> {l.addAll(r); return l;}));
*
*Foo::getBar is the keyMapper function to extract the map keys.
*v -> new ArrayList<>(singletonList(v)) is the valueMapper
function to extract the map values.
*(l, r) -> {l.addAll(r); return l;} is the merge function used to
combine two lists that happen to have the same getBar value.
A: To change the classic grouping to a Map<Bar, List<Foo>> you need to use the method which allows to change the values of the map :
*
*the version with a downstream Collectors.groupingBy(classifier, downstream)
*which is a mapping operation Collectors.mapping(mapper, downstream)
*which requires another operation to set the container Collectors.toList()
//Use the import to reduce the Collectors. redundancy
//import static java.util.stream.Collectors.*;
Map<Bar, List<Baz>> mapBarToFoos =
foos.stream().collect(groupingBy(Foo::getBar, mapping(Foo::getBaz, toList())));
//without you'll get
Map<Bar, List<Baz>> mapBarToFoos =
foos.stream().collect(Collectors.groupingBy(Foo::getBar, Collectors.mapping(Foo::getBaz, Collectors.toList()))); | unknown | |
d6723 | train | According to the Apple's Location Awareness Programming Guide You can achieve this using a CLGeocoder object:
CLGeocoder* geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:@"Your Address"
completionHandler:^(NSArray* placemarks, NSError* error){
for (CLPlacemark* aPlacemark in placemarks)
{
// Process the placemark.
}
}];
A CLPlacemark object has a property called location that yields latitude and longitude for the place.
A: You can use this function to get (latitude, longitude) tuple on the django side
import urllib, urllib2
import simplejson as json
def getLatLng( address ):
""" Native address format is House Number, Street Direction, Street Name,
Street Suffix, City, State, Zip, Country """
TIMEOUT = 3
try:
url = "http://maps.google.com/maps/api/geocode/json?address=" + urllib.quote_plus( address.encode('utf-8') ) + "&sensor=false"
opener = urllib2.build_opener()
req = urllib2.Request( url )
data = json.load( opener.open(req, None, TIMEOUT) )
results = data['results']
if len( results ):
location = results[0]['geometry']['location']
return ( location['lat'], location['lng'] )
else:
return None
except:
return None
A: Use the below link,this will return json which consist of latitude and longitude for the physical address.
http://maps.google.com/maps/api/geocode/json?address=Newyork&sensor=false | unknown | |
d6724 | train | I doubt you will get any useful answers in this forum, which concerns itself with programming questions. But you might want to try this discussion group, which seems to be just what you want. | unknown | |
d6725 | train | See this answer on how to connect to TimesTen via Python:
python access to TimesTen
Use cx_Oracle via tnsnames.ora as this is the method that Oracle will support in TimesTen 18.1.3
Please avoid using any ODBC based method to connect to Python as none of these techniques are developed or tested by Oracle. | unknown | |
d6726 | train | The most important thing here is that you cannot sign a billing agreement without a billing plan
So the first thing you need to consider is how you could create a plan.
Its very simple just trigger this api: https://developer.paypal.com/docs/api/payments.billing-plans/v1/
Now you have your plan Id
now you can subscribe a user with this plan id
by triggering this API
https://developer.paypal.com/docs/api/payments.billing-agreements/v1/#billing-agreements_create | unknown | |
d6727 | train | Take a look into the Islands and Gaps problem and Itzik Ben-gan. There is a set based way to get the results you want.
I was looking into using ROW_NUMBER or RANK, but then I stumbled upon LAG and LEAD (introduced in SQL 2012) which are nice. I've got the solution below. It could definitely be simplified, but having it as several CTEs makes my thought process (as flawed as it may be) easier to see. I just slowly transform the data into what I want. Uncomment one select at a time if you want to see what each new CTE produces.
create table Junk
(aDate Datetime,
aLocation varchar(32))
insert into Junk values
('2000', 'Location1'),
('2001', 'Location1'),
('2002', 'Location1'),
('2004', 'Unknown'),
('2005', 'Unknown'),
('2006', 'Unknown'),
('2007', 'Location2'),
('2008', 'Location2'),
('2009', 'Location2'),
('2010', 'Location2'),
('2011', 'Location1'),
('2012', 'Location1'),
('2013', 'Location1'),
('2014', 'Location3')
;WITH StartsMiddlesAndEnds AS
(
select
aLocation,
aDate,
CASE(LAG(aLocation) OVER (ORDER BY aDate, aLocation)) WHEN aLocation THEN 0 ELSE 1 END [isStart],
CASE(LEAD(aLocation) OVER (ORDER BY aDate, aLocation)) WHEN aLocation THEN 0 ELSE 1 END [isEnd]
from Junk
)
--select * from NumberedStartsMiddlesAndEnds
,NumberedStartsAndEnds AS --let's get rid of the rows that are in the middle of consecutive date groups
(
select
aLocation,
aDate,
isStart,
isEnd,
ROW_NUMBER() OVER(ORDER BY aDate, aLocation) i
FROM StartsMiddlesAndEnds
WHERE NOT(isStart = 0 AND isEnd = 0) --it is a middle row
)
--select * from NumberedStartsAndEnds
,CombinedStartAndEnds AS --now let's put the start and end dates in the same row
(
select
rangeStart.aLocation,
rangeStart.aDate [aStart],
rangeEnd.aDate [aEnd]
FROM NumberedStartsAndEnds rangeStart
join NumberedStartsAndEnds rangeEnd ON rangeStart.aLocation = rangeEnd.aLocation
WHERE rangeStart.i = rangeEnd.i - 1 --consecutive rows
and rangeStart.isStart = 1
and rangeEnd.isEnd = 1
)
--select * from CombinedStartAndEnds
,OneDateIntervals AS --don't forget the cases where a single row is both a start and end
(
select
aLocation,
aDate [aStart],
aDate [aEnd]
FROM NumberedStartsAndEnds
WHERE isStart = 1 and isEnd = 1
)
--select * from OneDateIntervals
select aLocation, DATEPART(YEAR, aStart) [start], DATEPART(YEAR, aEnd) [end] from OneDateIntervals
UNION
select aLocation, DATEPART(YEAR, aStart) [start], DATEPART(YEAR, aEnd) [end] from CombinedStartAndEnds
ORDER BY DATEPART(YEAR, aStart)
and it produces
aLocation start end
Location1 2000 2002
Unknown 2004 2006
Location2 2007 2010
Location1 2011 2013
Location3 2014 2014
Don't have 2012? Then you can still get the same StartsMiddlesAndEnds CTE using ROW_NUMBER:
;WITH NumberedRows AS
(
SELECT aLocation, aDate, ROW_NUMBER() OVER (ORDER BY aDate, aLocation) [i] FROM Junk
)
,StartsMiddlesAndEnds AS
(
select
currentRow.aLocation,
currentRow.aDate,
CASE upperRow.aLocation WHEN currentRow.aLocation THEN 0 ELSE 1 END [isStart],
CASE lowerRow.aLocation WHEN currentRow.aLocation THEN 0 ELSE 1 END [isEnd]
from
NumberedRows currentRow
left outer join NumberedRows upperRow on upperRow.i = currentRow.i-1
left outer join NumberedRows lowerRow on lowerRow.i = currentRow.i+1
)
--select * from StartsMiddlesAndEnds | unknown | |
d6728 | train | boost::archive's save and load methods understand the difference between pointers and object references. You don't need to specify *m_elem. m_elem will do (and work correctly). Boost will understand if the pointer is null and will simply store a value indicating a null pointer, which will be deserialised correctly.
(simplified) example:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_free.hpp>
struct A {
A() : a(0) {}
A(int aa) : a(aa) {}
int a;
template <class Archive>
void serialize(Archive& ar, const unsigned int /*version*/)
{
ar& BOOST_SERIALIZATION_NVP(a);
}
};
std::ostream& operator<<(std::ostream& os, const A& a) {
os << "A{" << a.a << "}";
return os;
}
template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
Ptr()
: m_elem(0)
{}
Ptr(T elem)
: m_elem(new T(elem))
{
}
private:
// no copies
Ptr(const Ptr&);
Ptr& operator=(const Ptr&);
public:
// delete is a NOP when called with nullptr arg
virtual ~Ptr() { delete m_elem; };
T* get() const {
return m_elem;
}
T& operator*() const {
return *m_elem;
}
template <class Archive>
void serialize(Archive& ar, const unsigned int /*version*/)
{
ar& BOOST_SERIALIZATION_NVP(m_elem);
}
private:
T* m_elem;
};
template<class T>
std::ostream& operator<<(std::ostream& os, const Ptr<T>& p) {
if (p.get()) {
os << *p;
}
else {
os << "{nullptr}";
}
return os;
}
int main()
{
std::string payload;
{
Ptr<A> p;
std::cout << p << std::endl;
std::ostringstream oss;
boost::archive::xml_oarchive oa(oss);
oa << BOOST_SERIALIZATION_NVP(p);
payload = oss.str();
// std::cout << payload << std::endl;
Ptr<A> p2(A(6));
std::cout << p2 << std::endl;
oa << BOOST_SERIALIZATION_NVP(p2);
payload = oss.str();
// std::cout << payload << std::endl;
}
{
Ptr<A> po;
std::istringstream iss(payload);
boost::archive::xml_iarchive ia(iss);
ia >> BOOST_SERIALIZATION_NVP(po);
std::cout << po << std::endl;
Ptr<A> po2;
ia >> BOOST_SERIALIZATION_NVP(po2);
std::cout << po2 << std::endl;
}
}
expected output:
{nullptr}
A{6}
{nullptr}
A{6}
A: Thanks to Jarod42 comment,
You should serialize a boolean to know if pointer is nullptr or not
(and if not, serialize also its content). for loading, retrieve this
boolean and allocate a default element when needed that you load.
we came with the following save and load functions :
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
bool is_null = !ptr.m_elem;
ar & boost::serialization::make_nvp("is_null", is_null);
if(!is_null) ar & boost::serialization::make_nvp("data", *ptr.m_elem);
}
template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
bool is_null;
ar & boost::serialization::make_nvp("is_null", is_null);
if (!is_null) {
ptr.m_elem = new T;
ar& boost::serialization::make_nvp("data", *ptr.m_elem);
}
}
Live on Coliru
Had an issue in the load function when is_null is false. A storage is indeed needed for ptr in this case. | unknown | |
d6729 | train | Perhaps update your .forward file to immediately forward the mail to procmail? Or setup a rule to forward the mail to a system you control where you can do the processing immediately?
The .procmailrc setup on the incoming host would look like:
"|IFS=' '&&p=/usr/local/bin/procmail&&test -f $p&&exec $p -f-||exit 75#some_string"
You could also use something like AWS SNS and Lambda to process the mail events.
If you don't have those options, polling frequently would be your best bet. You can setup a script to poll every few seconds in a loop without generating much load on the server. Typically your cron job would check if the script is running, and if not, relaunch it, otherwise do nothing. | unknown | |
d6730 | train | You can bring it back up with
Ctrl + Shift + Space | unknown | |
d6731 | train | Create a Windows service in Delphi:
http://www.devarticles.com/c/a/Delphi-Kylix/Creating-a-Windows-Service-in-Delphi/
A: You will want to do some research in the CBT hooks provided by the Microsoft SDK. They include the ability to be notified each time a window is created, among other things.
A: The Service code from Aldyn is able to track logged in users. Not sure if it is what you want, but it must surely be a good start. The vendor goes through fits of activity and sleep, so be sure it does what you want as-is.
Aldyn SvCOM | unknown | |
d6732 | train | The semicolons:
for f1 in zero-mam-2050-2074*.nc;
do;
f2={avm-mam-1976-2000-tasmax-*.nc};
command $f1 $f2 output;
done
are useless.
for f1 in zero-mam-2050-2074*.nc
do
f2={avm-mam-1976-2000-tasmax-*.nc}
command $f1 $f2 output
done
Line 3 is fishy. What do you want to do? Create an array?
for f1 in zero-mam-2050-2074*.nc
do
f2=(avm-mam-1976-2000-tasmax-*.nc)
command "$f1" "${f2[@]}" output
done
To loop over, let's say 20 files, matching pattern f1, and call each with let's say 20 files matching f2:
for f1 in zero-mam-2050-2074*.nc
do
f2=avm-mam-1976-2000-tasmax-*.nc
command "$f1" $f2 output
done
This would lead to 20 command invocations, rolling through f1 but each called with all the files matching f2.
For 20x20 matches, you would use a second loop.
Fitted to file patterns on my harddrive:
for f1 in file1*; do f2=sample.*; echo command "$f1" $f2* output; done
command file1 sample.conf sample.go sample.log sample.xml output
command file1.txt sample.conf sample.go sample.log sample.xml output
command file1nums sample.conf sample.go sample.log sample.xml output
You would of course use your patterns and, after testing, remove the echo. | unknown | |
d6733 | train | I'm using QT on a mac pro
MacOS does not support any OpenGL version higher than 4.1. It doesn't support 4.20 or most post-4.1 OpenGL extensions. And since OpenGL support is already deprecated in MacOS, no such support will be forthcoming.
If you want to use OpenGL on MacOS, then you're going to have to limit everything to 4.1 functionality. | unknown | |
d6734 | train | @client.event
async def on_message(msg):
if not msg.content == 'specific_msg':
await client.delete_message(msg)
You have to give Manage Messages permission to your bot.
A: You can use this method and add the messages you want to allow in the msgs variable.
msgs=['hi there','hello there']
@bot.event
async def on_message(msg):
if msg.content.lower() not in msgs:
await bot.delete_message(msg)
await bot.process_commands(msg) | unknown | |
d6735 | train | As of Jersey 2.3.1, a new feature has been added to support server-sent events. For your use-case, you might want to read more into the Jersey documentation
A: If you don't mind using an external library, I have been using atmosphere for a few years and it is a great server push / comet implementation. It has support for just about ever server and yes it will depend on the server. They support long poll and websockets natively. Almost the entire service can be configured with just a couple of annotations. Here is an example of how to use it on a jersey 2 service.
https://github.com/Atmosphere/atmosphere-samples/blob/master/samples/jersey2-chat/src/main/java/org/atmosphere/samples/chat/jersey/Jersey2Resource.java | unknown | |
d6736 | train | In a short discussion with a brilliant Pyramid IRC community, I decided to do this with Pyramid's tweens, rather than using the wrapper. | unknown | |
d6737 | train | Please refer to: https://developers.soundcloud.com/docs/api/rate-limits#play-requests
Rate limits are reset every 24 hours and code to handle hitting the limit is provided. | unknown | |
d6738 | train | Whenever you run a queryset like data_filed.objects.filter(g__contains=data_g).values() it always returns a dictionary kind of output with keys and values. And when you passed that result to your template file using:
return render(request, 'search_report.html',
{
'form': form,
'data': data,
'download_form': download_form
})
It is still in that format. If you want to output only the value, you need to output it as such
{{ data.Creator }}
That will give you the output "Davide" without the quotes | unknown | |
d6739 | train | I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.
The layout manager is invoked every time the divider location is changed which would add a lot of overhead.
One solution might be to stop invoking the layout manager as the divider is animating. This can be done by overriding the doLayout() method of the right panel:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SplitPaneTest2 {
public static boolean doLayout = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60))
{
@Override
public void doLayout()
{
if (SplitPaneTest2.doLayout)
super.doLayout();
}
};
for (int i = 0; i < 60 * 60; i++) {
rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
SplitPaneTest2.doLayout = false;
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
{
timer.stop();
SplitPaneTest2.doLayout = true;
splitPane.getRightComponent().revalidate();
}
});
timer.start();
}
}
Edit:
I was not going to include my test on swapping out the panel full of components with a panel that uses an image of components since I fell the animation is the same, but since it was suggested by someone else here is my attempt for your evaluation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
public class SplitPaneTest2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60));
for (int i = 0; i < 60 * 60; i++) {
rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
Component right = splitPane.getRightComponent();
Dimension size = right.getSize();
BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
right.paint( g );
g.dispose();
JLabel label = new JLabel( new ImageIcon( bi ) );
label.setHorizontalAlignment(JLabel.LEFT);
splitPane.setRightComponent( label );
splitPane.setDividerLocation( splitPane.getDividerLocation() );
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
{
timer.stop();
splitPane.setRightComponent( right );
}
});
timer.start();
}
}
A: @GeorgeZ. I think the concept presented by @camickr has to do with when you actually do the layout. As an alternative to overriding doLayout, I would suggest subclassing the GridLayout to only lay out the components at the end of the animation (without overriding doLayout). But this is the same concept as camickr's.
Although if the contents of your components in the right panel (ie the text of the labels) remain unchanged during the animation of the divider, you can also create an Image of the right panel when the user clicks the button and display that instead of the actual panel. This solution, I would imagine, involves:
*
*A CardLayout for the right panel. One card has the actual rightPanel contents (ie the JLabels). The second card has only one JLabel which will be loaded with the Image (as an ImageIcon) of the first card.
*As far as I know, by looking at the CardLayout's implementation, the bounds of all the child components of the Container are set during layoutContainer method. That would probably mean that the labels would be layed out inspite being invisible while the second card would be shown. So you should probably combine this with the subclassed GridLayout to lay out only at the end of the animation.
*To draw the Image of the first card, one should first create a BufferedImage, then createGraphics on it, then call rightPanel.paint on the created Graphics2D object and finally dispose the Graphics2D object after that.
*Create the second card such that the JLabel would be centered in it. To do this, you just have to provide the second card with a GridBagLayout and add only one Component in it (the JLabel) which should be the only. GridBagLayout always centers the contents.
Let me know if such a solution could be useful for you. It might not be useful because you could maybe want to actually see the labels change their lay out profile while the animation is in progress, or you may even want the user to be able to interact with the Components of the rightPanel while the animation is in progress. In both cases, taking a picture of the rightPanel and displaying it instead of the real labels while the animation takes place, should not suffice. So it really depends, in this case, on how dynamic will be the content of the rightPanel. Please let me know in the comments.
If the contents are always the same for every program run, then you could probably pre-create that Image and store it. Or even, a multitude of Images and store them and just display them one after another when the animation turns on.
Similarly, if the contents are not always the same for every program run, then you could also subclass GridLayout and precalculate the bounds of each component at startup. Then that would make GridLayout a bit faster in laying out the components (it would be like encoding a video with the location of each object), but as I am testing it, GridLayout is already fast: it just calculates about 10 variables at the start of laying out, and then imediately passes over to setting the bounds of each Component.
Edit 1:
And here is my attempt of my idea (with the Image):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SplitPaneTest {
//Just a Timer which plays the animation of the split pane's divider going from side to side...
public static class SplitPaneAnimationTimer extends Timer {
private final JSplitPane splitPane;
private int speed, newDivLoc;
private IntBinaryOperator directionf;
private Consumer<SplitPaneAnimationTimer> onFinish;
public SplitPaneAnimationTimer(final int delay, final JSplitPane splitPane) {
super(delay, null);
this.splitPane = Objects.requireNonNull(splitPane);
super.setRepeats(true);
super.setCoalesce(false);
super.addActionListener(e -> {
splitPane.setDividerLocation(directionf.applyAsInt(newDivLoc, splitPane.getDividerLocation() + speed));
if (newDivLoc == splitPane.getDividerLocation()) {
stop();
if (onFinish != null)
onFinish.accept(this);
}
});
speed = 0;
newDivLoc = 0;
directionf = null;
onFinish = null;
}
public int getSpeed() {
return speed;
}
public JSplitPane getSplitPane() {
return splitPane;
}
public void play(final int newDividerLocation, final int speed, final IntBinaryOperator directionf, final Consumer<SplitPaneAnimationTimer> onFinish) {
if (newDividerLocation != splitPane.getDividerLocation() && Math.signum(speed) != Math.signum(newDividerLocation - splitPane.getDividerLocation()))
throw new IllegalArgumentException("Speed needs to be in the direction towards the newDividerLocation (from the current position).");
this.directionf = Objects.requireNonNull(directionf);
newDivLoc = newDividerLocation;
this.speed = speed;
this.onFinish = onFinish;
restart();
}
}
//Just a GridLayout subclassed to only allow laying out the components only if it is enabled.
public static class ToggleGridLayout extends GridLayout {
private boolean enabled;
public ToggleGridLayout(final int rows, final int cols) {
super(rows, cols);
enabled = true;
}
@Override
public void layoutContainer(final Container parent) {
if (enabled)
super.layoutContainer(parent);
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
}
//How to create a BufferedImage (instead of using the constructor):
private static BufferedImage createBufferedImage(final int width, final int height, final boolean transparent) {
final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gdev = genv.getDefaultScreenDevice();
final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
return transparent
? gcnf.createCompatibleImage(width, height, Transparency.TRANSLUCENT)
: gcnf.createCompatibleImage(width, height);
}
//This is the right panel... It is composed by two cards: one for the labels and one for the image.
public static class RightPanel extends JPanel {
private static final String CARD_IMAGE = "IMAGE",
CARD_LABELS = "LABELS";
private final JPanel labels, imagePanel; //The two cards.
private final JLabel imageLabel; //The label in the second card.
private final int speed; //The speed to animate the motion of the divider.
private final SplitPaneAnimationTimer spat; //The Timer which animates the motion of the divider.
private String currentCard; //Which card are we currently showing?...
public RightPanel(final JSplitPane splitPane, final int delay, final int speed, final int rows, final int cols) {
super(new CardLayout());
super.setBorder(BorderFactory.createLineBorder(Color.red));
spat = new SplitPaneAnimationTimer(delay, splitPane);
this.speed = Math.abs(speed); //We only need a positive (absolute) value.
//Label and panel of second card:
imageLabel = new JLabel();
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
imagePanel = new JPanel(new GridBagLayout());
imagePanel.add(imageLabel);
//First card:
labels = new JPanel(new ToggleGridLayout(rows, cols));
for (int i = 0; i < rows * cols; ++i)
labels.add(new JLabel("|"));
//Adding cards...
final CardLayout clay = (CardLayout) super.getLayout();
super.add(imagePanel, CARD_IMAGE);
super.add(labels, CARD_LABELS);
clay.show(this, currentCard = CARD_LABELS);
}
//Will flip the cards.
private void flip() {
final CardLayout clay = (CardLayout) getLayout();
final ToggleGridLayout labelsLayout = (ToggleGridLayout) labels.getLayout();
if (CARD_LABELS.equals(currentCard)) { //If we are showing the labels:
//Disable the laying out...
labelsLayout.setEnabled(false);
//Take a picture of the current panel state:
final BufferedImage pic = createBufferedImage(labels.getWidth(), labels.getHeight(), true);
final Graphics2D g2d = pic.createGraphics();
labels.paint(g2d);
g2d.dispose();
imageLabel.setIcon(new ImageIcon(pic));
imagePanel.revalidate();
imagePanel.repaint();
//Flip the cards:
clay.show(this, currentCard = CARD_IMAGE);
}
else { //Else if we are showing the image:
//Enable the laying out...
labelsLayout.setEnabled(true);
//Revalidate and repaint so as to utilize the laying out of the labels...
labels.revalidate();
labels.repaint();
//Flip the cards:
clay.show(this, currentCard = CARD_LABELS);
}
}
//Called when we need to animate fully left motion (ie until reaching left side):
public void goLeft() {
final JSplitPane splitPane = spat.getSplitPane();
final int currDivLoc = splitPane.getDividerLocation(),
minDivLoc = splitPane.getMinimumDividerLocation();
if (CARD_LABELS.equals(currentCard) && currDivLoc > minDivLoc) { //If the animation is stopped:
flip(); //Show the image label.
spat.play(minDivLoc, -speed, Math::max, ignore -> flip()); //Start the animation to the left.
}
}
//Called when we need to animate fully right motion (ie until reaching right side):
public void goRight() {
final JSplitPane splitPane = spat.getSplitPane();
final int currDivLoc = splitPane.getDividerLocation(),
maxDivLoc = splitPane.getMaximumDividerLocation();
if (CARD_LABELS.equals(currentCard) && currDivLoc < maxDivLoc) { //If the animation is stopped:
flip(); //Show the image label.
spat.play(maxDivLoc, speed, Math::min, ignore -> flip()); //Start the animation to the right.
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
int rows, cols;
rows = cols = 60;
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
final RightPanel rightPanel = new RightPanel(splitPane, 10, 3, rows, cols);
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
JButton left = new JButton("Go left"),
right = new JButton("Go right");
left.addActionListener(e -> rightPanel.goLeft());
right.addActionListener(e -> rightPanel.goRight());
final JPanel buttons = new JPanel(new GridLayout(1, 0));
buttons.add(left);
buttons.add(right);
frame.add(splitPane, BorderLayout.CENTER);
frame.add(buttons, BorderLayout.PAGE_START);
frame.setSize(1000, 800);
frame.setMaximumSize(frame.getSize());
frame.setLocationByPlatform(true);
frame.setVisible(true);
splitPane.setDividerLocation(0.5);
});
}
} | unknown | |
d6740 | train | One approach you could take is to load the sound in right at the beginning of the scene:
YourScene.h:
@interface YourScene : SKScene
@property (strong, nonatomic) SKAction *yourSoundAction;
@end
YourScene.m:
- (void)didMoveToView: (SKView *) yourView
{
_yourSoundAction = [SKAction playSoundFileNamed:@"yourSoundFile" waitForCompletion:NO];
// the rest of your init code
// possibly wrap this in a check to make sure the scene's only initiated once...
}
This should preload the sound, and you should be able to run it by calling the action on your scene:
[self runAction:_yourSoundAction];
I've tried this myself in a limited scenario and it appears to get rid of the delay. | unknown | |
d6741 | train | You can add it directly like below:
$query= Yii::app()->db->createCommand()
->select('*')
->from('livematch')
->where('DATE(timestamp) BETWEEN DATE(NOW()) AND DATE(NOW()) + INTERVAL 7 DAY')
->order(array('timestamp', 'homeTeamName desc'))
->queryAll();
which means: ORDER BY timestamp,homeTeamName DESC
A: try like this ,
$query = Yii::app()->db->createCommand("SELECT * FROM livematch where DATE(timestamp) BETWEEN DATE(NOW()) AND DATE(NOW()) + INTERVAL 7 DAY order by timestamp desc" );
$std_list = $query->queryAll(); | unknown | |
d6742 | train | It is not possible to determine these values for non- jpegs. For jpegs, you can use a client side EXIF parser, like, https://github.com/jseidelin/exif-js to extract this data. | unknown | |
d6743 | train | You could write a function to attempt to find the matching substring, and return 'nan' if not found
def replace(s):
keywords = ['bond assy fixture', 'pierce', 'cad geometrical non-template']
try:
return next(i for i in keywords if i in s)
except StopIteration:
return 'nan'
Then you can use apply to make this substitution
>>> data['standardized_column'] = data.tool_description.apply(replace)
>>> data
tool_description standardized_column
0 bond assy fixture bond assy fixture
1 pierce die pierce
2 cad geometrical non-template cad geometrical non-template
3 707 bond assy fixture bond assy fixture
4 john pierce die pierce
5 123 cad geometrical non-template cad geometrical non-template
6 jjashd bond assy fixture bond assy fixture
7 10481 pierce die pierce
8 81235 cad geometrical non-template cad geometrical non-template
Instead of if i in s you could use a regex in the replace function as well if you need something more complex than a simple substring check.
A: You are close to the solution, just minor touch-ups needed, as follows:
data['standardized_column'] = np.nan # init column to NaN
for word in keywords:
data.loc[data.tool_description.str.contains((rf"\b{word}\b"), case=False, regex=True), 'standardized_column'] = word
Here, we use word boundary \b to enclose the keyword in the regex so that partial word match is avoided. Eg. 'pierce' won't match with 'mpierce'. Python test of StringA in StringB would produce false match since pierce in mpierce is True but not what we want to match.
Result:
print(data)
tool_description standardized_column
0 bond assy fixture bond assy fixture
1 pierce die pierce
2 cad geometrical non-template cad geometrical non-template
3 707 bond assy fixture bond assy fixture
4 john pierce die pierce
5 123 cad geometrical non-template cad geometrical non-template
6 jjashd bond assy fixture bond assy fixture
7 10481 pierce die pierce
8 81235 cad geometrical non-template cad geometrical non-template | unknown | |
d6744 | train | I managed it in the end using this code:
Dim userid As Guid = New Guid(Membership.GetUser(username.Text).ProviderUserKey.ToString())
...where username.Text is the content of the username form input, where the user chooses their username.
The relevant parameter line is this:
cmd.Parameters.Add("@UserId", g)
I get a warning about the method I'm using being deprecated, but it works at least!
A: Membership.CreateUser returns a MembershipUser object. You can get the UserId from that returned object.
MembershipUser user = Membership.CreateUser(...);
Guid userId = (Guid)user.ProviderUserKey; | unknown | |
d6745 | train | If you want each card to have drag functionality than you'll have to wrap each card in a DragSource, and not the entire list. I would split out the Card into it's own component, wrapped in a DragSource, like this:
import React, { Component, PropTypes } from 'react';
import { ItemTypes } from './Constants';
import { DragSource } from 'react-dnd';
const CardSource = {
beginDrag: function (props) {
return {};
}
};
function collect(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}
}
class CardDragContainer extends React.Component {
render() {
return this.props.connectDragSource(
<div>
<Card style= {{marginBottom: 2, opacity: this.props.isDragging ? 0 : 1}} id={value.id} key={value.id}
onMouseOver={this.props.onMouseOver}
onMouseOut={this.props.onMouseOut}
zDepth={this.props.shadow}>
<CardHeader
title={props.title}
actAsExpander={false}
showExpandableButton={false}
/>
</Card>
</div>
)
}
}
export default DragSource(ItemTypes.<Your Item Type>, CardSource, collect)(CardDragContainer);
Then you would use this DragContainer in render of the higher level component like this:
render() {
var Populate = this.props.mediaFiles.map((value) => {
return(
<div>
<MuiThemeProvider>
<CardDragContainer
value={value}
onMouseOver={this.onMouseOver}
onMouseOut={this.onMouseOut}
shadow={this.state.shadow}
/>
</MuiThemeProvider>
</div>
)
});
return (
<div>
<MuiThemeProvider>
<div className="mediaFilesComponent2">
{Populate}
</div>
</MuiThemeProvider>
</div>
);
}
That should give you a list of Cards, each of which will be individually draggable. | unknown | |
d6746 | train | The bezel is not saved as part of the screenshots from Simulator.app / simctl. The only option you have is whether or not the framebuffer mask is applied.
If you want the bezel, you'll need to use the macOS screenshot support. Hit shift-cmd-4, then hit space to toogle from "draw the rectangle" mode to "select the window" mode. Then click on the window to take a screenshot. | unknown | |
d6747 | train | We also started getting this Error since a few days.
The uri:
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd
returns a status code 301 which the SAX Parser cant handle.
Our hotfix was to change the schema location in the web.xml to the new file:
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_3_1.xsd
A: I changed the validation urls to https so the redirect, which is the problem, will not happen.
<? xml version = "1.0" encoding = "UTF-8"?>
<persistence version = "2.1"
xmlns = "https://xmlns.jcp.org/xml/ns/persistence" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation = "https://xmlns.jcp.org/xml/ns/persistence https://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
Note: I had this problem with java 7 and glassfish 3, with java 8 and glassfish 4, it works.
Another thing, in glassfish 3, I needed to disable the weld xml validations, add the parameter in the glassfish
-Dorg.jboss.weld.xml.disableValidating = true | unknown | |
d6748 | train | I'd recommend using REST and JSON to communicate to a PHP script running on Apache. Don't worry about the database on the Android side of things, just focus on what kinds of queries you might need to make and what data you need returned. Then put together a PHP script to take those queries and generate the necessary SQL to query the database on the server. For example, You need look look up a person by name and show their address in your Android app. A REST Query is just a simple HTTP GET to request data. For example, to look up John Smith, you might request: http://www.example.org/lookup.php?name=John+Smith which will return a short JSON snippet generated by PHP:
{
name: "John Smith",
address: "1234 N Elm St.",
city: "New York",
state: "New York"
}
You can instruct PHP to use the content type text/plain by putting this at the top of your PHP script:
Then you can just navigate to the above URL in your browser and see your JSON response printed out nicely as a page. There should be a good JSON parser written in Java out there you can use with Android. Hopefully, this will get you started.
A: This tutorial really helped me: http://www.screaming-penguin.com/node/7742 | unknown | |
d6749 | train | Please put gem 'web-console' into your Gemfile's test section. You can change the following lines
group :development, :test do
gem 'pry'
# Use mysql as the database for Active Record
gem 'mysql2', '~> 0.4.6'
end
with following
group :development, :test do
gem 'pry'
gem 'web-console'
# Use mysql as the database for Active Record
gem 'mysql2', '~> 0.4.6'
end
And remove web-console from following lines
group :development do
gem 'wdm', '>= 0.1.0' if Gem.win_platform?
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console' # remove this
Now run following command to update bundles
bundle install | unknown | |
d6750 | train | I summarize the useful suggestions by Liturgist and Alex K. and answer this question to get it removed from list of questions with no answer.
Batch file according to idea provided by Liturgist:
@echo off
if not "%~1" == "" (
if exist "C:\Windows\System32\drivers\etc\hosts_%~1" (
copy /Y "C:\Windows\System32\drivers\etc\hosts_%~1" C:\Windows\System32\drivers\etc\hosts
) else (
echo %~f0 %*
echo.
echo Error: There is no file C:\Windows\System32\drivers\etc\hosts_%~1
echo.
pause
)
) else (
echo %~f0
echo.
echo Please call this batch file with either X or Y as parameter.
echo.
pause
)
The batch file must be called with a parameter which specifies which hosts file should become active with at least hosts_X and hosts_Y in directory C:\Windows\System32\drivers\etc.
The parameter should be either X or Y.
An additional file check is made in case of parameter does not specify an existing hosts file resulting in an error message.
There is also a message output if batch file is called without a parameter.
Batch file according to idea provided by Alex K.:
@echo off
if exist C:\Windows\System32\drivers\etc\hosts_X (
ren C:\Windows\System32\drivers\etc\hosts hosts_Y
ren C:\Windows\System32\drivers\etc\hosts_X hosts
echo hosts_X is now the active hosts file.
) else (
ren C:\Windows\System32\drivers\etc\hosts hosts_X
ren C:\Windows\System32\drivers\etc\hosts_Y hosts
echo hosts_Y is now the active hosts file.
)
echo.
pause
This batch file toggles active hosts file depending on which template hosts file currently exists:
*
*With hosts_X existing, hosts is renamed to hosts_Y and hosts_X is renamed to hosts.
*Otherwise with hosts_Y existing, hosts is renamed to hosts_X and hosts_Y is renamed to hosts.
There should be never hosts, hosts_X and hosts_Y all existing at the same time in the directory as this would result in failing file renames. But all 3 files existing at same time should not be a use case to take into account for this task. (Using move /Y instead of ren with second file name having also full path would help in this not to expect use case.)
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
*
*call /? ... for an explanation of %~1, %~f0 and %*.
*copy /?
*echo /?
*if /?
*ren /?
*pause /? | unknown | |
d6751 | train | Your region configuration may be wrong. I ran into the same error when trying to access an S3 bucket. Since my bucket was on us-standard, aka 'us-east-1', this configuration ended up working:
AWS.config(access_key_id: 'xxx',
secret_access_key: 'xxx',
region: 'us-west-1',
s3: { region: 'us-east-1' }) | unknown | |
d6752 | train | :<anonymous>' has no member named 'foo'
A: The address is mostly just where the memory if the object "starts". How much to offset is needed members is then defined by the class definition.
So class A "starts" at 0x62fe9f.
At the beginning of class A is the member foo so because there is nothing in front of it it has also address 0x62fe9f etc.
When you change the class to
class A {
public:
int i;
struct {
void bar() { std::cout << this << std::endl; }
} foo;
};
You shloud see &a.i and &a having the same address and &a.foo should be &a + sizeof(int)
(Note: It may be more than sizeof(int) and in other cases also different because how padding is set. This is just a simple example. You should not rely on this in real code)
A: Possibly this modified version of your program, and its output, will be enlightening.
#include <iostream>
using std::cout;
class A {
public:
int data;
struct {
int data;
void bar()
{
cout << this << '\n';
cout << &this->data << '\n';
}
} foo;
void bar()
{
cout << this << '\n';
cout << &this->data << '\n';
cout << &this->foo << '\n';
}
};
int main(void)
{
A a;
cout << &a << '\n';
a.bar();
a.foo.bar();
} | unknown | |
d6753 | train | I think the most important part in this stacktrace is:
WELD-001408: Unsatisfied dependencies for type MorphologicalAnalysisPersistenceFacade
This usually means that not all required dependencies for MorphologicalAnalysisPersistenceFacade are deployed to the Weld-container. To debug this I would suggest temporarily rewriting your deployment method to:
@Deployment
public static Archive<?> createDeployment() {
JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "morphological-analysis-data-access-object-test.jar")
.addPackages(true, "br.com.cpmh.beacon")
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
// print all included packages
System.out.println(archive.toString(true));
return archive;
}
This will print out all the classes which are deployed to the container. With that, you can investigate if any required class does not get deployed and include that class or package manually in your createDeployment method. | unknown | |
d6754 | train | return A.height
else: return -1
class Binary_Node:
def __init__(self, x):
self.item = x
self.parent = None
self.left = None
self.right = None
self.subtree_update()
def subtree_update(self):
self.height = 1 + max(height(self.left), height(self.right))
def subtree_iter(self):
if self.left: yield from self.left.subtree_iter()
yield self
if self.right: yield from self.right.subtree_iter()
def subtree_first(self):
if self.left: return self.left.subtree_first()
else: return self
def subtree_last(self):
if self.right: return self.right.subtree_last()
else: return self
def sucessor(self):
if self.right: return self.right.subtree_first()
while self.parent and (self is self.parent.right): #A is parent's left child and A's parent exists
self = self.parent
return self.parent
def predecessor(self):
if self.left: return self.left.subtree_last()
while self.parent and (self is self.parent.left):
self = self.parent
return self.parent
def subtree_insert_before(self, A):
if self.left:
self = self.left.subtree_last()
self.right, A.parent = A, self
else:
self.left, A.parent = A, self
self.maintain()
def subtree_insert_after(self, A):
if self.right:
self = self.right.subtree_first()
self.left, A.parent = A, self
else:
self.right, A.parent = A, self
self.maintain()
def delete(self):
if not self.left and not self.right: # when self is leaf
if self.parent:
A = self.parent
if A.left is self: A.left = None
else: A.right = None
self.parent = None
if self.left:
self.item, self.left.subtree_last().item = self.left.subtree_last().item, self.item
self.left.subtree_last().delete()
else:
self.item, self.right.subtree_first().item = self.right.subtree_first().item, self.item
self.right.subtree_last().delete()
def subtree_delete(self):
if self.left or self.right:
if self.left: B = self.predecessor()
else: B = self.sucessor()
self.item, B.item = B.item, self.item
return B.subtree_delete()
if self.parent:
if self.parent.left is self: self.parent.left = None
else: self.parent.right = None
self.parent.maintain()
return self
def subtree_rotate_right(self):
assert self.left
B, E = self.left, self.right
A, C = B.left, B.right
B, self = self, B
self.item, B.item = B.item, self.item
B.left, B.right = A, self
self.left, self.right = C, E
if A: A.parent = B
if E: E.parent = self
B.subtree_update()
self.subtree_update()
def subtree_rotate_left(self):
assert self.right
A, D = self.left, self.right
C, E = D.left, D.right
self, D = D, self
self.item, D.item = D.item, self.item
self.left, self.right = A, C
D.left, D.right = self, E
if A: A.parent = self
if E: E.parent = D
self.subtree_update()
D.subtree_update()
def skew(self):
return height(self.right) - height(self.left)
def rebalance(self):
if self.skew() == 2:
if self.right.skew() < 0:
self.right.subtree_rotate_right()
self.subtree_rotate_left()
elif self.skew() == -2:
if self.left.skew() > 0:
self.left.subtree_rotate_left()
self.subtree_rotate_right()
def maintain(self):
self.rebalance()
self.subtree_update()
if self.parent: self.parent.maintain()
class Binary_Tree:
def __init__(self, Node_Type = Binary_Node):
self.root = None
self.size = 0
self.Node_Type = Node_Type
def __len__(self): return self.size
def __iter__(self):
if self.root:
for A in self.root.subtree_iter():
yield A.item
def build(self, X):
A = [x for x in X]
def build_subtree(A, i, j):
c = (i + j) // 2
root = self.Node_Type(A[c])
if i < c:
root.left = build_subtree(A, i, c - 1)
root.left.parent = root
if j > c:
root.right = build_subtree(A, c + 1, j)
root.right.parent = root
return root
self.root = build_subtree(A, 0, len(A) - 1)
class BST_Node(Binary_Node):
def subtree_find(self, k):
if self.item.key > k:
if self.left: self.left.subtree_find(k)
elif self.item.key < k:
if self.right: self.right.subtree_find(k)
else: return self
return None
def subtree_find_next(self, k):
if self.item.key <= k:
if self.right: return self.right.subtree_find_next(k)
else: return None
elif self.item.key > k:
if self.left: return self.left.subtree_find_next(k)
else: return self
return self
def subtree_find_prev(self, k):
if self.item.key >= k:
if self.left: return self.left.subtree_find_prev(k)
else: return None
elif self.item.key < k:
if self.right: return self.right.subtree_find_prev(k)
else: return self
return self
def subtree_insert(self, B):
if B.item.key < self.item.key:
if self.left: self.left.subtree_insert(B)
else: self.subtree_insert_before(B)
elif B.item.key > self.item.key:
if self.right: self.right.subtree_insert(B)
else: self.subtree_insert_after(B)
else:
self.item = B.item
class Set_Binary_Tree(Binary_Tree):
def __init__(self): super().__init__(BST_Node)
def iter_order(self): yield from self
def build(self, X):
for x in X: self.insert(x)
def find_min(self):
if self.root: return self.root.subtree_first()
def find_max(self):
if self.root: return self.root.subtree_last()
def find(self, k):
if self.root:
node = self.root.subtree_find(k)
if node:
return node.item
def find_next(self, k):
if self.root:
node = self.root.subtree_find_next(k)
if node:
return node.item
def find_prev(self, k):
if self.root:
node = self.root.subtree_find_prev(k)
if node:
return node.item
def insert(self, x):
new = self.Node_Type(x)
if self.root:
self.root.subtree_insert(new)
if new.parent is None: return False
else:
self.root = new
self.size += 1
return True
def delete(self, k):
assert self.root
node = self.root.subtree_find(k)
assert node
ext = node.subtree_delete()
if ext.parent is None: self.root = None
self.size -= 1
return ext.item
A: Wikipedia defines an in-place algorithm as follows:
In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However, a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. An in-place algorithm updates its input sequence only through replacement or swapping of elements.
So one of the properties of an algorithm that is called "in-place" is that it does not copy all input values into an newly allocated data structure. If an algorithm creates a binary search tree (like AVL), for which node objects are created that are populated with the input values, then it cannot be called in-place by the above definition, even if at the end of the process the values are copied back into the input array.
As a comparison, heap sort does not have to create a new data structure, as the input array can be used to reorganise its values into a heap. It merely has to swap values in that array in order to sort it. It is therefore an in-place algorithm. | unknown | |
d6755 | train | I won't list all the errors that you have in your code. I fixed most of them.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Scratch {
public static void main(String arg[]) throws Exception {
JFrame f = new JFrame();
f.setSize(600, 600);
f.setVisible(true);
f.getContentPane().setBackground(Color.BLACK);
f.setLayout(new BorderLayout());
for(int i=0; i<=360; i++) {
final int fi = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f.getContentPane().removeAll();
Circle c = new Circle(-fi);
f.add(c);
f.getContentPane().revalidate();
f.getContentPane().repaint();
}
});
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
}
}
}
}
class Circle extends JPanel {
int angle;
public Circle(int angle) {
this.angle=angle;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.RED);
g.fillArc(50, 50, 100, 100, 0, angle);
}
}
I recommend you to have one component that updates it's image rather than removing / adding different components. | unknown | |
d6756 | train | The size of an array has to be a constant expression, i.e. known at compile-time.
Reading a value from a file is an inherently dynamic operation, that happens at run-time.
One option is to use dynamic allocation:
int array_size()
{
int n;
ifstream infile("input.txt");
if (infile>>n)
return n;
else
throw std::runtime_error("Cannot read size from file");
}
int* array = new int[array_size()];
However it would be better to replace the array with std::vector<int> which can be resized dynamically.
A: Use a global pointer. Define
int* array;
in the global space before your main procedure. Then later, in a loop or not, say
array = new int[N];
to allocate your array. Just remember to also say
delete[] array;
before you exit your main or re-allocate array
A: int array[N]; - N should be know at compile-time.
Instead, use int array[]=new int[N]; /*some code using array*/ delete[] array;
int *array;
int main(){
ifstream infile("input.txt");
unsigned N;
infile>>N;
array=new int[N];
//using array...
delete[] array; //when no longer needed.
//don't use array after this line
//unless it's array=new int[] instruction
//or you know what you're doing.
} | unknown | |
d6757 | train | Why dont you use CalDAV to access the calendar, instead of trying to directly hit the MySQL DB ? From what I understand, you don't even own the schema as it comes from the Baikal server (?...) so you are running the risk of having to redo the work if/when Baikal changes the way they store the data.
Another advantage is that you are guaranteed to get a more consistent result: for example, time range queries (from date x to date y) can be tricky so by using CalDAV queries, both CalDAV clients and your calendar are going to return the same set of events whereas by trying to implement something on your own, you will likely diverge from what the CalDAV server returns.
There are php CalDAV clients. See for example Is there any php CalDav client library?
See https://www.rfc-editor.org/rfc/rfc4791#section-7.8.1 for a timerange based CalDAV query. | unknown | |
d6758 | train | Your regexp syntax is wrong. You have this:
syntax:regexp
^target*$
which means "ignore anything beginning with target and ending with an asterisk
Which fails to ignore these:
Core/target/classes/META-INF/MANIFEST.MF
Core/target/classes/xxx/yyy/zzz/X.class
for two reasons -- they begin with Core/ not target and they don't end with an asterisk.
What you probably meant was this:
syntax:regexp
^.*/target/.*$
which matches anything that has /target/ in it (notice it's .* in a regexp * is for glob style). However the ^ and $ only serve to root your regex and you don't want it rooted -- you want to find it anywhere in the string, so just do this:
syntax:regexp
/target/
The clue in all this was that the files were marked with ? which means not ignored and not added, if they were ignored you wouldn't see them at all without adding --ignored to the status command.
A: I got similar issue because I changed letter case for some files. So previously I got file called "sitenav.ext", renamed it to "siteNav.ext" and started to have same sort of issues - when I tried to "hg st" I got "? siteNav.ext".
Fix was easy
rename to "_siteNav.ext",
addremove,
commit,
rename back to "siteNav.ext",
addremove,
commit -> profit!
A: As commented by Jerome in the question, providing your config might help.
One (admittedly strange) reason for your problem could be a permission issue with the .hgignore file combined with exclude defaults for the addremove command.
I could reproduce your situation by revoking any read permission from the ignore file and by using -X "**/target/**" as a default option for the addremove command (which might be set in any of the possible Mercurial configuration files):
$ hg st
# no output, as expected
$ chmod 000 .hgignore
$ hg addremove # with '-X "**/target/**"' set as default somewhere
$ hg commit
nothing changed
$ hg st
? Core/target/Core-0.0.1-SNAPSHOT-tests.jar
? Core/target/Core-0.0.1-SNAPSHOT.jar
...
hg fails in reading the ignore file and thus does not know that the target stuff should be ignored. A corresponding warning from hg would be helpful here.
This question has been updated in response to Jerome's comment.
A: Many thanks for everyone's help on this. I haven't found an answer to the problem but I did find a workaround that got rid of it. So I'm assuming that at some point when modifying the hgignore regexps mercurial got confused and corrupted it's internal data... or something. I don't know enough internals to know what this could have been.
Anyway, should you find yourself in the same boat, here's what I did:
*
*Make sure your .hgignore file says what you want it to and that all the files turning up in the hg status are the ones you want to ignore.
*Add all the files to be ignored. hg addremove doesn't work because it does honour the hgignore contents, so I used Eclipse's hg plugin and did each file manually (well, I selected them all and Eclipse applied the add to them all individually).
*Revert all added files. I used the following because I'm on linux. (thanks to another poster on a separate question here on SO - which I can now no longer find unfortunately)
hg status -an0 | xargs -0 hg revert
*repeat the above step until it no longer works. In my case this was sometimes up to as many as 3 reverts in a row! (No idea what it was actually doing though :( )
*commit
You should now no longer see the ignored files in the hg status output.
I'm sorry, I have no idea why this worked, or what the original problem was. If anyone does, I'd be very interested to know your thoughts.
Many thanks again to everyone :)
A: ? does not mean ignored.
It just means that mercurial is not tracking the file.
If you don't want to see them just do
hg status -mard
i.e. only show modified, added, removed, deleted
A: Your .hgignore file says "^target" is ignored, but the files are in Core/target. So the ignore line should rather be "target" (without the ^) or "^Core/target".
Or am I missing sth here?
(Note: ^ implies that regex matching starts from the beginning of the path, i.e. only paths starting with target would be matched!)
A: Had the same problem and Bob's answer did the trick for me.
If you are using TortoiseHg you can select "edit ignore filter" in the context menu (windows) to verify and change your .hgignore settings there. | unknown | |
d6759 | train | By default, a vertical stack view has .alignment = .fill ... so it will stretch the arranged subviews to "fill the width of the stack view."
Change it to:
stackView.alignment = .center
As a side note, get rid of the stackView.distribution = .fillProportionally ... it almost certainly is not what you want. | unknown | |
d6760 | train | Change double quotes " for single quotes '
It is not necessary to add a escape character individually, it works for the rest of the parameters too.
Scaffold-DbContext 'Server=tcp:dbname.database.windows.net,1433;Initial Catalog=DBNAME_DB;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
A: I figured out my problem. My password contained the character $ and this needs to be escaped out by using ` before the $.
A: Did you tried to update your web.config file for connection string. This might be a reason which doesn't allow you to login to azure.
A: Please make sure the user login exists on the target SQL Azure database and not only on the Azure SQL Database server.
-- On master database
CREATE LOGIN MaryLogin WITH PASSWORD = '';
-- On the user database
CREATE USER MaryUser FROM LOGIN MaryLogin;
Create a firewall rule on Azure portal to allow access to the Azure SQL Database as explained here. Make sure port TCP 1433 is open from your computer.
A: For me the below command worked when executed in Package Manager console:PM>
Scaffold-DbContext "Server=.;Database=Employee;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models | unknown | |
d6761 | train | bot:nasuni jesse$ python
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Probably the biggest reason I went and upgraded this morning, it's not 2.6.2, but it's close enough.
A: Python 2.6.1
(according to the web)
Really good to know :)
A: http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html
A: It ships with both python 2.6.1 and 2.5.4.
$ python2.5
Python 2.5.4 (r254:67916, Jul 7 2009, 23:51:24)
$ python
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
A: You can get an installer for 2.6.2 from python.org, no reason to go without. | unknown | |
d6762 | train | You need to apply the plugin to any jQuery object, so you need to do something like this to use the plugin.
$($response).reverse(function (k, v) { /*.. code here ...*/ });
//-^^^- wrap using jQuery if it's not a jQuery object
Refer : How to Create a Basic Plugin | unknown | |
d6763 | train | This can't really be done with a single SQL statement as it would require an unknown number of columns.
I would be inclined to say that this is just formatting of the returned data, and hence probably better places in the calling script.
However it is easy to do if you have a fixed number of countries that you are interested in. But with several sub queries it is not likely to be that efficient.
What can be done is to dynamically build up the SQL, but that is messy.
Alternative would to GROUP_CONCAT the countries details into a single row:-
SELECT GROUP_CONCAT(CONCAT_WS('##', COUNTRY, ORGANIZATIONS ))
FROM
(
SELECT COUNTRY, COUNT(*) AS ORGANIZATIONS
FROM ORGANIZATION
GROUP BY COUNTRY
) sub0 | unknown | |
d6764 | train | If you're adding a reference to a DLL into your VBA project, you can use 'Object Browser' (F2), select the DLL you added and the methods / classes / properties will be shown. With luck, your DLLs will be well documented - and easy to use.
Rgds
A: I assume those are COM DLLs. In that case what you need is OLE-COM Object Viewer, available as part of whatever is the latest Windows SDK. | unknown | |
d6765 | train | Yes the child will have proper malloc()ed memory.
First, know that there are two memory managers in place:
*
*One is the Linux kernel, which allocates memory pages to processes. This is done through the sbrk() system call.
*On the other hand, malloc() uses sbrk() to request memory from the kernel and then manages it, by breaking it in chunks, remembering how the memory has been divided and later mark them as available when free()ed (and at times perform something similar to garbage collection).
That said, what malloc() does with memory is completely transparent to the Linux kernel. It's effectively just a linked list or two, which you could have implemented yourself. What the Linux kernel sees as your memory are the pages assigned to your process and their contents.
When you call fork() (emphasis mine):
*
*The child process is created with a single thread--the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.
*The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent. This means that the two descriptors share open file status flags, current file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl(2)).
*The child inherits copies of the parent's set of open message queue descriptors (see mq_overview(7)). Each descriptor in the child refers to the same open message queue description as the corresponding descriptor in the parent. This means that the two descriptors share the same flags (mq_flags).
*The child inherits copies of the parent's set of open directory streams (see opendir(3)). POSIX.1-2001 says that the corresponding directory streams in the parent and child may share the directory stream positioning; on Linux/glibc they do not.
So fork() not only copy the entire virtual address space, but also all mutexes, file descriptors and basically every kind of resource the parent has opened. Part of the virtual address space copied is the linked list(s) of malloc(). So after a fork(), the malloc()ed memories of both processes are equal and the information malloc() keeps and what memory is allocated is also the same. However, they now live on separate memory pages.
Side information: One might think that fork() is a very expensive operation. However (from the man page):
Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.
This basically says that on fork()ing, no actual copying is done, but the pages are marked to be copied if the child tries to modify them. Effectively, if the child only reads from that memory, or completely ignore it, there is no copy overhead. This is very important for the common fork()/exec() pattern. | unknown | |
d6766 | train | After some hours spent on searching the reason of warning and not built styles for everything after the warning, I finally found the cause.
And the winner is:
precss@^1.4.0
This is old package, last changes were added 2 years ago. It is not even a package, just gathered plugins for postcss to process styles.
I removed this package from my project and added few needed plugins postcss.conf.js:
const webpack = require('webpack');
const path = require('path');
module.exports = {
parser: 'postcss-scss',
plugins: [
require('postcss-smart-import')({
addDependencyTo: webpack,
path: [
path.resolve(__dirname, 'src/common'),
path.resolve(__dirname, 'src/app1'),
path.resolve(__dirname, 'src/app2'),
]
}),
require('postcss-advanced-variables'),
require('postcss-mixins'),
require('postcss-nested'),
require('postcss-nesting'),
require('postcss-extend'),
require('autoprefixer'),
]
};
works! | unknown | |
d6767 | train | Check the angular documentation for correct router implementation | unknown | |
d6768 | train | Access denied means that the application is being run from an account that is not permitted to access that remote folder. If the command is failing within the context of a JSP, that means that the account / identity that is running the web container doesn't have the necessary permissions.
This could be a deliberate security decision. Letting your web server access remote shares is asking for trouble ... if your website gets "hacked". It is prudent to run a web container with minimal privileges as a precaution.
This is not a programming problem per se. Rather it is a problem of figuring out why you don't have permission, and how to get permission safely; i.e. without making your entire network more vulnerable to hackers. Talk to your local (Windows) system administrators. | unknown | |
d6769 | train | A complete proposal. With an array with the wanted grouped result.
function getGroupedData(dates, from, to) {
function pad(s, n) { return s.toString().length < n ? pad('0' + s, n) : s; }
var temp = Object.create(null),
result = [],
fromYear = +from.slice(0, 4),
fromMonth = +from.slice(5, 7),
toYear = +to.slice(0, 4),
toMonth = +to.slice(5, 7),
o, k;
datearray.forEach(function (d) {
var k = d.slice(0, 7);
temp[k] = (temp[k] || 0) + 1;
});
while (true) {
k = pad(fromYear, 4) + '-' + pad(fromMonth, 2);
o = {};
o[k] = (temp[k] || 0).toString();
result.push(o);
if (fromYear === toYear && fromMonth === toMonth) {
break;
}
fromMonth++;
if (fromMonth > 12) {
fromMonth = 1;
fromYear++;
}
}
return result;
}
var datearray = ["2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22"];
console.log(getGroupedData(datearray, '2015-12-01', '2016-09-30'));
A: You can use Array.filter to filter through this array. Taking advantage of your particular date format, we do not need to do any date arithmetic, we can simply compare dates as strings and use localeCompare() to compare them:
var datearray = [
"2016-01-13",
"2016-01-18",
"2016-01-30",
"2016-02-13",
"2016-02-18",
"2016-02-28",
"2016-03-13",
"2016-03-23",
"2016-03-30",
"2016-04-13",
"2016-04-18",
"2016-04-30",
"2016-05-13",
"2016-05-18",
"2016-05-28",
"2016-06-13",
"2016-06-23",
"2016-06-30",
"2016-08-22"
];
var startDate = "2015-12-01";
var endDate = "2016-01-30";
var filteredArray = datearray.filter(function(item){
return item.localeCompare( startDate ) > -1 && endDate.localeCompare( item ) > -1;
});
console.log( filteredArray );
Now, you have the filteredArray and you can simply iterate through it to count the number of dates falling in a month.
A: You may try this:
Underscore.js has been used to manipulate data.
var datearray=["2016-01-13","2016-01-18","2016-01-30","2016-02-13","2016-02-18","2016-02-28","2016-03-13","2016-03-23","2016-03-30","2016-04-13","2016-04-18","2016-04-30","2016-05-13","2016-05-18","2016-05-28","2016-06-13","2016-06-23","2016-06-30","2016-08-22"];
var boxingDay = new Date("12/01/2015");
var nextWeek = new Date("09/30/2016");
function getDates( d1, d2 ){
var oneDay = 24*3600*1000;
for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){
var new_Date=new Date(ms);
d.push( new_Date.getFullYear()+"-"+("0" + (new_Date.getMonth() + 1)).slice(-2) );
}
return d;
}
var x=[];
_.each(datearray, function(e){x.push(e.substring(0, 7));});
var z= _.uniq(getDates( boxingDay, nextWeek ));
var f=x.concat(_.uniq(getDates( boxingDay, nextWeek )));
document.getElementById("xx").innerHTML=JSON.stringify(_.countBy(f));
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id="xx"></div>
A: If you looking for a more ES6 way then check it out:
var dateArray = ["2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22"];
var group = {};
dateArray.forEach(date =>
group[(date = date.substr(0, 7))] =
(group[date] || []).concat(date)
);
var result = Object.keys(group)
.map(date => ({
[date]: group[date].length
}));
console.log(result)
If your date format is as the date array then the easiest way would be to use substr if the length is not constant then you can split it by spacer and then get the two first values. And if it's totally a date string you can create a date from this and convert it to your desired string as key of your object. | unknown | |
d6770 | train | I'm not sure what you mean by "I use the and statement to specify only URL data", but I would use isnull function to provide a default value for NULLS
concat("example.com/",isnull(rs.answer,"default value"),"/415x380.png")
rather than using rs.answer is not null | unknown | |
d6771 | train | I see this question is a bit old now, however I do a similar thing with the Melody plugin. There is no value in this being installed during TEST - and can get in the way - so I do the following:
plugins {
// other plugins ...
if( Environment.current != Environment.TEST )
compile ":grails-melody:1.56.0"
// other plugins ...
}
So when I run 'test-app' I see the plugin 'uninstalled' and then when I do 'run-app' I see it installed and it's available.
NOTE: I recently got caught out by forgetting to also do an import grails.util.Environment. If you do that, you'll find that Environment.current == [:] as does Environment.TEST etc. I believe this is due to the builder behind the config file. | unknown | |
d6772 | train | Just do not have time to render it. You add it and immediately remove.
Try this approach, for example:
private MyPopup popup;
public void buttonClick(ClickEvent event) {
Thread workThread = new Thread() {
@Override
public void run() {
// some initialization here
getWindow().removeWindow(popup);
}
};
workThread.start();
popup = new MyPopup();
getWindow().addWindow(popup);
}
A: Depending on Vaadin version you can make use of ICEPush plugin (Vaadin 6) or built-in feature called Server Push (Vaadin 7).
public void buttonClick(ClickEvent event) {
MyPopup popup = new MyPopup();
getWindow().addWindow(popup);
log.warn("Added POPUP");
// start background thread with ICEPush or ServerPush
}
// Background thread in a separate class
// update UI accordingly when thread finished the job
getWindow().removeWindow(popup);
log.warn("Removed Popup");
Thanks to it you can move your time-consuming operations to another class thus decouple your business logic from the presentation layer. You can find examples of usage in the links above. | unknown | |
d6773 | train | For some reason, the wear project had '4.4w' as the build target, i updated this to 20 and the error went away. | unknown | |
d6774 | train | I just checked the source of the paned object which has the following code in the gtk_paned_state_flags_changed function:
if (gtk_widget_is_sensitive (widget))
cursor = gdk_cursor_new_from_name (gtk_widget_get_display (widget),
priv->orientation == GTK_ORIENTATION_HORIZONTAL
? "col-resize" : "row-resize");
else
cursor = NULL;
(https://git.gnome.org/browse/gtk+/tree/gtk/gtkpaned.c?h=3.18.6#n1866)
Thus in theory you could overwrite the do_state_flags_changed function of the paned widget (and all other widget that have behavior like this) to achieve the result you want.
But as you ask for a way to set the cursor for all objects in one go the answer is simply: No, that is not possible. | unknown | |
d6775 | train | It doesn't make any sense. Marshalling is used for interop - and when doing interop, the two sides have to agree exactly on the structure of the struct.
When you use auto layout, you defer the decision about the structure layout to the compiler. Even different versions of the same compiler can result in different layouts - that's a problem. For example, one compiler might use this:
public struct StructAutoLayout
{
byte B1;
long Long1;
byte B2;
long Long2;
byte B3;
}
while another might do something like this:
public struct StructAutoLayout
{
byte B1;
byte B2;
byte B3;
byte _padding;
long Long1;
long Long2;
}
When dealing with native/unmanaged code, there's pretty much no meta-data involved - just pointers and values. The other side has no way of knowing how the structure is actually laid out, it expects a fixed layout you both agreed upon in advance.
.NET has a tendency to make you spoiled - almost everything just works. This is not the case when interoping with something like C++ - if you just guess your way around, you'll most likely end up with a solution that usually works, but once in a while crashes your whole application. When doing anything with unmanaged / native code, make sure you understand perfectly what you're doing - unmanaged interop is just fragile that way.
Now, the Marshal class is designed specifically for unmanaged interop. If you read the documentation for Marshal.SizeOf, it specifically says
Returns the size of an unmanaged type in bytes.
And of course,
You can use this method when you do not have a structure. The layout must be sequential or explicit.
The size returned is the size of the unmanaged type. The unmanaged and managed sizes of an object can differ. For character types, the size is affected by the CharSet value applied to that class.
If the type can't possibly be marshalled, what should Marshal.SizeOf return? That doesn't even make sense :)
Asking for the size of a type or an instance doesn't make any sense in a managed environment. "Real size in memory" is an implementation detail as far as you are concerned - it's not a part of the contract, and it's not something to rely on. If the runtime / compiler wanted, it could make every byte 77 bytes long, and it wouldn't break any contract whatsoever as long as it only stores values from 0 to 255 exactly.
If you used a struct with an explicit (or sequential) layout instead, you would have a definite contract for how the unmanaged type is laid out, and Marshal.SizeOf would work. However, even then, it will only return the size of the unmanaged type, not of the managed one - that can still differ. And again, both can be different on different systems (for example, IntPtr will be four bytes on a 32-bit system and eight bytes on a 64-bit system when running as a 64-bit application).
Another important point is that there's multiple levels of "compilation" in a .NET application. The first level, using a C# compiler, is only the tip of the iceberg - and it's not the part that handles reordering fields in the auto-layout structs. It simply marks the struct as "auto-layouted", and it's done. The actual layouting is handled when you run the application by the CLI (the specification is not clear on whether the JIT compiler handles that, but I would assume so). But that has nothing to do with Marshal.SizeOf or even sizeof - both of those are still handled at runtime. Forget everything you know from C++ - C# (and even C++/CLI) is an entirely different beast.
If you need to profile managed memory, use a memory profiler (like CLRProfiler). But do understand that you're still profiling memory in a very specific environment - different systems or .NET versions can give you different results. And in fact, there's nothing saying two instances of the same structure must be the same size. | unknown | |
d6776 | train | We "fixed" the problem by changing the structure. So it's more of a workaround.
Instead of using a List of polymorphics, we now use a "container" class, which contains each type as it's own type.
The Condition object became a "container" or "manager" class, instead of a List.
In the Job class, the field is now defined as:
private Condition condition;
The Condition class itself is now
public final class Condition{
private List<Internal> internalConditions;
// etc...
}
And, as example, the Internal lost it's parent type and is now just
public final class Internal{
// Logic...
}
The Swagger generated JSON now looks like this (excerpt):
"Job": {
"Condition": {
"Internal": {
}
"External": {
}
//etc...
}
}
A: Useful display of polymorphic responses in Swagger UI with Springfox 2.9.2 seems hard (impossible?). Workaround feels reasonable.
OpenAPI 3.0 appears to improve support for polymorphism. To achieve your original goal, I would either
*
*Wait for Springfox to get Open API 3.0 support (issue 2022 in Springfox Github). Unfortunately, the issue has been open since Sept 2017 and there is no indication of Open API 3.0 support being added soon (in Aug 2019).
*Change to Spring REST Docs, perhaps adding the restdocs-api-spec extension to generate Open API 3.0.
We have run into similar problems with polymorphism but have not yet attempted to implement a solution based on Spring REST Docs + restdocs-api-spec. | unknown | |
d6777 | train | The reason behind this is not working is because you have passed same id for two text fields, and in HTML you can't have duplicate ids as it doesn't make sense.
here you can do two things
*
*Give class to new element and get element from class
*Or when you create an element at that time create a autosuggest object for that field
Here is a fiddle for you
HTML CODE:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<table class="table" id="dataTable" name="table">
<TD>
<INPUT type="text" id="tags" class="autosuggest" />
</TD>
</table>
<br>
<button type="button" class="btn btn-primary" value="Add Row" onclick="addRow('dataTable')">
Add More
</button>
JAVASCRIPT CODE:
function createAutoSuggest(element) { // Created a common function for you
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
];
$(element).autocomplete({
source: availableTags
});
}
$(function() {
createAutoSuggest($(".autosuggest"));
});
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
if (i == 1) {
newcell.innerHTML = (rowCount + 1)
} else {
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "test":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
if ($(newcell).find('.autosuggest').length > 0) {
createAutoSuggest($(newcell).find('.autosuggest'));// This is the change you basically need
}
}
}
A: You can use live to attach events to dynamically created textboxes.
Here is the example | unknown | |
d6778 | train | I learned something new today. I've never used the _s functions and always assumed they were vendor-supplied extensions, but they are actually defined in the language standard under Annex K, "Bounds-checking Interfaces". With respect to printf_s:
K.3.5.3.3 The printf_s function
Synopsis
1 #define _ _STDC_WANT_LIB_EXT1_ _ 1
#include <stdio.h>
int printf_s(const char * restrict format, ...);
Runtime-constraints
2 format shall not be a null pointer. The %n specifier394) (modified or not by flags, field
width, or precision) shall not appear in the string pointed to by format. Any argument
to printf_s corresponding to a %s specifier shall not be a null pointer.
3 If there is a runtime-constraint violation, the printf_s function does not attempt to
produce further output, and it is unspecified to what extent printf_s produced output
before discovering the runtime-constraint violation.
Description
4 The printf_s function is equivalent to the printf function except for the explicit
runtime-constraints listed above.
Returns
5 The printf_s function returns the number of characters transmitted, or a negative
value if an output error, encoding error, or runtime-constraint violation occurred.
394) It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed
at by format when those characters are not a interpreted as a %n specifier. For example, if the entire
format string was %%n.
C 2011 Online Draft
To summarize, printf_s performs additional runtime validation of its arguments not done by printf, and will not attempt to continue if any of those runtime validations fail.
The _s functions are optional, and the compiler is not required to support them. If they are supported, the macro __STDC_WANT_LIB_EXT1__ will be defined to 1, so if you want to use them you'll need to so something like
#if __STDC_WANT_LIB_EXT1__ == 1
printf_s( "%s", "This is a test\n" );
#else
printf( "%s", "This is a test\n" );
#endif | unknown | |
d6779 | train | Enable the text view's allowsEditingTextAttributes property.
A: For those who came here because they enabled Allows Editing Attributes in IB but don't see the BIU UIMenu in the app: apparently that checkbox only activates attribute editing for the pre-defined string displayed in IB, but not in the actual UITextView presented to the user. You still have to enable the allowsEditingTextAttributes property somewhere in your code. | unknown | |
d6780 | train | You'll have to use some kind of signal from the client to know whether it is sending text or an image.
Alternatively, you could receive on different ports depending on the type of input. | unknown | |
d6781 | train | Somewhere the text/value isn't equal. I inserted a msgbox in your code so you can see exactly what's being compared.
UPDATED WITH TRUE/FALSE DISPLAYED IN MESSAGE BOX TITLE
Sub SearchBox()
Dim lastrow As Long
Dim i As Long, x As Long
Dim count As Integer
lastrow = Sheets("Charlotte Gages").Cells(Rows.count, 1).End(xlUp).Row
i = Sheets("Gages").Cells(Rows.count, 1).End(xlUp).Row + 1
For x = 2 To lastrow
'try with this to test
Dim anSwer As Integer
Dim TrueOrFalse As String
TrueOrFalse = Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1")
anSwer = MsgBox("your value in Charlotte Gauges Cell " & Sheets("Charlotte Gages").Cells(x, 1).Address & " is """ & Sheets("Charlotte Gages").Cells(x, 1).Value & _
""" while your other value in cell " & Sheets("Gages").Range("A1").Address & " is """ & Sheets("Gages").Range("A1").Value & """. Continue?", vbYesNo, Title:=TrueOrFalse)
If anSwer = vbNo Then
Exit Sub
End If
'End of test code, this can be deleted once you figure out your issue
If Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") Then
Sheets("Gages").Cells(i, 1).Resize(, 7).Value = Sheets("Charlotte Gages").Cells(x, 1).Resize(, 7).Value
i = i + 1
count = count + 1
End If
Next x
If count = 0 Then
MsgBox ("Cannot Find Gage, Please check Gage ID")
End If
End Sub
A: So I figured out what was wrong. The number-only ID's were stored as text in Sheet 1, therefore not allowing my search box to find it. All I had to do was convert them all to numbers and it fixed everything. | unknown | |
d6782 | train | EBP is the base pointer for the current stack frame. Once you overwrite that base pointer with a new value, subsequent references to items on the stack will reference not the actual address of the stack, but the address your overwrite just provided.
Further behavior of the program depends on whether and how the stack is subsequently used in the code.
A: What exactly is corrupted heavily depends on generated code, so this is rather compiler and settings dependant. You also don't know if really ebp would be corrupted. Often compilers add additional bytes to the variables, so with one byte overrun nothing might happen at all. On newer Visual Studio code I saw that some safeguard code is added, which causes an exception to be thrown.
If the return address is corrupted, this can be used as an entrypoint for exploits installing their own code. | unknown | |
d6783 | train | As far as translating (ie moving) your JLabel:
First, you must make sure that the layout manager of its parent is set to null, or uses a customized layoutmanager that can be configured to do your translation.
Once you have that in place, it's a simple matter:
public void mouseClicked(MouseEvent ae) {
JLabel src = (JLabel) ae.getSource();
src.setLocation(src.getLocation().x + delta_x, src.getLocation().y + delta_y);
src.getParent().repaint();
} | unknown | |
d6784 | train | It's difficult to tell based on the limited code you provided. But based on the error message, it would seem that you do not have the onThemeRadio(View) method in the right place. It needs to be a method on the Activity class that uses that XML layout. Use Android Studio to help figure it out. For example, does Android Studio highlight onThemeRadio(View) as an unused method? Or does the onclick attribute in XML get flagged that the method is missing or has the wrong signature? These are signs that the method is in the wrong place. You can also use the light bulb that pops up next to a highlighted onclick attribute to automatically create the method in the right place. | unknown | |
d6785 | train | Finally I found a way out to solve this problem.
I have added a CALayer as sublayer and the fill color is used to create as a UIImage which is used to set as contents for the sublayer.
Here is the code for someone who may face this problem in future
CAShapeLayer *hexagonMask = [CAShapeLayer layer];
CAShapeLayer *hexagonBorder = [CAShapeLayer layer];
hexagonMask.frame=self.layer.bounds;
hexagonBorder.frame = self.layer.bounds;
UIBezierPath* hexagonPath=[self makeHexagonalMaskPathWithSquareSide:side]; //making hexagon path
hexagonMask.path = hexagonPath.CGPath; //setting the mask path for hexagon
hexagonBorder.path = hexagonPath.CGPath; //setting the maskpath for hexagon border
hexagonBorder.fillColor=[UIColor clearColor].CGColor; //setting by default color
hexagonBorder.lineWidth = self.customBorderWidth; // setting border width
hexagonBorder.strokeColor = self.customBorderColor.CGColor; //setting color for hexagon border
CGFloat coverImageSide=side-(_customBorderWidth);
CGFloat backgroundLayerXY=_customBorderWidth/2.0;
UIImage *coverImage=[UIImage ImageWithColor:_customFillColor width:coverImageSide height:coverImageSide];
UIBezierPath* dpath=[self makeHexagonalMaskPathWithSquareSide:coverImageSide];
CALayer *backgroundLayer=[CALayer layer];
backgroundLayer.frame=CGRectMake(backgroundLayerXY, backgroundLayerXY, coverImageSide, coverImageSide);
CAShapeLayer *backgroundMaskLayer=[CAShapeLayer layer];
backgroundMaskLayer.path=dpath.CGPath;
backgroundLayer.mask=backgroundMaskLayer;
[backgroundLayer setContentsScale:[UIScreen mainScreen].scale];
[backgroundLayer setContentsGravity:kCAGravityResizeAspectFill];
[backgroundLayer setContents:(__bridge id)[UIImage maskImage:coverImage toPath:dpath].CGImage];
[self.layer.sublayers[0] addSublayer:backgroundLayer]; | unknown | |
d6786 | train | Try this
optionimage: any[] = [];
surveyImageUrl = function () {
debugger;
this.commonService.surveyImageUrl().subscribe(data => {
if (data.success) {
data.survey.array.forEach(element => {
var obj = {
is_optionimages: true,
surveyImage: element.surveyImage,
}
this.optionimage.push(obj);
});
}
});
}
Then you can bind your image urls to View as below.
<div *ngFor="let image of optionimage">
<img [src] = "image.surveyImage"/>
</div> | unknown | |
d6787 | train | You can pass a regex as the url argument, which ignores parameters:
@responses.activate
def test_request_params():
url = r"http://example.com/api/endpoint"
params = {"hello": "world", "a": "b"}
# regex that matches the url and ignores anything that comes after
rx = re.compile(rf"{url}*")
responses.add(method=responses.GET, url=rx)
response = requests.get(url, params=params)
assert responses.calls[-1].request.params == params
url_path, *queries = responses.calls[-1].request.url.split("?")
assert url_path == url | unknown | |
d6788 | train | For n=2 you could
SELECT max(column1) m
FROM table t
GROUP BY column2
UNION
SELECT max(column1) m
FROM table t
WHERE column1 NOT IN (SELECT max(column1)
WHERE column2 = t.column2)
for any n you could use approaches described here to simulate rank over partition.
EDIT:
Actually this article will give you exactly what you need.
Basically it is something like this
SELECT t.*
FROM
(SELECT grouper,
(SELECT val
FROM table li
WHERE li.grouper = dlo.grouper
ORDER BY
li.grouper, li.val DESC
LIMIT 2,1) AS mid
FROM
(
SELECT DISTINCT grouper
FROM table
) dlo
) lo, table t
WHERE t.grouper = lo.grouper
AND t.val > lo.mid
Replace grouper with the name of the column you want to group by and val with the name of the column that hold the values.
To work out how exactly it functions go step-by-step from the most inner query and run them.
Also, there is a slight simplification - the subquery that finds the mid can return NULL if certain category does not have enough values so there should be COALESCE of that to some constant that would make sense in the comparison (in your case it would be MIN of domain of the val, in article it is MAX).
EDIT2:
I forgot to mention that it is the LIMIT 2,1 that determines the n (LIMIT n,1).
A: If you are using mySQl, why don't you use the LIMIT functionality?
Sort the records in descending order and limit the top n i.e. :
SELECT yourColumnName FROM yourTableName
ORDER BY Id desc
LIMIT 0,3
A: Starting from MySQL 8.0/MariaDB support window functions which are designed for this kind of operations:
SELECT *
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY column2 ORDER BY column1 DESC) AS r
FROM tab) s
WHERE r <= 2
ORDER BY column2 DESC, r DESC;
DB-Fiddle.com Demo
A: This is how I'm getting the N max rows per group in MySQL
SELECT co.id, co.person, co.country
FROM person co
WHERE (
SELECT COUNT(*)
FROM person ci
WHERE co.country = ci.country AND co.id < ci.id
) < 1
;
how it works:
*
*self join to the table
*groups are done by co.country = ci.country
*N elements per group are controlled by ) < 1 so for 3 elements - ) < 3
*to get max or min depends on: co.id < ci.id
*
*co.id < ci.id - max
*co.id > ci.id - min
Full example here:
mysql select n max values per group/
mysql select max and return multiple values
Note: Have in mind that additional constraints like gender = 0 should be done in both places. So if you want to get males only, then you should apply constraint on the inner and the outer select | unknown | |
d6789 | train | I've been searching for the same question. It looks like in python 2.7 you can add the following line to a file called custom.js:
IPython.Cell.options_default.cm_config.lineWrapping = true;
Custom.js is located in ~\Lib\site-packages\notebook\ or ~\Lib\site-packages\jupyter_core\
Note, however, that this isnt working for me yet. I will update here as soon as I get something working. | unknown | |
d6790 | train | Default system administrator account:
*
*login - [email protected]
*password - sysadmin
Default demo tenant administrator account:
*
*login - [email protected].
*password - tenant.
Demo tenant customers:
Customer A user: [email protected].
Customer B user: [email protected].
Customer C user: [email protected].
all users have “customer” password.
Take a look at demo-account documentation page for more information. | unknown | |
d6791 | train | You may use Graphics.drawPolygon(int[], int[], int) where the first int[] is the set of x values, the second int[] is the set of y values, and the int is the length of the array. (In a triangle's case, the int is going to be 3)
Example:
graphics.drawPolygon(new int[] {10, 20, 30}, new int[] {100, 20, 100}, 3);
Output:
A: I would use a Path2D object, and would place my first point with its moveTo(...) method, and then add additional points with its lineTo(...) method. Then I could draw it or fill it via Graphics2D#draw(...) and Graphics2D#fill(...). Also calling closePath() on it will make sure that your triangle closes appropriately.
For example, the following code produces:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Path2DExample extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color COLOR_1 = Color.blue;
private static final Color COLOR_2 = Color.red;
private static final Paint GRADIENT_PAINT = new GradientPaint(0, 0, COLOR_1, 20, 20, COLOR_2, true);
private Path2D myPath = new Path2D.Double();
public Path2DExample() {
double firstX = (PREF_W / 2.0) * (1 - 1 / Math.sqrt(3));
double firstY = 3.0 * PREF_H / 4.0;
myPath.moveTo(firstX, firstY);
myPath.lineTo(PREF_W - firstX, firstY);
myPath.lineTo(PREF_W / 2.0, PREF_H / 4.0);
myPath.closePath();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// to smooth out the jaggies
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(GRADIENT_PAINT); // just for fun!
g2.fill(myPath); // fill my triangle
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Path2DExample mainPanel = new Path2DExample();
JFrame frame = new JFrame("Path2DExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
An additional benefit to use of a Path2D object is that if you want to drag the Shape, it's not hard to do with a MouseListener and MouseMotionListener, say something like:
private class MyMouseAdapter extends MouseAdapter {
private Point pPressed = null;
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
if (myPath.contains(e.getPoint())) {
pPressed = e.getPoint();
}
}
public void mouseDragged(MouseEvent e) {
drag(e);
}
@Override
public void mouseReleased(MouseEvent e) {
drag(e);
pPressed = null;
}
private void drag(MouseEvent e) {
if (pPressed == null) {
return;
}
Point p = e.getPoint();
int tx = p.x - pPressed.x;
int ty = p.y - pPressed.y;
AffineTransform at = AffineTransform.getTranslateInstance(tx, ty);
myPath.transform(at);
pPressed = p;
repaint();
};
}
The whole thing could look like:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import javax.swing.*;
@SuppressWarnings("serial")
public class Path2DExample extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color COLOR_1 = Color.blue;
private static final Color COLOR_2 = Color.red;
private static final Paint GRADIENT_PAINT = new GradientPaint(0, 0, COLOR_1,
20, 20, COLOR_2, true);
private Path2D myPath = new Path2D.Double();
public Path2DExample() {
double firstX = (PREF_W / 2.0) * (1 - 1 / Math.sqrt(3));
double firstY = 3.0 * PREF_H / 4.0;
myPath.moveTo(firstX, firstY);
myPath.lineTo(PREF_W - firstX, firstY);
myPath.lineTo(PREF_W / 2.0, PREF_H / 4.0);
myPath.closePath();
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(GRADIENT_PAINT);
g2.fill(myPath);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
private Point pPressed = null;
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
if (myPath.contains(e.getPoint())) {
pPressed = e.getPoint();
}
}
public void mouseDragged(MouseEvent e) {
drag(e);
}
@Override
public void mouseReleased(MouseEvent e) {
drag(e);
pPressed = null;
}
private void drag(MouseEvent e) {
if (pPressed == null) {
return;
}
Point p = e.getPoint();
int tx = p.x - pPressed.x;
int ty = p.y - pPressed.y;
AffineTransform at = AffineTransform.getTranslateInstance(tx, ty);
myPath.transform(at);
pPressed = p;
repaint();
};
}
private static void createAndShowGui() {
Path2DExample mainPanel = new Path2DExample();
JFrame frame = new JFrame("Path2DExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
} | unknown | |
d6792 | train | Something I found extremely useful is to use the verifier pass.
So first, make sure basic opt flow works as intended, and that the input file is legal:
opt -verify vv.bc -o out.bc
Then make sure your pass results in a legal module:
opt -load ../../../Release+Asserts/lib/Hello.so -hello -verify vv.bc -o out.bc
If that still won't help, I'd fire up the debugger. | unknown | |
d6793 | train | The progress bar is shown on jobs that define the attribute environment
Here's an example of how to use it:
jobs:
deploy:
runs-on: ubuntu-latest
environment: Production
steps:
- run: ./deploy.sh --env prod
A: This is workflow reuse, you can read more in the documentation here
This progress bar shows jobs running in another workflow, which is probably not a good practice, but if you want this progress bar, you need to create various workflows and a centralized workflow that "reuses" all.
Github Actions show jobs running and done, you can track this why, no need for a progress bar. If you really want a progress bar directly for track jobs, you need to ask Github for this feature. | unknown | |
d6794 | train | I suggest you render the citations using the RefManageR package.
```{r}
library("RefManageR")
bib <- ReadBib(file = "references.bib")
invisible(data_frame(citation = RefManageR::TextCite(bib = bib)))
```
```{r}
data_frame(citation = RefManageR::TextCite(bib = bib,
"chambers_2012",
.opts = list(max.names = 1))) %>%
DT::datatable()
```
Or with link:
data_frame(citation = RefManageR::TextCite(bib = bib,
"chambers_2012",
.opts = list(style = "html",
max.names = 1))) %>%
DT::datatable(escape = FALSE)
Check ?BibOptions for more options on output format, link type, etc.
P.S. for whatever reason, the first time the function is called does not seem to fully take in consideration all options given, hence that invisible() call. | unknown | |
d6795 | train | Don't Include Separate links:
*
*Instead again Go to the google font
*Open Quattrocento Sans font
*Add Whatever weight and style you need for that font
*And, add this code to your website
Link will be like following:
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic' rel='stylesheet' type='text/css'>
A: Use this as an example:
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,800italic|Roboto:400,500,900|Oswald:400,300|Lato:400,100' rel='stylesheet' type='text/css'>
That way you can gather them all in one specific link.
A: try this example:
standart:
<link href='http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic,700,700italic&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
@import:
`@import url(http://fonts.googleapis.com/css?family=Quattrocento+Sans:400,400italic,700,700italic&subset=latin,latin-ext);`
javascript:
<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Quattrocento+Sans:400,400italic,700,700italic:latin,latin-ext' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})(); </script>
use: font-family: 'Quattrocento Sans', sans-serif; | unknown | |
d6796 | train | The danger of this approach is this: suppose you set this up. One day you receive no emails. What does this mean?
It could mean
*
*the supposed-to-be-running job is running successfully (and silently), and so the absence-of-running monitor job has nothing to say
or alternatively
*
*the supposed-to-be-running job is NOT running successfully, but the absence-of-running monitor job has ALSO failed
or even
*
*your server has caught fire, and can't send any emails even if it wants to
Don't seek to avoid receiving success messages - instead devise a strategy for coping with them. Because the only way to know that a job is running successfully is getting a message which says precisely this. | unknown | |
d6797 | train | My solution
public static boolean moreThanOnce(ArrayList<Integer> list, int searched)
{
int numCount = 0;
for (int thisNum : list) {
if (thisNum == searched)
numCount++;
}
return numCount > 1;
}
A: This will tell you if you have at least two same values in your ArrayList:
int first = portList.indexOf(someIntValue);
int last = portList.lastIndexOf(someIntValue);
if (first != -1 && first != last) {
// someIntValue exists more than once in the list (not sure how many times though)
}
If you really want to know how many duplicates of a given value you have, you need to iterate through the entire array. Something like this:
/**
* Will return a list of all indexes where the given value
* exists in the given array. The list will be empty if the
* given value does not exist at all.
*
* @param List<E> list
* @param E value
* @return List<Integer> a list of indexes in the list
*/
public <E> List<Integer> collectFrequency(List<E> list, E value) {
ArrayList<Integer> freqIndex = new ArrayList<Integer>();
E item;
for (int i=0, len=list.size(); i<len; i++) {
item = list.get(i);
if ((item == value) || (null != item && item.equals(value))) {
freqIndex.add(i);
}
}
return freqIndex;
}
if (!collectFrequency(portList, someIntValue).size() > 1) {
// Duplicate value
}
Or using the already availble method:
if (Collections.frequency(portList, someIntValue) > 1) {
// Duplicate value
}
A: If you are looking to do this in one method, then no. However, you could do it in two steps if you need to simply find out if it exists at least more than once in the List. You could do
int first = list.indexOf(object)
int second = list.lastIndexOf(object)
// Don't forget to also check to see if either are -1, the value does not exist at all.
if (first == second) {
// No Duplicates of object appear in the list
} else {
// Duplicate exists
}
A: You could use something like this to see how many times a specific value is there:
System.out.println(Collections.frequency(portList, 1));
// There can be whatever Integer, and I use 1, so you can understand
And to check if a specific value is there more than once you could use something like this:
if ( (Collections.frequency(portList, x)) > 1 ){
System.out.println(x + " is in portList more than once ");
}
A: Set portSet = new HashSet<Integer>();
portSet.addAll(portList);
boolean listContainsDuplicates = portSet.size() != portList.size();
A: I used the following solution to find out whether an ArrayList contains a number more than once. This solution comes very close to the one listed by user3690146, but it does not use a helper variable at all. After running it, you get "The number is listed more than once" as a return message.
public class Application {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(8);
list.add(1);
list.add(8);
int number = 8;
if (NumberMoreThenOnceInArray(list, number)) {
System.out.println("The number is listed more than once");
} else {
System.out.println("The number is not listed more than once");
}
}
public static boolean NumberMoreThenOnceInArray(ArrayList<Integer> list, int whichNumber) {
int numberCounter = 0;
for (int number : list) {
if (number == whichNumber) {
numberCounter++;
}
}
if (numberCounter > 1) {
return true;
}
return false;
}
}
A: Here is my solution (in Kotlin):
// getItemsMoreThan(list, 2) -> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3}
// getItemsMoreThan(list, 1)-> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3, 2.05=2}
fun getItemsMoreThan(list: List<Any>, moreThan: Int): Map<Any, Int> {
val mapNumbersByElement: Map<Any, Int> = getHowOftenItemsInList(list)
val findItem = mapNumbersByElement.filter { it.value > moreThan }
return findItem
}
// Return(map) how often an items is list.
// E.g.: [16.44, 200.00, 200.00, 33.33, 200.00, 0.00] -> {16.44=1, 200.00=3, 33.33=1, 0.00=1}
fun getHowOftenItemsInList(list: List<Any>): Map<Any, Int> {
val mapNumbersByItem = list.groupingBy { it }.eachCount()
return mapNumbersByItem
}
A: By looking at the question, we need to find out whether a value exists twice in an ArrayList. So I believe that we can reduce the overhead of "going through the entire list just to check whether the value only exists twice" by doing the simple check below.
public boolean moreThanOneMatch(int number, ArrayList<Integer> list) {
int count = 0;
for (int num : list) {
if (num == number) {
count ++ ;
if (count == 2) {
return true;
}
}
}
return false;
} | unknown | |
d6798 | train | Those are called "hooks" and you can read about them here: http://codex.wordpress.org/Plugin_API
Otherwise your code is essentially correct, with one mistake. You have jQuery as a dependency to jQuery, which means it is never loaded and subsequently bootstrap is never loaded:
wp_enqueue_script(
'jquery',
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
array( 'jquery' ), // <-- Problem
'1.9.1',
true
);
Solution:
wp_enqueue_script(
'jquery',
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
array(), // <-- There we go
'1.9.1',
true
);
But, there's one more thing. WordPress already has jQuery ready for you to enqueue (i.e. wp_enqueue_script( 'jquery' ); will load the local copy of jQuery). It isn't necessary but I think it is best practice to enqueue a CDN version of a script with a suffix, i.e.:
wp_enqueue_script(
'jquery-cdn',
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
array(),
'1.9.1',
true
);
// And then update your dependency on your bootstrap script
// to use the CDN jQuery:
wp_enqueue_script(
'bootstrap-js',
'//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js',
array( 'jquery-cdn' ),
true
); | unknown | |
d6799 | train | I think you want something like this:
insert into table1 (uniqueID, ID2, ID3, Number1, Number2)
select stuff(uniqueID, 1, 1, '9')
t1.ID2, t1.ID3,
Number1 * t2.MultiplyBy, t1.Number2 * MultiplyBy
from table1 t1 join
table2 t2
on t1.id2 = t2.id2 and t1.id3 = t2.id3; -- Are both keys needed?
A: Ill made a solution:
temp table inserted from table1 and tabl2 with join converted first char and multiplied the numbers and insert back with new data to original table | unknown | |
d6800 | train | Try this:
-(void)uploadPhoto{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://server.url"]];
NSData *imgData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);
NSDictionary *params = @{@"username": self.username, @"password" : self.password};
AFHTTPRequestOperation *operation = [manager POST:@"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imgData name:paramNameForImage fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[operation start];
} | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.