qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | giving height to widget which is throwing error solved my issue | I solved the problem this way:
```
children: <Widget>[
(controller== null)
? Container()
: controller.value.Initialized
? Container(child: CameraPreview(controller))
: Container(),
],
``` |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | I had this problem before and putting a height into the parent widget of `AspectRatio` fixed it. | giving height to widget which is throwing error solved my issue |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | giving height to widget which is throwing error solved my issue | Most of the time. `HOT RESTART (R)` will fix this error. |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | If you have created and assigned value to the variable and still it shows `getter 'value' was called on null`,
try to `Run` or `Restart` your app instead of `Hot Reload`. Because `Hot Reload` will not call `initstate()` (where variables assign their values) which will be only called by `Restarting` the app. | ```
aspectRatio: (this.controller?.value?.aspectRatio) ?? false
```
`aspectRatio` is a double value and you assigned it to `false` when it is `null`. Give it a double value. |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | If you have created and assigned value to the variable and still it shows `getter 'value' was called on null`,
try to `Run` or `Restart` your app instead of `Hot Reload`. Because `Hot Reload` will not call `initstate()` (where variables assign their values) which will be only called by `Restarting` the app. | I had this problem before and putting a height into the parent widget of `AspectRatio` fixed it. |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | In the `initState`, you don't always instantiate a controller.
Which means it can be `null`. Therefore inside the `build` method, you need to check null to not crash
```
(!this.controller?.value?.initialized ?? false) ? new Container() : cameraView ,
``` | ```
aspectRatio: (this.controller?.value?.aspectRatio) ?? false
```
`aspectRatio` is a double value and you assigned it to `false` when it is `null`. Give it a double value. |
50,304,502 | I'm building one app where on top of Camera view I need to show something. Here is my code.
```
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
void main() async {
runApp(new MaterialApp(
home: new CameraApp(),
));
}
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => new _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController controller;
var cameras;
bool cameraGot = false;
Future<Null> getCamera() async {
cameras = await availableCameras();
setState(() {
this.cameras = cameras;
this.cameraGot = true;
});
}
@override
void initState() {
getCamera();
super.initState();
if(this.cameraGot) {
controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// camera widget
Widget cameraView = new Container(
child: new Row(children: [
new Expanded(
child: new Column(
children: <Widget>[
new AspectRatio(
aspectRatio:
controller.value.aspectRatio,
child: new CameraPreview(controller)
)
]
),
)
])
);
return new Scaffold(
body: new Stack(
children: <Widget>[
!this.controller.value.initialized ? new Container() : cameraView,
// ---On top of Camera view add one mroe widget---
],
),
);
}
}
```
Whenever I'm building the app I'm getting following error...
```
I/flutter ( 6911): βββ‘ EXCEPTION CAUGHT BY WIDGETS LIBRARY ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
```
Can't able to fig. out what's the error. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50304502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304215/"
] | I solved the problem this way:
```
children: <Widget>[
(controller== null)
? Container()
: controller.value.Initialized
? Container(child: CameraPreview(controller))
: Container(),
],
``` | Most of the time. `HOT RESTART (R)` will fix this error. |
44,063,027 | I need to show confirm dialog message as html, this is how looks my dialog in component:
```
this.confirmationService.confirm({
header: "Change user status",
message: "Do you want to change user status to <strong>" + status + "</strong >?",
accept: () => {
//
}
});
```
and this is how it looks like on a page:
[](https://i.stack.imgur.com/jttBV.png)
I tried to do this two ways but without success
```
<p-confirmDialog width="500" appendTo="body">
<template pTemplate="body">
<span class="ui-confirmdialog-message">{{message}}</span>
</template>
```
```
<p-confirmDialog width="500" [innerHTML]="message"></p-confirmDialog>
``` | 2017/05/19 | [
"https://Stackoverflow.com/questions/44063027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471882/"
] | so this is kind of old, but for the future- the solution is to change the quote type of `message`.
so, change
```
message: "Do you want to change user status to <strong>" + status + "</strong >?",
```
to
```
message: `Do you want to change user status to <strong>" + status + "</strong >?`,
``` | PrimeNG ConfirmDialog's message element class is ui-confirmdialog-message
Set up a property (e.g: message) in your ts file
```
public message: string;
this.confirmationService.confirm({
header: "Change user status",
message: this.message,
accept: () => {
//
}
});
this.message = document.getElementsByClassName('ui-confirmdialog-message')[0].innerHTML = "Do you want to change user status to <span id='someOtherId'>" + status + "</span >?"
```
Then in your root styles.css, add this:
```
.ui-confirmdialog-message span#someOtherId { color: yourColor};
```
You can console.log "document.getElementsByClassName('ui-confirmdialog-message')" first to see what's in it. I got an array and the [0] element contains my initial ConfirmDialog message.
There might be a better way but I just happened to tackle this after seeing your question and it worked for me.[Check this result](https://i.stack.imgur.com/Bw2Le.png) |
24,789,585 | I am trying to update users **via AJAX** from my index view, so I have the following view:
```
<% @users.each do |user| %>
<tr>
<td><%= user.email %></td>
<td>
<%= form_for [:admin, user], :remote => true, :authenticity_token => true, :format => :json do |f| %>
<%= f.radio_button :approved, true, :checked => user.approved, :id => "user_approved_#{user.id}", :onclick => "this.form.submit();"%> Yes
<%= f.radio_button :approved, false, :checked => !user.approved, :id => "user_not_approved_#{user.id}", :onclick => "this.form.submit();" %> No
<% end %>
</td>
</tr>
<% end %>
```
And I have the controller update method that looks like this:
```
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update(user_params)
format.json { render nothing: true }
else
format.json { render nothing: true}
end
end
end
```
Even though the record gets correctly updated, it renders an empty page with the following URL: `admin/users/2.json` or whatever id is the record that was just updated.
Any idea how can I make it just render the index view where the form was submitted from? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24789585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196150/"
] | You should change your onclick handler, from `this.form.submit()` to `$(this).closest("form").trigger("submit");`
As you have it now you are directly submitting the form, so jquery-ujs can't handle the event. | Add this javascript snippet on your page:
```
$("form").on("ajax:complete", (xhr, status) ->
location.reload();
)
```
You might want to use ajax:success and ajax:error instead of ajax:complete.
If AJAX is not used then you can redirect to the index page after an update:
```
def update
@user = User.find(params[:id])
@user.update(user_params)
redirect_to :action => :index
end
``` |
24,789,585 | I am trying to update users **via AJAX** from my index view, so I have the following view:
```
<% @users.each do |user| %>
<tr>
<td><%= user.email %></td>
<td>
<%= form_for [:admin, user], :remote => true, :authenticity_token => true, :format => :json do |f| %>
<%= f.radio_button :approved, true, :checked => user.approved, :id => "user_approved_#{user.id}", :onclick => "this.form.submit();"%> Yes
<%= f.radio_button :approved, false, :checked => !user.approved, :id => "user_not_approved_#{user.id}", :onclick => "this.form.submit();" %> No
<% end %>
</td>
</tr>
<% end %>
```
And I have the controller update method that looks like this:
```
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update(user_params)
format.json { render nothing: true }
else
format.json { render nothing: true}
end
end
end
```
Even though the record gets correctly updated, it renders an empty page with the following URL: `admin/users/2.json` or whatever id is the record that was just updated.
Any idea how can I make it just render the index view where the form was submitted from? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24789585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196150/"
] | **JS**
Firstly, I don't understand *exactly* what you're trying to achieve
I surmise that you're trying to capture the updated data you've just sent? If this is the case, I would not use the `json` MIME-type; instead, I would just send a plain `JS` request.
The JSON mime type is mainly for the likes of `API`s - where noted objects are called back using the `json` structure. You'll be setting yourself up for a headache if you try and do things other than show the JSON data in your response
---
**Render**
You *may* be looking for the following:
```
#app/views/controller/your_view.html.erb
<%= form_for [:admin, user], :remote => true, :authenticity_token => true do |f| %>
#app/controllers/users_controller.rb
Class UsersController < ApplicationController
def update
respond_to do |format|
format.js { render :index }
format.json { render json: index_path.to_json }
end
end
end
```
---
**Fix**
From what you're saying, it seems you want to be able to do the following:
```
#app/assets/javascripts/application.js
$(document).on("ajax:success", "#your_form", function(data, status, xhr){
document.location.href= data; //have to find a way to use data's index path reference
});
``` | Add this javascript snippet on your page:
```
$("form").on("ajax:complete", (xhr, status) ->
location.reload();
)
```
You might want to use ajax:success and ajax:error instead of ajax:complete.
If AJAX is not used then you can redirect to the index page after an update:
```
def update
@user = User.find(params[:id])
@user.update(user_params)
redirect_to :action => :index
end
``` |
71,252,692 | When updating one DataFrame based on info from second one the NaN's are not transferred.
With below code
```
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'A':[1,2,3,4,5], 'B':[4,5,6,7,8]})
df2 = pd.DataFrame({'A':[1,2,3], 'B':[7,np.nan,6]})
df1.update(df2)
```
The new DataFrame will look as below:
[](https://i.stack.imgur.com/2JbAm.png)
So the value from df2 is not transferred as this is a NaN
[](https://i.stack.imgur.com/MPJy5.png)
Normally this is probably an expected outcome but not in the particular case that I'm working on.
For the moment how I deal with it is that I replace all NaNs with a value or string that signalizes to me that it's something I need to check but I was wondering if there is an actual solution to pass the NaN as an update?
[](https://i.stack.imgur.com/bWc7H.png) | 2022/02/24 | [
"https://Stackoverflow.com/questions/71252692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16659145/"
] | Try this,
```
bool isCountryChanged = false; // for update UI when country changed.
appBar: AppBar(
backgroundColor: Colors.transparent,
leading: const Icon(
Icons.public,
color: Colors.black,
size: 27,
),
title: const Text(
"Kelime ΓΔren",
style: TextStyle(color: Colors.black),
),
elevation: 0,
actions: [
DropdownButton<String>(
items: countryFlags
.map((country, flag) {
return MapEntry(
country,
DropdownMenuItem<String>(
value: flag,
child: Text(flag, style: TextStyle(fontSize: 20),),
));
})
.values
.toList(),
value: defaultFlag,
onChanged: (String? country) {
setState(() {
defaultFlag = country!;
isCountryChanged = true; });
// display circular indicator for 1 second.
Future.delayed(Duration(milliseconds: 1000), () async {
setState(() {
isCountryChanged = false; });
});
},
)
],
),
body:isCountryChanged? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
strokeWidth: 5,
); : // do stuff
``` | You can create a variable of type duration and then create a function which returns a future builder which is going to await for the duration to finish then display the country but in the mean time will display a circular indicator |
71,252,692 | When updating one DataFrame based on info from second one the NaN's are not transferred.
With below code
```
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'A':[1,2,3,4,5], 'B':[4,5,6,7,8]})
df2 = pd.DataFrame({'A':[1,2,3], 'B':[7,np.nan,6]})
df1.update(df2)
```
The new DataFrame will look as below:
[](https://i.stack.imgur.com/2JbAm.png)
So the value from df2 is not transferred as this is a NaN
[](https://i.stack.imgur.com/MPJy5.png)
Normally this is probably an expected outcome but not in the particular case that I'm working on.
For the moment how I deal with it is that I replace all NaNs with a value or string that signalizes to me that it's something I need to check but I was wondering if there is an actual solution to pass the NaN as an update?
[](https://i.stack.imgur.com/bWc7H.png) | 2022/02/24 | [
"https://Stackoverflow.com/questions/71252692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16659145/"
] | Need a ternary operator which can control your data is ready or not if not CircularProgressIndicator() will shown at appbar unless you can see your data.For example you can be try to fetch data from db that can be take time or maybe you cant fetch data so in this stuation must be show a progress indicator when data ready progress indicator bar will execute.
```
String? foo;
Future fetchDummy()async{
foo = await dummyData
}
foo !=nul? Text("$foo") : CircularProgressIndicator()
``` | You can create a variable of type duration and then create a function which returns a future builder which is going to await for the duration to finish then display the country but in the mean time will display a circular indicator |
41,553,641 | ```
["trnx_date"]=>
array(2) {
[0]=>
string(10) "2017-01-10"
[1]=>
string(10) "2017-01-10"
}
["curr_from"]=>
array(2) {
[0]=>
string(3) "USD"
[1]=>
string(3) "PHP"
}
["curr_from_amt"]=>
array(2) {
[0]=>
string(8) "4,000.00"
[1]=>
string(8) "3,000.00"
}
["curr_to"]=>
array(2) {
[0]=>
string(3) "GBP"
[1]=>
string(3) "SAR"
}
["curr_to_amt"]=>
array(2) {
[0]=>
string(8) "3,000.00"
[1]=>
string(8) "2,000.00"
}
["amount"]=>
array(2) {
[0]=>
string(8) "7,000.00"
[1]=>
string(8) "5,000.00"
}
```
I have the above array which was being submitted. This input was in sets of multiple field which was generated by dynamic table row. How can I group this into 1 (one) array so that I could save in the database? Like this:
```
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "USD",
'curr_from_amt' => "4,000.00",
'curr_to' => "GBP",
'curr_to_amt' => "3,000.00",
'amount' => "7,000.00"
),
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "PHP",
'curr_from_amt' => "3,000.00",
'curr_to' => "SAR",
'curr_to_amt' => "2,000.00",
'amount' => "5,000.00"
),
```
All of the above we being populated like this:
```
$trnx_date = $this->input->post('trnx_date');
$curr_from = $this->input->post('curr_from');
$curr_from_amt = $this->input->post('curr_from_amt');
$curr_to = $this->input->post('curr_to');
$curr_to_amt = $this->input->post('curr_to_amt');
$amount = $this->input->post('amount');
``` | 2017/01/09 | [
"https://Stackoverflow.com/questions/41553641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1504299/"
] | Assuming all the sub-arrays have the same length, you can use a simple `for` loop that iterates over the index of one of them, and use that to access each of the sub-arrays at that index. Then combine all of them into the associative array for each customer.
```
$result = array();
$keys = array_keys($array);
$len = count($array[$keys[0]]); // Get the length of one of the sub-arrays
for ($i = 0; $i < $len; $i++) {
$new = array();
foreach ($keys as $k) {
$new[$k] = $array[$k][$i];
}
$result[] = $new;
}
``` | How about this?
```
// assume $arr is your original data array
$keys = array_keys($arr);
$result = array();
foreach($keys as $key) {
$vals = $arr[$key];
foreach($vals as $i =>$val) {
if (!is_array($result[$i]) {
$result[$i] = array();
}
$result[$i][$key] = $val;
}
}
var_dump($result);
```
EDIT: added array check for $result[$i] |
41,553,641 | ```
["trnx_date"]=>
array(2) {
[0]=>
string(10) "2017-01-10"
[1]=>
string(10) "2017-01-10"
}
["curr_from"]=>
array(2) {
[0]=>
string(3) "USD"
[1]=>
string(3) "PHP"
}
["curr_from_amt"]=>
array(2) {
[0]=>
string(8) "4,000.00"
[1]=>
string(8) "3,000.00"
}
["curr_to"]=>
array(2) {
[0]=>
string(3) "GBP"
[1]=>
string(3) "SAR"
}
["curr_to_amt"]=>
array(2) {
[0]=>
string(8) "3,000.00"
[1]=>
string(8) "2,000.00"
}
["amount"]=>
array(2) {
[0]=>
string(8) "7,000.00"
[1]=>
string(8) "5,000.00"
}
```
I have the above array which was being submitted. This input was in sets of multiple field which was generated by dynamic table row. How can I group this into 1 (one) array so that I could save in the database? Like this:
```
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "USD",
'curr_from_amt' => "4,000.00",
'curr_to' => "GBP",
'curr_to_amt' => "3,000.00",
'amount' => "7,000.00"
),
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "PHP",
'curr_from_amt' => "3,000.00",
'curr_to' => "SAR",
'curr_to_amt' => "2,000.00",
'amount' => "5,000.00"
),
```
All of the above we being populated like this:
```
$trnx_date = $this->input->post('trnx_date');
$curr_from = $this->input->post('curr_from');
$curr_from_amt = $this->input->post('curr_from_amt');
$curr_to = $this->input->post('curr_to');
$curr_to_amt = $this->input->post('curr_to_amt');
$amount = $this->input->post('amount');
``` | 2017/01/09 | [
"https://Stackoverflow.com/questions/41553641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1504299/"
] | ```
$arr = array(
'trnx_date' => array('2017-01-10', '2017-01-10'),
'curr_from' => array('USD', 'PHP'),
'curr_from_amt' => array('4,000.00', '3,000.00'),
'curr_to' => array('GBP', 'SAR'),
'curr_to_amt' => array('3,000.00', '2,000.00'),
'amount' => array('7,000.00', '5,000.00')
);
$arr_out = array();
$arr_keys = array_keys($arr);
for($i = 0; $i < count($arr[$arr_keys[0]]); $i++) {
$new_arr = array();
foreach($arr_keys as $key => $value) {
$new_arr[$value] = $arr[$value][$i];
}
$arr_out[] = $new_arr;
}
var_dump($arr_out);
```
Hope it helps! | How about this?
```
// assume $arr is your original data array
$keys = array_keys($arr);
$result = array();
foreach($keys as $key) {
$vals = $arr[$key];
foreach($vals as $i =>$val) {
if (!is_array($result[$i]) {
$result[$i] = array();
}
$result[$i][$key] = $val;
}
}
var_dump($result);
```
EDIT: added array check for $result[$i] |
61,469,253 | I have an `appsettings.json` file where I want to transform the value located at:
```
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
```
I found the following answer so I know that an app service can retrieve values directly from the key vault:
<https://stackoverflow.com/a/59994040/3850405>
This is not the reason for asking. Since Microsoft offers `JSON variable substitution` I still think this should be possible since the only problem is the nested value. The question above is similar but I would like to specify a bit more what has already been tested and where I got stuck.
<https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/transforms-variable-substitution?view=azure-devops&tabs=Classic#json-variable-substitution>
It is possible to use Pipelines -> Library -> Variable group
[](https://i.stack.imgur.com/j9Fid.png)
or a Azure Key Vault Task to get the secret value.
[](https://i.stack.imgur.com/vpNSS.png)
The problem is the secret value can not contain dots:
[](https://i.stack.imgur.com/q88an.png)
>
> Please provide a valid secret name. Secret names can only contain
> alphanumeric characters and dashes.
>
>
>
Neither in a linked Variable group or in a Azure Key Vault Task I'm allowed to rewrite a secret name to another variable name.
Looking at the sample below if the secret name was `ConnectionStringsDefaultConnection` I could access the value like this `$(ConnectionStringsDefaultConnection)` but I don't know how to rename it.
<https://azuredevopslabs.com/labs/vstsextend/azurekeyvault/>
I have found a task that could get the job done but it requires a third party Release task. This is not acceptable since the project only allows Tasks written by Microsoft.
[](https://i.stack.imgur.com/m3BTf.png)
<https://daniel-krzyczkowski.github.io/How-to-inject-Azure-Key-Vault-secrets-in-the-Azure-DevOps-CICD-pipelines/>
I also know that a Pipeline variable can be used to store the value but we wan't to have a single source of truth and that is the Azure Key Vault Secret.
[](https://i.stack.imgur.com/adDYD.png) | 2020/04/27 | [
"https://Stackoverflow.com/questions/61469253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3850405/"
] | Read a similar question from VSTS (Visual Studio Team Services) and was able to solve it.
Created a `Pipeline variable` called `ConnectionStrings.DefaultConnection` that had a reference value to my linked variable group.
If my secret was named `ConnectionStringsDefaultConnection` I would hook this up as a linked variable and then add `$(ConnectionStringsDefaultConnection)` as a value.
[](https://i.stack.imgur.com/llmm4.png)
Source:
<https://stackoverflow.com/a/47787972/3850405> | One of the option will be to use Key Vault directly in your application instead of replacing your appsettings.json. You can configure this in `CreateHostBuilder` method:
```cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
if (context.HostingEnvironment.IsProduction())
{
var builtConfig = config.Build();
using (var store = new X509Store(StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates
.Find(X509FindType.FindByThumbprint,
builtConfig["AzureADCertThumbprint"], false);
config.AddAzureKeyVault(
$"https://{builtConfig["KeyVaultName"]}.vault.azure.net/",
builtConfig["AzureADApplicationId"],
certs.OfType<X509Certificate2>().Single());
store.Close();
}
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
```
Please check the [documentation](https://learn.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-3.1). |
61,469,253 | I have an `appsettings.json` file where I want to transform the value located at:
```
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
```
I found the following answer so I know that an app service can retrieve values directly from the key vault:
<https://stackoverflow.com/a/59994040/3850405>
This is not the reason for asking. Since Microsoft offers `JSON variable substitution` I still think this should be possible since the only problem is the nested value. The question above is similar but I would like to specify a bit more what has already been tested and where I got stuck.
<https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/transforms-variable-substitution?view=azure-devops&tabs=Classic#json-variable-substitution>
It is possible to use Pipelines -> Library -> Variable group
[](https://i.stack.imgur.com/j9Fid.png)
or a Azure Key Vault Task to get the secret value.
[](https://i.stack.imgur.com/vpNSS.png)
The problem is the secret value can not contain dots:
[](https://i.stack.imgur.com/q88an.png)
>
> Please provide a valid secret name. Secret names can only contain
> alphanumeric characters and dashes.
>
>
>
Neither in a linked Variable group or in a Azure Key Vault Task I'm allowed to rewrite a secret name to another variable name.
Looking at the sample below if the secret name was `ConnectionStringsDefaultConnection` I could access the value like this `$(ConnectionStringsDefaultConnection)` but I don't know how to rename it.
<https://azuredevopslabs.com/labs/vstsextend/azurekeyvault/>
I have found a task that could get the job done but it requires a third party Release task. This is not acceptable since the project only allows Tasks written by Microsoft.
[](https://i.stack.imgur.com/m3BTf.png)
<https://daniel-krzyczkowski.github.io/How-to-inject-Azure-Key-Vault-secrets-in-the-Azure-DevOps-CICD-pipelines/>
I also know that a Pipeline variable can be used to store the value but we wan't to have a single source of truth and that is the Azure Key Vault Secret.
[](https://i.stack.imgur.com/adDYD.png) | 2020/04/27 | [
"https://Stackoverflow.com/questions/61469253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3850405/"
] | Read a similar question from VSTS (Visual Studio Team Services) and was able to solve it.
Created a `Pipeline variable` called `ConnectionStrings.DefaultConnection` that had a reference value to my linked variable group.
If my secret was named `ConnectionStringsDefaultConnection` I would hook this up as a linked variable and then add `$(ConnectionStringsDefaultConnection)` as a value.
[](https://i.stack.imgur.com/llmm4.png)
Source:
<https://stackoverflow.com/a/47787972/3850405> | I managed to resolve this issue automatically without the need to manage all the variables by myself.
I used the idea of @Ogglas and made this little script in an Azure Powershell task.
```
$results = Get-AzKeyVaultSecret -VaultName $(key-vault-name)
foreach ($result in $results)
{
if ($result.Name.Contains("--")) {
$key = $result.Name.Replace('--', '.')
$value = '$(' + $result.Name.ToString() + ')'
Write-Host "##vso[task.setvariable variable=$key;issecret=true;]$value"
}
}
```
The "[Get-AzKeyVaultSecret](https://learn.microsoft.com/en-us/powershell/module/az.keyvault/get-azkeyvaultsecret?view=azps-8.3.0#example-1-get-all-current-versions-of-all-secrets-in-a-key-vault)" allow you to list all the variables present in your KeyVault and the "[Write-Host "##vso[task.setvariable...](https://learn.microsoft.com/en-us/azure/devops/pipelines/process/set-variables-scripts?view=azure-devops&tabs=powershell)" allow you to create variable that can be used in future tasks.
Like that, you can keep the KeyVault naming convention for the secrets, retrieves them in your pipeline and uses the task "[FileTransform](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/file-transform-v2?view=azure-pipelines&viewFallbackFrom=azure-devops)" from Microsoft to replace the values
See the example in a release:
 |
61,469,253 | I have an `appsettings.json` file where I want to transform the value located at:
```
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
```
I found the following answer so I know that an app service can retrieve values directly from the key vault:
<https://stackoverflow.com/a/59994040/3850405>
This is not the reason for asking. Since Microsoft offers `JSON variable substitution` I still think this should be possible since the only problem is the nested value. The question above is similar but I would like to specify a bit more what has already been tested and where I got stuck.
<https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/transforms-variable-substitution?view=azure-devops&tabs=Classic#json-variable-substitution>
It is possible to use Pipelines -> Library -> Variable group
[](https://i.stack.imgur.com/j9Fid.png)
or a Azure Key Vault Task to get the secret value.
[](https://i.stack.imgur.com/vpNSS.png)
The problem is the secret value can not contain dots:
[](https://i.stack.imgur.com/q88an.png)
>
> Please provide a valid secret name. Secret names can only contain
> alphanumeric characters and dashes.
>
>
>
Neither in a linked Variable group or in a Azure Key Vault Task I'm allowed to rewrite a secret name to another variable name.
Looking at the sample below if the secret name was `ConnectionStringsDefaultConnection` I could access the value like this `$(ConnectionStringsDefaultConnection)` but I don't know how to rename it.
<https://azuredevopslabs.com/labs/vstsextend/azurekeyvault/>
I have found a task that could get the job done but it requires a third party Release task. This is not acceptable since the project only allows Tasks written by Microsoft.
[](https://i.stack.imgur.com/m3BTf.png)
<https://daniel-krzyczkowski.github.io/How-to-inject-Azure-Key-Vault-secrets-in-the-Azure-DevOps-CICD-pipelines/>
I also know that a Pipeline variable can be used to store the value but we wan't to have a single source of truth and that is the Azure Key Vault Secret.
[](https://i.stack.imgur.com/adDYD.png) | 2020/04/27 | [
"https://Stackoverflow.com/questions/61469253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3850405/"
] | I managed to resolve this issue automatically without the need to manage all the variables by myself.
I used the idea of @Ogglas and made this little script in an Azure Powershell task.
```
$results = Get-AzKeyVaultSecret -VaultName $(key-vault-name)
foreach ($result in $results)
{
if ($result.Name.Contains("--")) {
$key = $result.Name.Replace('--', '.')
$value = '$(' + $result.Name.ToString() + ')'
Write-Host "##vso[task.setvariable variable=$key;issecret=true;]$value"
}
}
```
The "[Get-AzKeyVaultSecret](https://learn.microsoft.com/en-us/powershell/module/az.keyvault/get-azkeyvaultsecret?view=azps-8.3.0#example-1-get-all-current-versions-of-all-secrets-in-a-key-vault)" allow you to list all the variables present in your KeyVault and the "[Write-Host "##vso[task.setvariable...](https://learn.microsoft.com/en-us/azure/devops/pipelines/process/set-variables-scripts?view=azure-devops&tabs=powershell)" allow you to create variable that can be used in future tasks.
Like that, you can keep the KeyVault naming convention for the secrets, retrieves them in your pipeline and uses the task "[FileTransform](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/file-transform-v2?view=azure-pipelines&viewFallbackFrom=azure-devops)" from Microsoft to replace the values
See the example in a release:
 | One of the option will be to use Key Vault directly in your application instead of replacing your appsettings.json. You can configure this in `CreateHostBuilder` method:
```cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
if (context.HostingEnvironment.IsProduction())
{
var builtConfig = config.Build();
using (var store = new X509Store(StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates
.Find(X509FindType.FindByThumbprint,
builtConfig["AzureADCertThumbprint"], false);
config.AddAzureKeyVault(
$"https://{builtConfig["KeyVaultName"]}.vault.azure.net/",
builtConfig["AzureADApplicationId"],
certs.OfType<X509Certificate2>().Single());
store.Close();
}
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
```
Please check the [documentation](https://learn.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-3.1). |
2,016 | Hi guys, can any one please give me an examples of Subtextual sound and Visual amplification sound within a film. | 2010/07/16 | [
"https://sound.stackexchange.com/questions/2016",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/442/"
] | Emmanuel,
Can you clarify what exactly you are asking? I say this because it would be useful to have some idea about what specifically you are looking to find out.
Film sound will contain a lot of subtexts in varying degrees. From a basic illiciting of an emotional response from the audience (animal sounds layered into vehicle sounds for example) right through to sounds meaning 2 different things at the same time. For example, I just put in the sound of a ticking Grandfather's Clock into a scene. Firstly because you can see one in the background, this adds sense of realism to the show. Secondly because it's an old sound you don't come across so much these days and as the room we are in is an antique shop then it adds to the sense of the old. Same sound but given 2 meanings.
As for Visual Amplification, it's not a term I've ever come across in relation to sound. Are you talking about [Added Value](http://filmsound.org/chion/Added.htm)?
Ian | Thank you Ian.....Basically Visual Amplication sound is one of the 6 Areas of sound within a film, which are found on the David Sonnenschein`s book (The Expressive Power Of Music, Voice And Sound Effects In Cinema), but I needed a clear understandind of how it works within a film..By the way I`m still a student whose in 2nd year studying Sound Design, so I`ll be aksing you lots of questions based on sound...
Cheers |
9,834,289 | Using the native Android MediaPlayer class I am able to play Shoutcast streams. Furthermore, using streamscraper (http://code.google.com/p/streamscraper/) I am able to get the metadata for the current playing song in the stream.
I would like to know if there is a way to be notified when the song in the radio stream changes, using my current setup (MediaPlayer and streamscraper).
If someone could point me in the right direction, I would be grateful. | 2012/03/23 | [
"https://Stackoverflow.com/questions/9834289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345191/"
] | Shorthand properties (such as `border`) are not supported by `jQuery.css()`.
<http://api.jquery.com/css/> | I'm not sure this will solve your problem, but I would start by trying to clean up the way you're making that link. You may have missed one or two quotes. Instead of the confusion of escaping or failing to escape double quotes, just surround your string with single quotes:
```
var merkTag = '<a class="deletemerk" href="http://localhost/website/remove_merk.php?id='
+ this.pkFavorietemerken
+ '">'
+ this.merken
+ '</a>';
```
This leaves you free to use double quotes when you're building an HTML string. I've used multiple lines here just for clarity's sake. Clarity over brevity. |
9,834,289 | Using the native Android MediaPlayer class I am able to play Shoutcast streams. Furthermore, using streamscraper (http://code.google.com/p/streamscraper/) I am able to get the metadata for the current playing song in the stream.
I would like to know if there is a way to be notified when the song in the radio stream changes, using my current setup (MediaPlayer and streamscraper).
If someone could point me in the right direction, I would be grateful. | 2012/03/23 | [
"https://Stackoverflow.com/questions/9834289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345191/"
] | If you want to use all the three properties of border, try defining them independently , it might solve your problem. | I'm not sure this will solve your problem, but I would start by trying to clean up the way you're making that link. You may have missed one or two quotes. Instead of the confusion of escaping or failing to escape double quotes, just surround your string with single quotes:
```
var merkTag = '<a class="deletemerk" href="http://localhost/website/remove_merk.php?id='
+ this.pkFavorietemerken
+ '">'
+ this.merken
+ '</a>';
```
This leaves you free to use double quotes when you're building an HTML string. I've used multiple lines here just for clarity's sake. Clarity over brevity. |
9,834,289 | Using the native Android MediaPlayer class I am able to play Shoutcast streams. Furthermore, using streamscraper (http://code.google.com/p/streamscraper/) I am able to get the metadata for the current playing song in the stream.
I would like to know if there is a way to be notified when the song in the radio stream changes, using my current setup (MediaPlayer and streamscraper).
If someone could point me in the right direction, I would be grateful. | 2012/03/23 | [
"https://Stackoverflow.com/questions/9834289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345191/"
] | Shorthand properties (such as `border`) are not supported by `jQuery.css()`.
<http://api.jquery.com/css/> | If you want to use all the three properties of border, try defining them independently , it might solve your problem. |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | To let Jackson know how to create an object for deserialization, use the [`@JsonCreator`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonCreator.html) and [`@JsonProperty`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonProperty.html) annotations for your constructors, like this:
```
@JsonCreator
public ImportResultItemImpl(@JsonProperty("name") String name,
@JsonProperty("resultType") ImportResultItemType resultType,
@JsonProperty("message") String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
``` | You can use a private default constructor, Jackson will then fill the fields via reflection even if they are private final.
EDIT: And use a protected/package-protected default constructor for parent classes if you have inheritance. |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | To let Jackson know how to create an object for deserialization, use the [`@JsonCreator`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonCreator.html) and [`@JsonProperty`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonProperty.html) annotations for your constructors, like this:
```
@JsonCreator
public ImportResultItemImpl(@JsonProperty("name") String name,
@JsonProperty("resultType") ImportResultItemType resultType,
@JsonProperty("message") String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
``` | The first answer of Sergei Petunin is right.
However, we could simplify code with removing redundant @JsonProperty annotations on each parameter of constructor.
It can be done with adding com.fasterxml.jackson.module.paramnames.ParameterNamesModule into ObjectMapper:
```
new ObjectMapper()
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES))
```
(Btw: this module is registered by default in SpringBoot. If you use ObjectMapper bean from JacksonObjectMapperConfiguration or if you create your own ObjectMapper with bean Jackson2ObjectMapperBuilder then you can skip manual registration of the module)
For example:
```
public class FieldValidationError {
private final String field;
private final String error;
@JsonCreator
public FieldValidationError(String field,
String error) {
this.field = field;
this.error = error;
}
public String getField() {
return field;
}
public String getError() {
return error;
}
}
```
and ObjectMapper deserializes this json without any errors:
```
{
"field": "email",
"error": "some text"
}
``` |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | To let Jackson know how to create an object for deserialization, use the [`@JsonCreator`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonCreator.html) and [`@JsonProperty`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonProperty.html) annotations for your constructors, like this:
```
@JsonCreator
public ImportResultItemImpl(@JsonProperty("name") String name,
@JsonProperty("resultType") ImportResultItemType resultType,
@JsonProperty("message") String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
``` | It's 2021, I had the same issue. Unfortunately, the previous answers in this thread weren't helpful in my case, because:
1. I need to deserialize `java.net.HttpCookie` class object. I can't modify it.
2. Due to some reasons, I use jackson-databind-2.11.0 version. `ParameterNamesModule` has been added in 3+ version.
So, here's the solution I've found for my case.
You can just use DeserializationProblemHandler:
```
objectMapper.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, ValueInstantiator valueInsta, JsonParser p, String msg) throws IOException {
return super.handleMissingInstantiator(ctxt, instClass, valueInsta, p, msg);
}
});
```
Just return the object which you're expecting |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | To let Jackson know how to create an object for deserialization, use the [`@JsonCreator`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonCreator.html) and [`@JsonProperty`](http://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonProperty.html) annotations for your constructors, like this:
```
@JsonCreator
public ImportResultItemImpl(@JsonProperty("name") String name,
@JsonProperty("resultType") ImportResultItemType resultType,
@JsonProperty("message") String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
``` | Since Java 14 and [Jackson 2.12.0](https://github.com/FasterXML/jackson-future-ideas/issues/46) you can use a [record](https://docs.oracle.com/en/java/javase/14/language/records.html) class like this:
```
public record ImportResultItemImpl(String name, ImportResultItemType resultType, String message) implements ImportResultItem {
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
// calling the default constructor
this(name, resultType, null);
}
}
```
Also, you will have to refactor your interface and usage because record's getters do not start with `get` or `is`:
```
public interface ImportResultItem {
String name();
ImportResultItemType resultType();
String message();
}
``` |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | You can use a private default constructor, Jackson will then fill the fields via reflection even if they are private final.
EDIT: And use a protected/package-protected default constructor for parent classes if you have inheritance. | The first answer of Sergei Petunin is right.
However, we could simplify code with removing redundant @JsonProperty annotations on each parameter of constructor.
It can be done with adding com.fasterxml.jackson.module.paramnames.ParameterNamesModule into ObjectMapper:
```
new ObjectMapper()
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES))
```
(Btw: this module is registered by default in SpringBoot. If you use ObjectMapper bean from JacksonObjectMapperConfiguration or if you create your own ObjectMapper with bean Jackson2ObjectMapperBuilder then you can skip manual registration of the module)
For example:
```
public class FieldValidationError {
private final String field;
private final String error;
@JsonCreator
public FieldValidationError(String field,
String error) {
this.field = field;
this.error = error;
}
public String getField() {
return field;
}
public String getError() {
return error;
}
}
```
and ObjectMapper deserializes this json without any errors:
```
{
"field": "email",
"error": "some text"
}
``` |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | You can use a private default constructor, Jackson will then fill the fields via reflection even if they are private final.
EDIT: And use a protected/package-protected default constructor for parent classes if you have inheritance. | It's 2021, I had the same issue. Unfortunately, the previous answers in this thread weren't helpful in my case, because:
1. I need to deserialize `java.net.HttpCookie` class object. I can't modify it.
2. Due to some reasons, I use jackson-databind-2.11.0 version. `ParameterNamesModule` has been added in 3+ version.
So, here's the solution I've found for my case.
You can just use DeserializationProblemHandler:
```
objectMapper.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, ValueInstantiator valueInsta, JsonParser p, String msg) throws IOException {
return super.handleMissingInstantiator(ctxt, instClass, valueInsta, p, msg);
}
});
```
Just return the object which you're expecting |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | You can use a private default constructor, Jackson will then fill the fields via reflection even if they are private final.
EDIT: And use a protected/package-protected default constructor for parent classes if you have inheritance. | Since Java 14 and [Jackson 2.12.0](https://github.com/FasterXML/jackson-future-ideas/issues/46) you can use a [record](https://docs.oracle.com/en/java/javase/14/language/records.html) class like this:
```
public record ImportResultItemImpl(String name, ImportResultItemType resultType, String message) implements ImportResultItem {
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
// calling the default constructor
this(name, resultType, null);
}
}
```
Also, you will have to refactor your interface and usage because record's getters do not start with `get` or `is`:
```
public interface ImportResultItem {
String name();
ImportResultItemType resultType();
String message();
}
``` |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | The first answer of Sergei Petunin is right.
However, we could simplify code with removing redundant @JsonProperty annotations on each parameter of constructor.
It can be done with adding com.fasterxml.jackson.module.paramnames.ParameterNamesModule into ObjectMapper:
```
new ObjectMapper()
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES))
```
(Btw: this module is registered by default in SpringBoot. If you use ObjectMapper bean from JacksonObjectMapperConfiguration or if you create your own ObjectMapper with bean Jackson2ObjectMapperBuilder then you can skip manual registration of the module)
For example:
```
public class FieldValidationError {
private final String field;
private final String error;
@JsonCreator
public FieldValidationError(String field,
String error) {
this.field = field;
this.error = error;
}
public String getField() {
return field;
}
public String getError() {
return error;
}
}
```
and ObjectMapper deserializes this json without any errors:
```
{
"field": "email",
"error": "some text"
}
``` | It's 2021, I had the same issue. Unfortunately, the previous answers in this thread weren't helpful in my case, because:
1. I need to deserialize `java.net.HttpCookie` class object. I can't modify it.
2. Due to some reasons, I use jackson-databind-2.11.0 version. `ParameterNamesModule` has been added in 3+ version.
So, here's the solution I've found for my case.
You can just use DeserializationProblemHandler:
```
objectMapper.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, ValueInstantiator valueInsta, JsonParser p, String msg) throws IOException {
return super.handleMissingInstantiator(ctxt, instClass, valueInsta, p, msg);
}
});
```
Just return the object which you're expecting |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | The first answer of Sergei Petunin is right.
However, we could simplify code with removing redundant @JsonProperty annotations on each parameter of constructor.
It can be done with adding com.fasterxml.jackson.module.paramnames.ParameterNamesModule into ObjectMapper:
```
new ObjectMapper()
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES))
```
(Btw: this module is registered by default in SpringBoot. If you use ObjectMapper bean from JacksonObjectMapperConfiguration or if you create your own ObjectMapper with bean Jackson2ObjectMapperBuilder then you can skip manual registration of the module)
For example:
```
public class FieldValidationError {
private final String field;
private final String error;
@JsonCreator
public FieldValidationError(String field,
String error) {
this.field = field;
this.error = error;
}
public String getField() {
return field;
}
public String getError() {
return error;
}
}
```
and ObjectMapper deserializes this json without any errors:
```
{
"field": "email",
"error": "some text"
}
``` | Since Java 14 and [Jackson 2.12.0](https://github.com/FasterXML/jackson-future-ideas/issues/46) you can use a [record](https://docs.oracle.com/en/java/javase/14/language/records.html) class like this:
```
public record ImportResultItemImpl(String name, ImportResultItemType resultType, String message) implements ImportResultItem {
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
// calling the default constructor
this(name, resultType, null);
}
}
```
Also, you will have to refactor your interface and usage because record's getters do not start with `get` or `is`:
```
public interface ImportResultItem {
String name();
ImportResultItemType resultType();
String message();
}
``` |
30,568,353 | I want to serialize and deserialize an immutable object using com.fasterxml.jackson.databind.ObjectMapper.
The immutable class looks like this (just 3 internal attributes, getters and constructors):
```
public final class ImportResultItemImpl implements ImportResultItem {
private final ImportResultItemType resultType;
private final String message;
private final String name;
public ImportResultItemImpl(String name, ImportResultItemType resultType, String message) {
super();
this.resultType = resultType;
this.message = message;
this.name = name;
}
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
super();
this.resultType = resultType;
this.name = name;
this.message = null;
}
@Override
public ImportResultItemType getResultType() {
return this.resultType;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public String getName() {
return this.name;
}
}
```
However when I run this unit test:
```
@Test
public void testObjectMapper() throws Exception {
ImportResultItemImpl originalItem = new ImportResultItemImpl("Name1", ImportResultItemType.SUCCESS);
String serialized = new ObjectMapper().writeValueAsString((ImportResultItemImpl) originalItem);
System.out.println("serialized: " + serialized);
//this line will throw exception
ImportResultItemImpl deserialized = new ObjectMapper().readValue(serialized, ImportResultItemImpl.class);
}
```
I get this exception:
```
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class eu.ibacz.pdkd.core.service.importcommon.ImportResultItemImpl]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"resultType":"SUCCESS","message":null,"name":"Name1"}; line: 1, column: 2]
at
... nothing interesting here
```
This exception asks me to create a default constructor, but this is an immutable object, so I don't want to have it. How would it set the internal attributes? It would totally confuse the user of the API.
**So my question is:** Can I somehow de/serialize immutable objects without default constructor? | 2015/06/01 | [
"https://Stackoverflow.com/questions/30568353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2717958/"
] | It's 2021, I had the same issue. Unfortunately, the previous answers in this thread weren't helpful in my case, because:
1. I need to deserialize `java.net.HttpCookie` class object. I can't modify it.
2. Due to some reasons, I use jackson-databind-2.11.0 version. `ParameterNamesModule` has been added in 3+ version.
So, here's the solution I've found for my case.
You can just use DeserializationProblemHandler:
```
objectMapper.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, ValueInstantiator valueInsta, JsonParser p, String msg) throws IOException {
return super.handleMissingInstantiator(ctxt, instClass, valueInsta, p, msg);
}
});
```
Just return the object which you're expecting | Since Java 14 and [Jackson 2.12.0](https://github.com/FasterXML/jackson-future-ideas/issues/46) you can use a [record](https://docs.oracle.com/en/java/javase/14/language/records.html) class like this:
```
public record ImportResultItemImpl(String name, ImportResultItemType resultType, String message) implements ImportResultItem {
public ImportResultItemImpl(String name, ImportResultItemType resultType) {
// calling the default constructor
this(name, resultType, null);
}
}
```
Also, you will have to refactor your interface and usage because record's getters do not start with `get` or `is`:
```
public interface ImportResultItem {
String name();
ImportResultItemType resultType();
String message();
}
``` |
6,662,497 | I have some links that have \_2 if they are duplicates, I want to keep the href the same but change the text to remove the \_2, sometimes there's an \_3 or \_4 so I just want to remove from the text everything after the \_.
Here is an example of the href's I want to change
```
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002837/Dior-Charlize-Theron-2">Charlize-Theron_2</a></div>
</li>
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002840/Dior-Natalie-Portman">Natalie-Portman</a></div>
</li>
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002838/Dior-Sharon-Stone-4">Sharon-Stone_4</a></div>
</li>
```
I have already found a code that replaces the hyphens with space's and this works well, so my code so far is
```
$(".images li").find("a").each(function(i){
$(this).text($(this).text().replace(/-/g," "));
$(this).text($(this).text().replace(/_/g,""));//removes the _
});
```
Any Ideas? Thanks for replys | 2011/07/12 | [
"https://Stackoverflow.com/questions/6662497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526938/"
] | you can try this:
```
$(this).text($(this).text().replace(/_\d+$/, "_"));
``` | ```
$(this).text($(this).text().split('_')[0]);
``` |
6,662,497 | I have some links that have \_2 if they are duplicates, I want to keep the href the same but change the text to remove the \_2, sometimes there's an \_3 or \_4 so I just want to remove from the text everything after the \_.
Here is an example of the href's I want to change
```
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002837/Dior-Charlize-Theron-2">Charlize-Theron_2</a></div>
</li>
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002840/Dior-Natalie-Portman">Natalie-Portman</a></div>
</li>
<li style="display: list-item;" class="menu-item">
<div><a href="/_webapp_4002838/Dior-Sharon-Stone-4">Sharon-Stone_4</a></div>
</li>
```
I have already found a code that replaces the hyphens with space's and this works well, so my code so far is
```
$(".images li").find("a").each(function(i){
$(this).text($(this).text().replace(/-/g," "));
$(this).text($(this).text().replace(/_/g,""));//removes the _
});
```
Any Ideas? Thanks for replys | 2011/07/12 | [
"https://Stackoverflow.com/questions/6662497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526938/"
] | you can try this:
```
$(this).text($(this).text().replace(/_\d+$/, "_"));
``` | `$(this).text($(this).text().replace(/_([0-9])+/, ''));` |
39,851,616 | I tried to switch to popup alert and click on OK button, but i got an error saying that xpath (for OK button) is not found.
But this is working for me sometimes using the same code. Could anyone help me out on this. I tried all possible ways that is available in blogs. But i couldn't make it | 2016/10/04 | [
"https://Stackoverflow.com/questions/39851616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318753/"
] | you need to move control to your pop-up window first before doing any operation on pop-up window:-
below code is to move selenium control on pop-up window
```
driver.switchTo().alert();
```
by writing below line
```
alert.accept();
```
alert will get close | Based on the original question and the subsequent comments, I suspect what you're dealing with is a browser pop up window and not an alert. So this won't work
```
driver.switchTo().alert().accept();
```
You need to use window handles
```
Set<String> handles = driver.getWindowHandles();
Iterator<String> windows = handles.iterator();
String parent = windows.next();
String child = windows.next();
driver.switchTo().window(child);
driver.findElement(By.xpath("insert xpath to OK button")).click();
driver.switchTo().window(parent);
//continue with steps on parent window
```
Note: ensure that you add the required synchronization to the code snippet above |
131,056 | In the [Matrix](https://matrix.org/) instant messaging protocol, when using the reference implementation of the Matrix server (called `synapse`), there is an [admin API](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/) with functions like [resetting a password](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/user_admin_api.rst#reset-password) for a user etc..
Accessing this requires an [`access_token`](https://matrix.org/docs/spec/client_server/latest#using-access-tokens) "API key" of a server admin user.
How do I get one? | 2019/06/20 | [
"https://webapps.stackexchange.com/questions/131056",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/75677/"
] | Solution to find your access token:
1. Log in to the account you want to get the access token for. Click on the name in the top left corner, then "Settings".
2. Click the "Help & About" tab (left side of the dialog).
3. Scroll to the bottom and click on `<click to reveal>` part of Access
Token.
4. Copy your access token to a safe place. | These `access_token` API keys were listed in the [Riot](https://riot.im/) web application until not too long ago, somewhere under the account settings. In the newest version, I could no longer find them there.
So instead, I use a technique I found [here](https://github.com/matrix-org/synapse/issues/1707#issuecomment-405455882), which is basically a login procedure done with `curl`. The server's answer will contain the `access_token`.
1. Find out the Matrix user ID and password of a server admin user. The username has to be in the fully qualified form, for example `@user:example.com`.
2. Execute the following command on a Linux-based system that has `curl` installed. Of course, supply the address of you Matrix server for `example.com`, and also your Matrix user ID and password.
```
curl -XPOST \
-d '{"type":"m.login.password", "user":"<userid>", "password":"<password>"}' \
"https://example.com:8448/_matrix/client/r0/login"
``` |
131,056 | In the [Matrix](https://matrix.org/) instant messaging protocol, when using the reference implementation of the Matrix server (called `synapse`), there is an [admin API](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/) with functions like [resetting a password](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/user_admin_api.rst#reset-password) for a user etc..
Accessing this requires an [`access_token`](https://matrix.org/docs/spec/client_server/latest#using-access-tokens) "API key" of a server admin user.
How do I get one? | 2019/06/20 | [
"https://webapps.stackexchange.com/questions/131056",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/75677/"
] | These `access_token` API keys were listed in the [Riot](https://riot.im/) web application until not too long ago, somewhere under the account settings. In the newest version, I could no longer find them there.
So instead, I use a technique I found [here](https://github.com/matrix-org/synapse/issues/1707#issuecomment-405455882), which is basically a login procedure done with `curl`. The server's answer will contain the `access_token`.
1. Find out the Matrix user ID and password of a server admin user. The username has to be in the fully qualified form, for example `@user:example.com`.
2. Execute the following command on a Linux-based system that has `curl` installed. Of course, supply the address of you Matrix server for `example.com`, and also your Matrix user ID and password.
```
curl -XPOST \
-d '{"type":"m.login.password", "user":"<userid>", "password":"<password>"}' \
"https://example.com:8448/_matrix/client/r0/login"
``` | With the current version of the Matrix protocol, getting an access\_token programmatically works slightly different:
To find out the endpoint, e.g., for matrix.org, you need to check a `.well-known` file for the API URL ([Documentation](https://spec.matrix.org/v1.1/client-server-api/#well-known-uri)): `https://matrix.org/.well-known/matrix/client`:
```
$ curl https://matrix.org/.well-known/matrix/client
{
"m.homeserver": {
"base_url": "https://matrix-client.matrix.org"
},
"m.identity_server": {
"base_url": "https://vector.im"
}
}
```
Afterwards, the homeserver base url can be used for the curl call ([See Documentation for the /login endpoint](https://spec.matrix.org/v1.1/client-server-api/#post_matrixclientv3login)):
```
$ curl '{"type":"m.login.password", "user":"'$username'", "password":"'$password'"} \
"https://$base_url/_matrix/client/v3/login"
{
"user_id":"@username:matrix.org",
"access_token":"token",
"home_server":"matrix.org",
"device_id":"ID",
"well_known": {
"m.homeserver": {
"base_url":"https://matrix-client.matrix.org/"
}
}
}
``` |
131,056 | In the [Matrix](https://matrix.org/) instant messaging protocol, when using the reference implementation of the Matrix server (called `synapse`), there is an [admin API](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/) with functions like [resetting a password](https://github.com/matrix-org/synapse/blob/master/docs/admin_api/user_admin_api.rst#reset-password) for a user etc..
Accessing this requires an [`access_token`](https://matrix.org/docs/spec/client_server/latest#using-access-tokens) "API key" of a server admin user.
How do I get one? | 2019/06/20 | [
"https://webapps.stackexchange.com/questions/131056",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/75677/"
] | Solution to find your access token:
1. Log in to the account you want to get the access token for. Click on the name in the top left corner, then "Settings".
2. Click the "Help & About" tab (left side of the dialog).
3. Scroll to the bottom and click on `<click to reveal>` part of Access
Token.
4. Copy your access token to a safe place. | With the current version of the Matrix protocol, getting an access\_token programmatically works slightly different:
To find out the endpoint, e.g., for matrix.org, you need to check a `.well-known` file for the API URL ([Documentation](https://spec.matrix.org/v1.1/client-server-api/#well-known-uri)): `https://matrix.org/.well-known/matrix/client`:
```
$ curl https://matrix.org/.well-known/matrix/client
{
"m.homeserver": {
"base_url": "https://matrix-client.matrix.org"
},
"m.identity_server": {
"base_url": "https://vector.im"
}
}
```
Afterwards, the homeserver base url can be used for the curl call ([See Documentation for the /login endpoint](https://spec.matrix.org/v1.1/client-server-api/#post_matrixclientv3login)):
```
$ curl '{"type":"m.login.password", "user":"'$username'", "password":"'$password'"} \
"https://$base_url/_matrix/client/v3/login"
{
"user_id":"@username:matrix.org",
"access_token":"token",
"home_server":"matrix.org",
"device_id":"ID",
"well_known": {
"m.homeserver": {
"base_url":"https://matrix-client.matrix.org/"
}
}
}
``` |
67,651,333 | I have built a python class, which takes a string as input
I have put 3 functions in the python class.
First function is to count no of upper and lower case
Second function is to truncate the string
Third function is to check if the string is a palindrome
```
class stringUtility():
def _init_(self,string):
self.string = string
def upperlower(self):
upper = 0
lower = 0
for i in range(len(self.string)):
# For lower letters
if (ord(self.string[i]) >= 97 and ord(self.string[i]) <= 122):
lower += 1
# For upper letters
elif (ord(self.string[i]) >= 65 and ord(self.string[i]) <= 90):
upper += 1
print('Lower case characters = %s' %lower,
'Upper case characters = %s' %upper)
# # Driver Code
# string = 'jjfkhgbhf'
# #upperlower(string)
def trimString(self):
trimmedString = self.string[:10] + "..."
if len(self.string) <= 10:
print(self.string)
else:
print(trimmedString)
# string2 = "fdsfsdfsdfsdf"
# #trimString(string2)
def checkPalindrome(self):
reverseString = self.string[::-1]
convert_to_palindrome = self.string + reverseString[1:]
if reverseString == self.string:
print('input is a palindrome')
else:
print(convert_to_palindrome )
# string3 = 'dad'
# checkPalindrome(string3)
person2 = stringUtility.upperlower('mayanDFSDDk')
```
But i am getting the error:
```
File "class.py", line 58, in <module>
person2 = stringUtility.upperlower('mayanDFSDDk')
File "class.py", line 11, in upperlower
for i in range(len(self.string)):
AttributeError: 'str' object has no attribute 'string'
``` | 2021/05/22 | [
"https://Stackoverflow.com/questions/67651333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There's a lot amiss with Windows Terminal [#10153](https://github.com/microsoft/terminal/issues/10153), since the developers were as they say [*"shooting from the hip"*](https://www.collinsdictionary.com/us/dictionary/english/to-shoot-from-the-hip). There's no study of the available documentation, testing, etc.
The bug report is not talking about [xterm](https://invisible-island.net/xterm/xterm.html), since its DECRQM does actually return a value for [bracketed-paste](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h4-Functions-using-CSI-_-ordered-by-the-final-character-lparen-s-rparen:CSI-?-Pm-h:Ps-=-2-0-0-4.1F7D). Here's a screenshot in [vttest](https://invisible-island.net/vttest/vttest.html) illustrating that:
[](https://i.stack.imgur.com/lPl1Q.png)
`XTSAVE` and `XTRESTORE` are old features dating back to December 1986, preceding the VT420 PCTerm (announced in February 1992) by a little over 5 years. Since DEC participated in developing xterm during the 1980s (see [copyright notice](https://github.com/ThomasDickey/xterm-snapshots/blob/b2ecdc26094793725db0353b0699e4d31446351e/charproc.c#L57)), one might have assumed that its terminals division would have accommodated this. But that's so long ago, that it's unlikely that someone can point out why that didn't happen.
Like the cursor save/restore, the private-mode save/restore feature does not use a stack.
Back to the question: the point of #10153 is that the Windows Terminal developers choose to not make it xterm-compatible by providing the control responses that would enable an application to determine what state it is in. Perhaps at some point Windows Terminal will provide a solution. However, `DECRQM` is a VT320 (and up) feature, while [Windows Terminal](https://invisible-island.net/ncurses/terminfo.src.html#tic-ms-terminal) identifies itself as a VT100 (but masquerades as xterm).
Further reading:
* [XTerm Control Sequences (Miscellaneous)](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Miscellaneous)
* [Unit test framework for terminal emulation #1746](https://github.com/microsoft/terminal/issues/1746)
* [Add support for the DECSCNM Screen Mode #3773](https://github.com/microsoft/terminal/issues/3773) (eventually resolved)
* [RE: ms-terminal in terminfo.src](https://lists.gnu.org/archive/html/bug-ncurses/2019-08/msg00004.html) (not resolved, see [#8303](https://github.com/microsoft/terminal/issues/https://github.com/microsoft/terminal/issues/8303)) | Summarizing the discussion I had on the [Windows Terminal bug tracker about the missing support for DECRQM or XTSAVE+XTRESTORE](https://github.com/microsoft/terminal/issues/10153) :
>
> It is the implicit assumption that terminal-based application would
> set any desired modes upon start and **reset to the default** at the
> end of the application. Even though this is inefficient it is the way
> around missing support for DECRQM and other ways to query VT-100
> modes.
>
>
> |
59,067,075 | array = ["Β£179.95", "Β£199.95", "Β£89.95"]
How to multiple this values add get the total values in ios swift 4.
Please help me. | 2019/11/27 | [
"https://Stackoverflow.com/questions/59067075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11923334/"
] | Try this. This will Works.
```
$a = 1;
$x = 1;
$array = [];
$array[] = array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
);
if( $a == $x ){
$array[] = array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
);
}
$array[] = array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
);
```
**OUTPUT:**
```
Array
(
[0] => Array
(
[name] => name
[type] => type
[label] => label
)
[1] => Array
(
[name] => name
[type] => type
[label] => label
)
[2] => Array
(
[name] => name
[type] => type
[label] => label
)
)
``` | Hope help:
```
$a = 1;
$x = 1;
$array = array(
array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
),
array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
),
);
if ( $a === $x ) {
$array[] = array(
'name' => 'name',
'type' => 'type',
'label' => 'label',
);
}
print_r($array);
``` |
6,040,640 | I have an sql query in which I need to select the records from table where the time is between 3:00 PM yesterday to 3:00 PM today *if* today's time is more than 3:00 PM.
If today's time is less than that, like if today's time is 1:00 PM. then then my query should take today's time as 1:00 PM (which should return me records).
**I need to get the time between 3:00pm yesterday to 3:00pm today if todays time is more than 3:00pm
if todays time is less than 3:00pm then get the 3:00pm yesterday to current time today** | 2011/05/18 | [
"https://Stackoverflow.com/questions/6040640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96180/"
] | The best way of handling this is to use an [IF statement](http://www.techonthenet.com/oracle/loops/if_then.php):
```
IF TO_CHAR(SYSDATE, 'HH24') >= 15 THEN
SELECT x.*
FROM YOUR_TABLE x
WHERE x.date_column BETWEEN TO_DATE(TO_CHAR(SYSDATE -1, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
AND TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
ELSE
SELECT x.*
FROM YOUR_TABLE x
WHERE x.date_column BETWEEN TO_DATE(TO_CHAR(SYSDATE -1, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
AND SYSDATE
END IF;
```
Conditional WHERE clauses are non-sargable.
Previously:
-----------
If I understand correctly, you want to get records within the last day. If the current time is 3 PM or later, the time should be set to 3 PM. If earlier than 3 PM, take the current time...
```
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT CASE
WHEN TO_CHAR(SYSDATE, 'HH24') >= 15 THEN
TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM-DD')|| ' 15:00:00', 'YYYY-MM-DD HH24:MI:SS')
ELSE SYSDATE
END AS dt
FROM DUAL) y ON x.date_column BETWEEN dt - 1 AND dt
```
### Note:
`dt - 1` means that 24 hours will be subtracted from the Oracle DATE.
### Reference:
* [TO\_CHAR](http://www.techonthenet.com/oracle/functions/to_char.php)
* [TO\_DATE](http://www.techonthenet.com/oracle/functions/to_date.php) | There is no need for an IF statement. This can be solved easily with simple SQL.
My table T23 has some records with dates; here is a sample with times at 3.00pm:
```
SQL> select id, some_date from t23
2 where to_char(some_date,'HH24') = '15'
3 /
ID SOME_DATE
---------- ---------
14 16-MAY-11
38 17-MAY-11
62 18-MAY-11
81 19-MAY-11
SQL>
```
As the current time is before 3.00pm my query will return records from 17-MAY and 18-MAY but not the record where ID=62...
```
SQL> select to_char(sysdate, 'DD-MON-YYYY HH24:MI') as time_now
2 from dual
3 /
TIME_NOW
-----------------
18-MAY-2011 10:45
SQL> select id, to_char(some_date, 'DD-MON-YYYY HH24:MI') as dt
2 from t23
3 where some_date between trunc(sysdate-1)+(15/24)
4 and least( trunc(sysdate)+(15/24), sysdate)
5 /
ID DT
---------- -----------------
38 17-MAY-2011 15:00
39 17-MAY-2011 16:00
40 17-MAY-2011 17:00
41 17-MAY-2011 18:00
42 17-MAY-2011 19:00
43 17-MAY-2011 20:00
44 17-MAY-2011 21:00
45 17-MAY-2011 22:00
46 17-MAY-2011 23:00
47 18-MAY-2011 00:00
48 18-MAY-2011 01:00
49 18-MAY-2011 02:00
50 18-MAY-2011 03:00
51 18-MAY-2011 04:00
52 18-MAY-2011 05:00
53 18-MAY-2011 06:00
54 18-MAY-2011 07:00
55 18-MAY-2011 08:00
56 18-MAY-2011 09:00
57 18-MAY-2011 10:00
20 rows selected.
SQL>
``` |
18,877,580 | Consider the following snippet:
```
"12-18" -Contains "-"
```
Youβd think this evaluates to `true`, but it doesn't. This will evaluate to `false` instead. Iβm not sure why this happens, but it does.
To avoid this, you can use this instead:
```
"12-18".Contains("-")
```
Now the expression will evaluate to true.
Why does the first code snippet behave like that? Is there something special about `-` that doesn't play nicely with `-Contains`? [The documentation](http://technet.microsoft.com/en-us/library/hh847759.aspx) doesn't mention anything about it. | 2013/09/18 | [
"https://Stackoverflow.com/questions/18877580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770270/"
] | The `-Contains` operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
>
> -Contains
> Description: Containment operator. **Tells whether a collection of reference values includes a single test value.**
>
>
>
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
```
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
```
I think what you want is the [`-Match`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match) operator:
```
"12-18" -Match "-"
```
Which returns `True`.
**Important:** As pointed out in the comments and in the [linked documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match), it should be noted that the `-Match` operator uses [regular expressions](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-6) to perform text matching. | `-Contains` is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.
[`-match` and `-imatch`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6) are regular expression string matchers, and set automatic variables to use with captures.
`-like`, `-ilike` are SQL-like matchers. |
18,877,580 | Consider the following snippet:
```
"12-18" -Contains "-"
```
Youβd think this evaluates to `true`, but it doesn't. This will evaluate to `false` instead. Iβm not sure why this happens, but it does.
To avoid this, you can use this instead:
```
"12-18".Contains("-")
```
Now the expression will evaluate to true.
Why does the first code snippet behave like that? Is there something special about `-` that doesn't play nicely with `-Contains`? [The documentation](http://technet.microsoft.com/en-us/library/hh847759.aspx) doesn't mention anything about it. | 2013/09/18 | [
"https://Stackoverflow.com/questions/18877580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770270/"
] | The `-Contains` operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
>
> -Contains
> Description: Containment operator. **Tells whether a collection of reference values includes a single test value.**
>
>
>
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
```
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
```
I think what you want is the [`-Match`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match) operator:
```
"12-18" -Match "-"
```
Which returns `True`.
**Important:** As pointed out in the comments and in the [linked documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match), it should be noted that the `-Match` operator uses [regular expressions](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-6) to perform text matching. | You can use `like`:
```
"12-18" -like "*-*"
```
Or `split` for `contains`:
```
"12-18" -split "" -contains "-"
``` |
18,877,580 | Consider the following snippet:
```
"12-18" -Contains "-"
```
Youβd think this evaluates to `true`, but it doesn't. This will evaluate to `false` instead. Iβm not sure why this happens, but it does.
To avoid this, you can use this instead:
```
"12-18".Contains("-")
```
Now the expression will evaluate to true.
Why does the first code snippet behave like that? Is there something special about `-` that doesn't play nicely with `-Contains`? [The documentation](http://technet.microsoft.com/en-us/library/hh847759.aspx) doesn't mention anything about it. | 2013/09/18 | [
"https://Stackoverflow.com/questions/18877580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770270/"
] | The `-Contains` operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
>
> -Contains
> Description: Containment operator. **Tells whether a collection of reference values includes a single test value.**
>
>
>
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
```
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
```
I think what you want is the [`-Match`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match) operator:
```
"12-18" -Match "-"
```
Which returns `True`.
**Important:** As pointed out in the comments and in the [linked documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match), it should be noted that the `-Match` operator uses [regular expressions](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-6) to perform text matching. | * `like` is best, or at least easiest.
* `match` is used for regex comparisons.
Reference: *[About Comparison Operators](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators)* |
18,877,580 | Consider the following snippet:
```
"12-18" -Contains "-"
```
Youβd think this evaluates to `true`, but it doesn't. This will evaluate to `false` instead. Iβm not sure why this happens, but it does.
To avoid this, you can use this instead:
```
"12-18".Contains("-")
```
Now the expression will evaluate to true.
Why does the first code snippet behave like that? Is there something special about `-` that doesn't play nicely with `-Contains`? [The documentation](http://technet.microsoft.com/en-us/library/hh847759.aspx) doesn't mention anything about it. | 2013/09/18 | [
"https://Stackoverflow.com/questions/18877580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770270/"
] | `-Contains` is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.
[`-match` and `-imatch`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6) are regular expression string matchers, and set automatic variables to use with captures.
`-like`, `-ilike` are SQL-like matchers. | You can use `like`:
```
"12-18" -like "*-*"
```
Or `split` for `contains`:
```
"12-18" -split "" -contains "-"
``` |
18,877,580 | Consider the following snippet:
```
"12-18" -Contains "-"
```
Youβd think this evaluates to `true`, but it doesn't. This will evaluate to `false` instead. Iβm not sure why this happens, but it does.
To avoid this, you can use this instead:
```
"12-18".Contains("-")
```
Now the expression will evaluate to true.
Why does the first code snippet behave like that? Is there something special about `-` that doesn't play nicely with `-Contains`? [The documentation](http://technet.microsoft.com/en-us/library/hh847759.aspx) doesn't mention anything about it. | 2013/09/18 | [
"https://Stackoverflow.com/questions/18877580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770270/"
] | `-Contains` is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.
[`-match` and `-imatch`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6) are regular expression string matchers, and set automatic variables to use with captures.
`-like`, `-ilike` are SQL-like matchers. | * `like` is best, or at least easiest.
* `match` is used for regex comparisons.
Reference: *[About Comparison Operators](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators)* |
18,877,580 | Consider the following snippet:
```
"12-18" -Contains "-"
```
Youβd think this evaluates to `true`, but it doesn't. This will evaluate to `false` instead. Iβm not sure why this happens, but it does.
To avoid this, you can use this instead:
```
"12-18".Contains("-")
```
Now the expression will evaluate to true.
Why does the first code snippet behave like that? Is there something special about `-` that doesn't play nicely with `-Contains`? [The documentation](http://technet.microsoft.com/en-us/library/hh847759.aspx) doesn't mention anything about it. | 2013/09/18 | [
"https://Stackoverflow.com/questions/18877580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770270/"
] | You can use `like`:
```
"12-18" -like "*-*"
```
Or `split` for `contains`:
```
"12-18" -split "" -contains "-"
``` | * `like` is best, or at least easiest.
* `match` is used for regex comparisons.
Reference: *[About Comparison Operators](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators)* |
2,880,449 | after some simplification, we get (2004y)/(y-2004)=x
and by looking at the prime factorization of 2004 we observe there are only 12 ways in which 2004 can be expressed as the product of two integers.
which gives us 12 ordered pairs.But the answer is 45. how?(sorry for not using mathjax my browser does not support it) | 2018/08/12 | [
"https://math.stackexchange.com/questions/2880449",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/570638/"
] | Guide:
Once we get $$2004y+2004x=xy$$
$$-2004y-2004x+xy=0$$
$$2004^2-2004y-2004x+xy=2004^2$$
$$(2004-x)(2004-y)=2004^2=2^4\cdot 3^2\cdot 167^2$$
Can you complete the task? | 1/x +1/y=2004
y+x/xy = 1/2004
2004(x+y)=xy
0=xy-2004x-2004y
0=(x-2004)(y-2004)-(2004)^2
(2004)^2=(x-2004)(y-2004)
It should be pretty easy from here. Just find the factors of 2004 squared. |
2,880,449 | after some simplification, we get (2004y)/(y-2004)=x
and by looking at the prime factorization of 2004 we observe there are only 12 ways in which 2004 can be expressed as the product of two integers.
which gives us 12 ordered pairs.But the answer is 45. how?(sorry for not using mathjax my browser does not support it) | 2018/08/12 | [
"https://math.stackexchange.com/questions/2880449",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/570638/"
] | $$\frac{1}{x}+\frac{1}{y}= \frac{1}{2004}$$
Rearrange:
$(x-2004)(y-2004)=2004^2 = 2^4\cdot3^2\cdot167^2$.
There are exactly $5\cdot 3\cdot 3= 45$ positive integer divisors of this number, so it has $90$ integer divisors. This yields 90 solutions.
For example, one case is that $x-2004= -2^3\cdot3$, and then $y-2004=-2\cdot3\cdot167^2$. Note that however you write $2^4\cdot3^2\cdot167^2$ as a product of two integers, it yields exactly one solution. So the answer is $90$. | 1/x +1/y=2004
y+x/xy = 1/2004
2004(x+y)=xy
0=xy-2004x-2004y
0=(x-2004)(y-2004)-(2004)^2
(2004)^2=(x-2004)(y-2004)
It should be pretty easy from here. Just find the factors of 2004 squared. |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | Manoj's answer will work, there is another way using the updater function *(funtinal `setState`)* for `setState` (which you can read about [here](https://reactjs.org/docs/react-component.html#setstate "setState"))
```js
onBack() {
this.setState(prevState => {
let newArray = prevState.array
newArray[2] = "something"
return { array: newArray }
});
}
``` | using hooks
===========
```
const [totalSet, setTotalSet] = useState(null);
```
console.log(totalSet); // {sets: Array(3), subscribed: false}
```
setTotalSet(datas => ({
...datas,
sets: updatedSet,
}));
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | Manoj's answer will work, there is another way using the updater function *(funtinal `setState`)* for `setState` (which you can read about [here](https://reactjs.org/docs/react-component.html#setstate "setState"))
```js
onBack() {
this.setState(prevState => {
let newArray = prevState.array
newArray[2] = "something"
return { array: newArray }
});
}
``` | ***Create a temporary array update that, then assign the whole array back to the state***
```
var arr = [];
arr = this.state.array;
arr[2] = "something";
this.setState({
array : arr
});
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | Manoj's answer will work, there is another way using the updater function *(funtinal `setState`)* for `setState` (which you can read about [here](https://reactjs.org/docs/react-component.html#setstate "setState"))
```js
onBack() {
this.setState(prevState => {
let newArray = prevState.array
newArray[2] = "something"
return { array: newArray }
});
}
``` | Use [Object.assign({});](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
```
let array= Object.assign({}, this.state.array); //creating copy of object
array[2]="something"
this.setState({array});
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | You can't update the state like this.
>
> Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
>
>
>
Read [React docs](https://reactjs.org/docs/react-component.html#state).
You can do something like this :
```
let newArray = [...this.state.array];
newArray[2] = 'somethingElse';
this.setState({array: newArray});
```
The above example is using [Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
There are multiple ways to modify state, but all the ways should ensure that data is treated as immutable. You can read more about handling state in React [here](https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5) | Use [Object.assign({});](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
```
let array= Object.assign({}, this.state.array); //creating copy of object
array[2]="something"
this.setState({array});
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | You can't update the state like this.
>
> Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
>
>
>
Read [React docs](https://reactjs.org/docs/react-component.html#state).
You can do something like this :
```
let newArray = [...this.state.array];
newArray[2] = 'somethingElse';
this.setState({array: newArray});
```
The above example is using [Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
There are multiple ways to modify state, but all the ways should ensure that data is treated as immutable. You can read more about handling state in React [here](https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5) | Manoj's answer will work, there is another way using the updater function *(funtinal `setState`)* for `setState` (which you can read about [here](https://reactjs.org/docs/react-component.html#setstate "setState"))
```js
onBack() {
this.setState(prevState => {
let newArray = prevState.array
newArray[2] = "something"
return { array: newArray }
});
}
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | You can't update the state like this.
>
> Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
>
>
>
Read [React docs](https://reactjs.org/docs/react-component.html#state).
You can do something like this :
```
let newArray = [...this.state.array];
newArray[2] = 'somethingElse';
this.setState({array: newArray});
```
The above example is using [Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
There are multiple ways to modify state, but all the ways should ensure that data is treated as immutable. You can read more about handling state in React [here](https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5) | using hooks
===========
```
const [totalSet, setTotalSet] = useState(null);
```
console.log(totalSet); // {sets: Array(3), subscribed: false}
```
setTotalSet(datas => ({
...datas,
sets: updatedSet,
}));
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | If you are bother to set the new updated array on your `currentArray` using spread function, you may use `Array.from(duplicateArray)`
```
let duplicateArray = [...currentArray] //duplicate the array into new array
duplicateArray[index].value = 'x'; // update the field you want to update
setCurrentArray(Array.from(duplicateArray )) //set the new updated array into currentArray
```
I bother with this issue and I just search about and I saw this idea, and it works!
<https://github.com/facebook/react-native/issues/21734#issuecomment-433885436> | ***Create a temporary array update that, then assign the whole array back to the state***
```
var arr = [];
arr = this.state.array;
arr[2] = "something";
this.setState({
array : arr
});
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | using hooks
===========
```
const [totalSet, setTotalSet] = useState(null);
```
console.log(totalSet); // {sets: Array(3), subscribed: false}
```
setTotalSet(datas => ({
...datas,
sets: updatedSet,
}));
``` | ***Create a temporary array update that, then assign the whole array back to the state***
```
var arr = [];
arr = this.state.array;
arr[2] = "something";
this.setState({
array : arr
});
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | You can't update the state like this.
>
> Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
>
>
>
Read [React docs](https://reactjs.org/docs/react-component.html#state).
You can do something like this :
```
let newArray = [...this.state.array];
newArray[2] = 'somethingElse';
this.setState({array: newArray});
```
The above example is using [Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
There are multiple ways to modify state, but all the ways should ensure that data is treated as immutable. You can read more about handling state in React [here](https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5) | ***Create a temporary array update that, then assign the whole array back to the state***
```
var arr = [];
arr = this.state.array;
arr[2] = "something";
this.setState({
array : arr
});
``` |
50,603,368 | Trying to update one element of an array in this.state I'm getting an (expected ,) error but cant see where I've gone wrong. Do I need to create a temporary array update that, then assign the whole array back to the state
This is essentially what I have
```
this.state = { array: ['a', 'b', 'c'] };
onBack() {
this.setState({
array[2]: 'something'
});
}
``` | 2018/05/30 | [
"https://Stackoverflow.com/questions/50603368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608821/"
] | Manoj's answer will work, there is another way using the updater function *(funtinal `setState`)* for `setState` (which you can read about [here](https://reactjs.org/docs/react-component.html#setstate "setState"))
```js
onBack() {
this.setState(prevState => {
let newArray = prevState.array
newArray[2] = "something"
return { array: newArray }
});
}
``` | If you are bother to set the new updated array on your `currentArray` using spread function, you may use `Array.from(duplicateArray)`
```
let duplicateArray = [...currentArray] //duplicate the array into new array
duplicateArray[index].value = 'x'; // update the field you want to update
setCurrentArray(Array.from(duplicateArray )) //set the new updated array into currentArray
```
I bother with this issue and I just search about and I saw this idea, and it works!
<https://github.com/facebook/react-native/issues/21734#issuecomment-433885436> |
18,410,997 | I have two to three variables that I want to mix into strings and then place them all into a table, however I can't figure out how to make the variables mix.
What I have is
```
document.write('<table cellspacing="0" cellpadding="5">')
var a = ["String1", "String2"]
var n = ["string3", "String4"]
for(var i=0; i <a.length; i++){
document.write('<tr'>
document.write('td' + (a[i]) + (b[i]) +'</td>')
document.write('</td>')
}
document.write('</table>')
```
This does create the table I want however it doesn't perform the function I am looking for.
It creates a table that goes:
"string1" "string3"
"string2" "string4'
I'm looking for:
"string1" "string3"
"string1" "string4"
"string2" "string3"
"string2" "string4"
Hopefully that makes sense. I've tried searching through the internet and on Stack Overflow to no avail. How would I make this happen? Eventually the arrays should be able to grow to maybe a hundred each... | 2013/08/23 | [
"https://Stackoverflow.com/questions/18410997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014858/"
] | You need an additional loop -
```
for(var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
document.write('<tr'>);
document.write('<td>' + a[i] + b[j] + '</td>');
document.write('</td>');
}
}
```
P.S.: Do you really need to create elements using `document.write`? It's OK if it's an example, but this style of element creation is strongly discouraged in real development code. | ```
document.write('<table cellspacing="0" cellpadding="5">');
var a = ["String1", "String2"];
var b = ["string3", "String4"];
for(var i=0; i <b.length; i++){
for (var j=0;j<a.length;j++){
document.write('<tr>');
document.write('<td>' + (a[i]) + (b[j]) +'</td>');
document.write('</td>');
}
}
document.write('</table>');
``` |
18,410,997 | I have two to three variables that I want to mix into strings and then place them all into a table, however I can't figure out how to make the variables mix.
What I have is
```
document.write('<table cellspacing="0" cellpadding="5">')
var a = ["String1", "String2"]
var n = ["string3", "String4"]
for(var i=0; i <a.length; i++){
document.write('<tr'>
document.write('td' + (a[i]) + (b[i]) +'</td>')
document.write('</td>')
}
document.write('</table>')
```
This does create the table I want however it doesn't perform the function I am looking for.
It creates a table that goes:
"string1" "string3"
"string2" "string4'
I'm looking for:
"string1" "string3"
"string1" "string4"
"string2" "string3"
"string2" "string4"
Hopefully that makes sense. I've tried searching through the internet and on Stack Overflow to no avail. How would I make this happen? Eventually the arrays should be able to grow to maybe a hundred each... | 2013/08/23 | [
"https://Stackoverflow.com/questions/18410997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014858/"
] | You need an additional loop -
```
for(var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
document.write('<tr'>);
document.write('<td>' + a[i] + b[j] + '</td>');
document.write('</td>');
}
}
```
P.S.: Do you really need to create elements using `document.write`? It's OK if it's an example, but this style of element creation is strongly discouraged in real development code. | ```
document.write('<table cellspacing="0" cellpadding="5">');
var a = ["String1", "String2"];
var n = ["String3", "String4"];
for (var i = 0; i < a.length; i++)
{
for (var j = 0; j < n.length; j++)
{
document.write("<tr>");
document.write("<td>" + a[i] + "</td><td>" + n[j] + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
```
Basically, you need to read the entire **n** array for every element from the **a** array. |
18,410,997 | I have two to three variables that I want to mix into strings and then place them all into a table, however I can't figure out how to make the variables mix.
What I have is
```
document.write('<table cellspacing="0" cellpadding="5">')
var a = ["String1", "String2"]
var n = ["string3", "String4"]
for(var i=0; i <a.length; i++){
document.write('<tr'>
document.write('td' + (a[i]) + (b[i]) +'</td>')
document.write('</td>')
}
document.write('</table>')
```
This does create the table I want however it doesn't perform the function I am looking for.
It creates a table that goes:
"string1" "string3"
"string2" "string4'
I'm looking for:
"string1" "string3"
"string1" "string4"
"string2" "string3"
"string2" "string4"
Hopefully that makes sense. I've tried searching through the internet and on Stack Overflow to no avail. How would I make this happen? Eventually the arrays should be able to grow to maybe a hundred each... | 2013/08/23 | [
"https://Stackoverflow.com/questions/18410997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014858/"
] | You need an additional loop -
```
for(var i = 0; i < a.length; i++) {
for (var j = 0; j < b.length; j++) {
document.write('<tr'>);
document.write('<td>' + a[i] + b[j] + '</td>');
document.write('</td>');
}
}
```
P.S.: Do you really need to create elements using `document.write`? It's OK if it's an example, but this style of element creation is strongly discouraged in real development code. | Here's a working solution after fixing a lot of syntax errors:
```
document.write('<table cellspacing="0" cellpadding="5">')
var a = ["String1", "String2"]
var n = ["string3", "String4"]
for(var i=0; i<a.length; i++){
for (x=0;x<n.length;x++) {
document.write('<tr>')
document.write('<td>' + (a[i]) + (n[x]) +'</td>')
document.write('</tr>')
}
}
document.write('</table>')
``` |
22,651,117 | I am using captcha and I want to create a captcha using the cpatcha helper!I read the user guide and write a piece of code,but it fails to create an captcha,also here is no error displayed on the page,so I just can't find where I am wrong,my code is as follows:
```
public function captcha(){
$this->load->helper('captcha');
$vals=array(
'word'=>'0123456789',
'img_path'=>base_url('asserts/cpatcha').'/',
'img_url'=>base_url('asserts/cpatcha').'/',
'img_width'=>150,
'img_height'=>30,
'expiration'=>7200
);
var_dump($vals);
$cap=create_captcha($vals);
var_dump($cap['image']);
}
```
as I print the two variables,the result displayed on the page is as follows:
```
array (size=6)
'word' => string '0123456789' (length=10)
'img_path' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_url' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_width' => int 150
'img_height' => int 30
'expiration' => int 7200
null
``` | 2014/03/26 | [
"https://Stackoverflow.com/questions/22651117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392958/"
] | It looks like derby locking issue. you can temporarily fix this issue by deleting the lock file inside the directory `/var/lib/hive/metastore/metastore_db`. But this issue will also occur in future also
`sudo rm -rf /var/lib/hive/metastore/metastore_db/*.lck`
With default hive metastore embedded derby, it is not possible to start multiple instance of hive at the same time. By changing hive metastore to mysql or postgres server this issue can be solved.
See the following cloudera documentation for changing hive metastore
<http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH4/4.2.0/CDH4-Installation-Guide/cdh4ig_topic_18_4.html> | update `hive-site.xml` under `~/hive/conf` folder as below name/value and try this:
```
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/var/lib/hive/metastore/metastore_db;create=true</value>
``` |
22,651,117 | I am using captcha and I want to create a captcha using the cpatcha helper!I read the user guide and write a piece of code,but it fails to create an captcha,also here is no error displayed on the page,so I just can't find where I am wrong,my code is as follows:
```
public function captcha(){
$this->load->helper('captcha');
$vals=array(
'word'=>'0123456789',
'img_path'=>base_url('asserts/cpatcha').'/',
'img_url'=>base_url('asserts/cpatcha').'/',
'img_width'=>150,
'img_height'=>30,
'expiration'=>7200
);
var_dump($vals);
$cap=create_captcha($vals);
var_dump($cap['image']);
}
```
as I print the two variables,the result displayed on the page is as follows:
```
array (size=6)
'word' => string '0123456789' (length=10)
'img_path' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_url' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_width' => int 150
'img_height' => int 30
'expiration' => int 7200
null
``` | 2014/03/26 | [
"https://Stackoverflow.com/questions/22651117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392958/"
] | It looks like derby locking issue. you can temporarily fix this issue by deleting the lock file inside the directory `/var/lib/hive/metastore/metastore_db`. But this issue will also occur in future also
`sudo rm -rf /var/lib/hive/metastore/metastore_db/*.lck`
With default hive metastore embedded derby, it is not possible to start multiple instance of hive at the same time. By changing hive metastore to mysql or postgres server this issue can be solved.
See the following cloudera documentation for changing hive metastore
<http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH4/4.2.0/CDH4-Installation-Guide/cdh4ig_topic_18_4.html> | I've encountered similar error when I forgot about another instance of `spark-shell` running on same node. |
22,651,117 | I am using captcha and I want to create a captcha using the cpatcha helper!I read the user guide and write a piece of code,but it fails to create an captcha,also here is no error displayed on the page,so I just can't find where I am wrong,my code is as follows:
```
public function captcha(){
$this->load->helper('captcha');
$vals=array(
'word'=>'0123456789',
'img_path'=>base_url('asserts/cpatcha').'/',
'img_url'=>base_url('asserts/cpatcha').'/',
'img_width'=>150,
'img_height'=>30,
'expiration'=>7200
);
var_dump($vals);
$cap=create_captcha($vals);
var_dump($cap['image']);
}
```
as I print the two variables,the result displayed on the page is as follows:
```
array (size=6)
'word' => string '0123456789' (length=10)
'img_path' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_url' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_width' => int 150
'img_height' => int 30
'expiration' => int 7200
null
``` | 2014/03/26 | [
"https://Stackoverflow.com/questions/22651117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392958/"
] | It looks like derby locking issue. you can temporarily fix this issue by deleting the lock file inside the directory `/var/lib/hive/metastore/metastore_db`. But this issue will also occur in future also
`sudo rm -rf /var/lib/hive/metastore/metastore_db/*.lck`
With default hive metastore embedded derby, it is not possible to start multiple instance of hive at the same time. By changing hive metastore to mysql or postgres server this issue can be solved.
See the following cloudera documentation for changing hive metastore
<http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH4/4.2.0/CDH4-Installation-Guide/cdh4ig_topic_18_4.html> | In my case I needed to create a directory and grant proper permissions:
```
$ sudo mkdir /var/lib/hive/metastore/
$ sudo chown hdfs:hdfs /var/lib/hive/metastore/
``` |
22,651,117 | I am using captcha and I want to create a captcha using the cpatcha helper!I read the user guide and write a piece of code,but it fails to create an captcha,also here is no error displayed on the page,so I just can't find where I am wrong,my code is as follows:
```
public function captcha(){
$this->load->helper('captcha');
$vals=array(
'word'=>'0123456789',
'img_path'=>base_url('asserts/cpatcha').'/',
'img_url'=>base_url('asserts/cpatcha').'/',
'img_width'=>150,
'img_height'=>30,
'expiration'=>7200
);
var_dump($vals);
$cap=create_captcha($vals);
var_dump($cap['image']);
}
```
as I print the two variables,the result displayed on the page is as follows:
```
array (size=6)
'word' => string '0123456789' (length=10)
'img_path' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_url' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_width' => int 150
'img_height' => int 30
'expiration' => int 7200
null
``` | 2014/03/26 | [
"https://Stackoverflow.com/questions/22651117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392958/"
] | I've encountered similar error when I forgot about another instance of `spark-shell` running on same node. | update `hive-site.xml` under `~/hive/conf` folder as below name/value and try this:
```
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/var/lib/hive/metastore/metastore_db;create=true</value>
``` |
22,651,117 | I am using captcha and I want to create a captcha using the cpatcha helper!I read the user guide and write a piece of code,but it fails to create an captcha,also here is no error displayed on the page,so I just can't find where I am wrong,my code is as follows:
```
public function captcha(){
$this->load->helper('captcha');
$vals=array(
'word'=>'0123456789',
'img_path'=>base_url('asserts/cpatcha').'/',
'img_url'=>base_url('asserts/cpatcha').'/',
'img_width'=>150,
'img_height'=>30,
'expiration'=>7200
);
var_dump($vals);
$cap=create_captcha($vals);
var_dump($cap['image']);
}
```
as I print the two variables,the result displayed on the page is as follows:
```
array (size=6)
'word' => string '0123456789' (length=10)
'img_path' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_url' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_width' => int 150
'img_height' => int 30
'expiration' => int 7200
null
``` | 2014/03/26 | [
"https://Stackoverflow.com/questions/22651117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392958/"
] | update `hive-site.xml` under `~/hive/conf` folder as below name/value and try this:
```
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/var/lib/hive/metastore/metastore_db;create=true</value>
``` | In my case I needed to create a directory and grant proper permissions:
```
$ sudo mkdir /var/lib/hive/metastore/
$ sudo chown hdfs:hdfs /var/lib/hive/metastore/
``` |
22,651,117 | I am using captcha and I want to create a captcha using the cpatcha helper!I read the user guide and write a piece of code,but it fails to create an captcha,also here is no error displayed on the page,so I just can't find where I am wrong,my code is as follows:
```
public function captcha(){
$this->load->helper('captcha');
$vals=array(
'word'=>'0123456789',
'img_path'=>base_url('asserts/cpatcha').'/',
'img_url'=>base_url('asserts/cpatcha').'/',
'img_width'=>150,
'img_height'=>30,
'expiration'=>7200
);
var_dump($vals);
$cap=create_captcha($vals);
var_dump($cap['image']);
}
```
as I print the two variables,the result displayed on the page is as follows:
```
array (size=6)
'word' => string '0123456789' (length=10)
'img_path' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_url' => string 'http://wrecruit.tudouya.com/asserts/cpatcha/' (length=44)
'img_width' => int 150
'img_height' => int 30
'expiration' => int 7200
null
``` | 2014/03/26 | [
"https://Stackoverflow.com/questions/22651117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392958/"
] | I've encountered similar error when I forgot about another instance of `spark-shell` running on same node. | In my case I needed to create a directory and grant proper permissions:
```
$ sudo mkdir /var/lib/hive/metastore/
$ sudo chown hdfs:hdfs /var/lib/hive/metastore/
``` |
146,490 | Is there a simple way to select only one radio button with the `<apex:selectRadio>` component? I searched for examples and found two posts on this topic that did not resolve the issue I'm having. I might be missing something simple. | 2016/10/30 | [
"https://salesforce.stackexchange.com/questions/146490",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/7528/"
] | The reason you are having this issue is because it is not one Radio button. It is a list of radio buttons. While in each one you can only select one options. For every one you can choose one.
I don't think there is a very quick fix for this one. Either, you give up using apex repeat in this case and put all the opportunity roles in the option list. In that case, you will be able to select only one primary opportunity role. Or otherwise, if you still want the table structure, you will need to use Javascript to enhance the logic. | There's no way to have it work the way you expect; each iteration in your apex:repeat creates a new radio group, which is why you can select all of the radios. They're simply not one logical group. To get a better idea of how apex:selectRadio is supposed to work, check out this trivial page:
```
<apex:page>
<apex:form>
<apex:selectRadio>
<apex:selectOption itemValue="yes" itemLabel="yes" />
<apex:selectOption itemValue="no" itemLabel="no" />
</apex:selectRadio>
</apex:form>
</apex:page>
```
Usually, this means people resort to using normal checkboxes, and use some JavaScript to make sure only one is selected. |
25,496,692 | I'm trying to open multiple windows with JavaFX, I have an eventlistener that opens a new window when a button is clicked it looks like this:
```
@FXML
private void joinAction() {
Parent root;
try {
Stage stage = (Stage) joinButton.getScene().getWindow();
stage.close();
root = FXMLLoader.load(getClass().getResource("main.fxml"));
stage = new Stage();
stage.setTitle("TuneUs");
stage.setScene(new Scene(root));
stage.show();
} catch (IOException e) {e.printStackTrace();}
}
```
the first window opens and the new one opens, but my problem is getting events to work with my second window
in `main.fxml` I have this line:
```
<TextField id="chat_bar" onAction="#sendChat" layoutX="14.0" layoutY="106.0" prefHeight="22.0" prefWidth="403.0"/>
```
Then in my controller class I have this method:
```
@FXML
private void sendChat() {
System.out.println("test");
}
```
but Intellij is telling me that; no controller specified for top level element
So, my question is: Do I need to create multiple controller classes or can I use just one for multiple windows if so how? | 2014/08/26 | [
"https://Stackoverflow.com/questions/25496692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2292723/"
] | The recommended approach is to define a controller for each FXML. Since controllers are very lightweight this shouldn't add much overhead. The controller for your main.fxml file might be as simple as
```
import javafx.fxml.FXML ;
public class MainController {
@FXML
private void sendChat() {
// ...
}
}
```
I have used this approach with fairly large numbers of FXML files and corresponding controllers in a single project, and have had no issues with managing the code etc. I recommend using a naming convention of the form `Main.fxml <-> MainController`.
If your controllers need to share data, use the techniques outlined in [Passing Parameters JavaFX FXML](https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml/14190310#14190310)
As @Vertex points out in the comments, there is an alternative approach provided by the `FXMLLoader.setController(...)` method. So in your example above, you could do
```
@FXML
private void joinAction() {
Parent root;
try {
Stage stage = (Stage) joinButton.getScene().getWindow();
stage.close();
FXMLLoader loader = new FXMLLoader (getClass().getResource("main.fxml"));
loader.setController(this);
root = loader.load();
stage = new Stage();
stage.setTitle("TuneUs");
stage.setScene(new Scene(root));
stage.show();
} catch (IOException e) {e.printStackTrace();}
}
@FXML
private void sendChat() {
// ...
}
```
This approach is fine if you are not setting any fields (controls) via FXML injection (i.e. with an `fx:id` attribute in the fxml and a corresponding `@FXML` annotation in the controller). If you are, it will be very difficult to keep track of when those fields have been set. Moreover, if your `joinAction` handler is invoked multiple times, you will have multiple instances of the node created by main.fxml, but all sharing a single controller instance (and consequently overwriting the same injected fields). Also note that with this approach, your `initialize()` method will be invoked *both* when the original fxml file is loaded, **and** when the main.fxml file is loaded, which will almost certainly cause undesired effects.
One last note: if you have many FXML files, and corresponding controllers, you might want to look at the [afterburner.fx framework](http://afterburner.adam-bien.com/). This is a very lightweight framework that mandates a naming convention on FXML files and their corresponding controllers, and also provides a (very) easy mechanism for sharing data between them. | You need to add top level element fx:controller. Look at this answer:<https://stackoverflow.com/a/41316536/4247308> |
25,496,692 | I'm trying to open multiple windows with JavaFX, I have an eventlistener that opens a new window when a button is clicked it looks like this:
```
@FXML
private void joinAction() {
Parent root;
try {
Stage stage = (Stage) joinButton.getScene().getWindow();
stage.close();
root = FXMLLoader.load(getClass().getResource("main.fxml"));
stage = new Stage();
stage.setTitle("TuneUs");
stage.setScene(new Scene(root));
stage.show();
} catch (IOException e) {e.printStackTrace();}
}
```
the first window opens and the new one opens, but my problem is getting events to work with my second window
in `main.fxml` I have this line:
```
<TextField id="chat_bar" onAction="#sendChat" layoutX="14.0" layoutY="106.0" prefHeight="22.0" prefWidth="403.0"/>
```
Then in my controller class I have this method:
```
@FXML
private void sendChat() {
System.out.println("test");
}
```
but Intellij is telling me that; no controller specified for top level element
So, my question is: Do I need to create multiple controller classes or can I use just one for multiple windows if so how? | 2014/08/26 | [
"https://Stackoverflow.com/questions/25496692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2292723/"
] | The recommended approach is to define a controller for each FXML. Since controllers are very lightweight this shouldn't add much overhead. The controller for your main.fxml file might be as simple as
```
import javafx.fxml.FXML ;
public class MainController {
@FXML
private void sendChat() {
// ...
}
}
```
I have used this approach with fairly large numbers of FXML files and corresponding controllers in a single project, and have had no issues with managing the code etc. I recommend using a naming convention of the form `Main.fxml <-> MainController`.
If your controllers need to share data, use the techniques outlined in [Passing Parameters JavaFX FXML](https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml/14190310#14190310)
As @Vertex points out in the comments, there is an alternative approach provided by the `FXMLLoader.setController(...)` method. So in your example above, you could do
```
@FXML
private void joinAction() {
Parent root;
try {
Stage stage = (Stage) joinButton.getScene().getWindow();
stage.close();
FXMLLoader loader = new FXMLLoader (getClass().getResource("main.fxml"));
loader.setController(this);
root = loader.load();
stage = new Stage();
stage.setTitle("TuneUs");
stage.setScene(new Scene(root));
stage.show();
} catch (IOException e) {e.printStackTrace();}
}
@FXML
private void sendChat() {
// ...
}
```
This approach is fine if you are not setting any fields (controls) via FXML injection (i.e. with an `fx:id` attribute in the fxml and a corresponding `@FXML` annotation in the controller). If you are, it will be very difficult to keep track of when those fields have been set. Moreover, if your `joinAction` handler is invoked multiple times, you will have multiple instances of the node created by main.fxml, but all sharing a single controller instance (and consequently overwriting the same injected fields). Also note that with this approach, your `initialize()` method will be invoked *both* when the original fxml file is loaded, **and** when the main.fxml file is loaded, which will almost certainly cause undesired effects.
One last note: if you have many FXML files, and corresponding controllers, you might want to look at the [afterburner.fx framework](http://afterburner.adam-bien.com/). This is a very lightweight framework that mandates a naming convention on FXML files and their corresponding controllers, and also provides a (very) easy mechanism for sharing data between them. | I create Borderpane, and inside it vbox at left and scene at the center and also implement initializable . Every time i click diff button in vbox, it changes only scene. For every scene, i create scene.fxml file. |
62,521,767 | I have variable from an HTML form that are currently being posted to one table in my database table.
I would like to post those same variables to other tables at the same time within the same function. Is this possible? Here is my current PHP function that is posting successfully to one table
```
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
// Database connection
$conn = new mysqli('localhost','user','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$execval = $stmt->execute();
echo $execval;
$stmt->close();
$conn->close();
}
?>
```
And I would like the following the variables to post to more than one table in the same database, so was thinking the following but it does not work -
```
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
// Database connection
$conn = new mysqli('localhost','user','password','database');
if($conn->connect_error){
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$stmt = $conn->prepare("insert into table2(var1) values(?)");
$stmt->bind_param("s", $var1);
$stmt = $conn->prepare("insert into table3(var2, var3) values(?, ?)");
$stmt->bind_param("ss", $var2, $var3);
$execval = $stmt->execute();
echo $execval;
$stmt->close();
$conn->close();
}
?>
``` | 2020/06/22 | [
"https://Stackoverflow.com/questions/62521767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13794315/"
] | Yes, it is possible. You can do what you are doing now, but you need to call `execute()` method after preparing each query. Apart from this, it would also be a good idea to wrap this in a transaction. Transactions help you make you sure that either all or none operations are successful. If one of them fails the others are not executed.
Your fixed code should look something like this:
```
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
// Database connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // switches error reporting on
$conn = new mysqli('localhost','user','password','database');
$conn->set_charset('utf8mb4'); // always set the charset
// Start transaction
$conn->begin_transaction();
$stmt = $conn->prepare("insert into table1(var1, var2, var3) values(?, ?, ?)");
$stmt->bind_param("sss", $var1, $var2, $var3);
$stmt->execute();
$stmt = $conn->prepare("insert into table2(var1) values(?)");
$stmt->bind_param("s", $var1);
$stmt->execute();
$stmt = $conn->prepare("insert into table3(var2, var3) values(?, ?)");
$stmt->bind_param("ss", $var2, $var3);
$stmt->execute();
// End transaction
$conn->commit();
``` | Try to call $stmt->execute(); after every calling of $stmt->bind\_param();
Take a look at this solved problem for executing multiple queries at the same call.
[PDO support for multiple queries (PDO\_MYSQL, PDO\_MYSQLND)](https://stackoverflow.com/questions/6346674/pdo-support-for-multiple-queries-pdo-mysql-pdo-mysqlnd) |
11,088,343 | Let's say I have a table with 1M rows and I need to add an index on it. What would be the process of doing so? Am I able to do `ALTER TABLE table ADD INDEX column (column)` directly on production? Or do I need to take other things into account to add the index.
How does one normally go about adding an index on a live production db? | 2012/06/18 | [
"https://Stackoverflow.com/questions/11088343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651174/"
] | First, get the `GtkTextBuffer` from the `GtkTextView` using `gtk_text_view_get_buffer()`. Then get the start and end *GtkTextIters* from the buffer to use to get the text of the buffer. Finally, write that text to the file using the API of your choice, however, I would recommend `Gio`. Here's a snippet from my old tutorial:
```c
gtk_widget_set_sensitive (text_view, FALSE);
buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (editor->text_view));
gtk_text_buffer_get_start_iter (buffer, &start);
gtk_text_buffer_get_end_iter (buffer, &end);
text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
gtk_text_buffer_set_modified (buffer, FALSE);
gtk_widget_set_sensitive (editor->text_view, TRUE);
/* set the contents of the file to the text from the buffer */
if (filename != NULL)
result = g_file_set_contents (filename, text, -1, &err);
else
result = g_file_set_contents (editor->filename, text, -1, &err);
if (result == FALSE)
{
/* error saving file, show message to user */
error_message (err->message);
g_error_free (err);
}
g_free (text);
```
Check out the following API documentation:
1. <http://developer.gnome.org/gtk3/stable/GtkTextBuffer.html>
2. [http://developer.gnome.org/glib/stable/glib-File-Utilities.html](http://developer.gnome.org/gtk3/stable/GtkTextBuffer.html) | ```
void on_toolbutton3_clicked(GtkToolButton *toolbutton, gpointer data)
{
GtkWidget *dialog;
dialog = gtk_file_chooser_dialog_new ("Abspeichern...",
NULL,
GTK_FILE_CHOOSER_ACTION_SAVE,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
NULL);
if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
{
char *filename;
char *text;
GtkTextIter *start;
GtkTextIter *end;
gboolean result;
GError *err;
filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
gtk_widget_set_sensitive (data, FALSE);
savebuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (data));
gtk_text_buffer_get_start_iter (savebuffer, &start);
gtk_text_buffer_get_end_iter (savebuffer, &end);
text = gtk_text_buffer_get_text (savebuffer, &start, &end, FALSE);
gtk_text_buffer_set_modified (savebuffer, FALSE);
gtk_widget_set_sensitive (data, TRUE);
/* set the contents of the file to the text from the buffer */
if (filename != NULL)
result = g_file_set_contents (filename, text, -1, &err);
else
result = g_file_set_contents (filename, text, -1, &err);
if (result == FALSE)
{
/* error saving file, show message to user */
}
g_free (text);
}
gtk_widget_destroy (dialog);
}
```
data points on textview1. |
852,814 | I'm trying to set up a VM network using vmbuilder. When setting it up using Ubuntu 12.04 there are no problems. However, when trying any of the newer LTS (14.04 or 16.04) i get the following error when I try to build my KVM:
```
Configuration file '/etc/sudoers'
==> Modified (by you or by a script) since installation.
==> Package distributor has shipped an updated version.
What would you like to do about it ? Your options are:
Y or I : install the package maintainer's version
N or O : keep your currently-installed version
D : show the differences between the versions
Z : start a shell to examine the situation
The default action is to keep your current version.
*** sudoers (Y/I/N/O/D/Z) [default=N] ? dpkg: error processing package sudo (--configure):
EOF on stdin at conffile prompt
Errors were encountered while processing:
sudo
E: Sub-process /usr/bin/dpkg returned an error code (1)
```
I have read a bunch of similar issues where the recommendation is more or less to blow out the whole system. This is however VERY undesirable in this case since we are running jobs on the computer each day. So please, if anyone knows a workaround??
FYI, this is how my VM.sh looks:
```
vmbuilder kvm ubuntu \
--dest=/home/pett/VM \
--overwrite \
--mem=15000\
--cpus=4 \
--rootsize=10240\
--swapsize=5000\
--addpkg=openssh-server \
--addpkg=vim \
--addpkg=cron \
--addpkg=acpid \
--arch=amd64 \
--suite=trusty\
--flavour virtual \
--components main,universe,restricted \
--hostname Buri \
--user pett \
--pass hello \
--libvirt qemu:///system ;
```
PS the following did NOT solve it:
```
sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f
``` | 2016/11/23 | [
"https://askubuntu.com/questions/852814",
"https://askubuntu.com",
"https://askubuntu.com/users/622692/"
] | I have exactly the same bug, on several fresh 1604 installations. I don't know why this doesn't get fixed, because it would come up if they ever tested this package.
The solution I found from another post is:
1. change the word 'dist-upgrade' to 'update' in
/usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.py
2. delete /usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.pyc
Annoying that the "solution" to a problem like this is to edit the installed package, but that's what it is. | From launchpad discussion:
>
> can you find in file /usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.py
> next string:
>
>
> self.run\_in\_target('apt-get', '-y', '--force-yes', 'dist-upgrade',
>
>
> and replace with:
>
>
> self.run\_in\_target('apt-get', '-y', '--force-yes',
> '--option=Dpkg::Options::=--force-confnew', 'dist-upgrade',
>
>
> and try to build new vm after that.
>
>
> I describe similar situation on my blog
> <http://anzhiganov.com/2016/11/02/869/>. it was useful for me.
>
>
> |
852,814 | I'm trying to set up a VM network using vmbuilder. When setting it up using Ubuntu 12.04 there are no problems. However, when trying any of the newer LTS (14.04 or 16.04) i get the following error when I try to build my KVM:
```
Configuration file '/etc/sudoers'
==> Modified (by you or by a script) since installation.
==> Package distributor has shipped an updated version.
What would you like to do about it ? Your options are:
Y or I : install the package maintainer's version
N or O : keep your currently-installed version
D : show the differences between the versions
Z : start a shell to examine the situation
The default action is to keep your current version.
*** sudoers (Y/I/N/O/D/Z) [default=N] ? dpkg: error processing package sudo (--configure):
EOF on stdin at conffile prompt
Errors were encountered while processing:
sudo
E: Sub-process /usr/bin/dpkg returned an error code (1)
```
I have read a bunch of similar issues where the recommendation is more or less to blow out the whole system. This is however VERY undesirable in this case since we are running jobs on the computer each day. So please, if anyone knows a workaround??
FYI, this is how my VM.sh looks:
```
vmbuilder kvm ubuntu \
--dest=/home/pett/VM \
--overwrite \
--mem=15000\
--cpus=4 \
--rootsize=10240\
--swapsize=5000\
--addpkg=openssh-server \
--addpkg=vim \
--addpkg=cron \
--addpkg=acpid \
--arch=amd64 \
--suite=trusty\
--flavour virtual \
--components main,universe,restricted \
--hostname Buri \
--user pett \
--pass hello \
--libvirt qemu:///system ;
```
PS the following did NOT solve it:
```
sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f
``` | 2016/11/23 | [
"https://askubuntu.com/questions/852814",
"https://askubuntu.com",
"https://askubuntu.com/users/622692/"
] | I have exactly the same bug, on several fresh 1604 installations. I don't know why this doesn't get fixed, because it would come up if they ever tested this package.
The solution I found from another post is:
1. change the word 'dist-upgrade' to 'update' in
/usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.py
2. delete /usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.pyc
Annoying that the "solution" to a problem like this is to edit the installed package, but that's what it is. | Note that there is a slightly better maintained community fork of python-vm-builder at <https://github.com/newroco/vmbuilder>.
Instead of using the system package, you install it with `sudo python setup.py install` |
852,814 | I'm trying to set up a VM network using vmbuilder. When setting it up using Ubuntu 12.04 there are no problems. However, when trying any of the newer LTS (14.04 or 16.04) i get the following error when I try to build my KVM:
```
Configuration file '/etc/sudoers'
==> Modified (by you or by a script) since installation.
==> Package distributor has shipped an updated version.
What would you like to do about it ? Your options are:
Y or I : install the package maintainer's version
N or O : keep your currently-installed version
D : show the differences between the versions
Z : start a shell to examine the situation
The default action is to keep your current version.
*** sudoers (Y/I/N/O/D/Z) [default=N] ? dpkg: error processing package sudo (--configure):
EOF on stdin at conffile prompt
Errors were encountered while processing:
sudo
E: Sub-process /usr/bin/dpkg returned an error code (1)
```
I have read a bunch of similar issues where the recommendation is more or less to blow out the whole system. This is however VERY undesirable in this case since we are running jobs on the computer each day. So please, if anyone knows a workaround??
FYI, this is how my VM.sh looks:
```
vmbuilder kvm ubuntu \
--dest=/home/pett/VM \
--overwrite \
--mem=15000\
--cpus=4 \
--rootsize=10240\
--swapsize=5000\
--addpkg=openssh-server \
--addpkg=vim \
--addpkg=cron \
--addpkg=acpid \
--arch=amd64 \
--suite=trusty\
--flavour virtual \
--components main,universe,restricted \
--hostname Buri \
--user pett \
--pass hello \
--libvirt qemu:///system ;
```
PS the following did NOT solve it:
```
sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f
``` | 2016/11/23 | [
"https://askubuntu.com/questions/852814",
"https://askubuntu.com",
"https://askubuntu.com/users/622692/"
] | Note that there is a slightly better maintained community fork of python-vm-builder at <https://github.com/newroco/vmbuilder>.
Instead of using the system package, you install it with `sudo python setup.py install` | From launchpad discussion:
>
> can you find in file /usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.py
> next string:
>
>
> self.run\_in\_target('apt-get', '-y', '--force-yes', 'dist-upgrade',
>
>
> and replace with:
>
>
> self.run\_in\_target('apt-get', '-y', '--force-yes',
> '--option=Dpkg::Options::=--force-confnew', 'dist-upgrade',
>
>
> and try to build new vm after that.
>
>
> I describe similar situation on my blog
> <http://anzhiganov.com/2016/11/02/869/>. it was useful for me.
>
>
> |
461,545 | ΠΠ°ΠΊΠΎΠΉ Π²Π°ΡΠΈΠ°Π½Ρ Π²Π΅ΡΠ½ΡΠΉ? Π‘ΠΏΠ°ΡΠΈΠ±ΠΎ!
1. Π‘Π»ΠΈΡΠΊΠΎΠΌ Π±ΡΡΡΡΠΎ ΠΎΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ Ρ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ, Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ ΡΠ΅Π»ΡΡΠ°, Π΄ΡΠ°Π³ΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΡΠ΅ΠΏΠ»ΠΎ.
2. Π‘Π»ΠΈΡΠΊΠΎΠΌ Π±ΡΡΡΡΠΎ ΠΎΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ Ρ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ, Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ ΡΠ΅Π»ΡΡΠ° Π΄ΡΠ°Π³ΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΡΠ΅ΠΏΠ»ΠΎ. | 2020/07/24 | [
"https://rus.stackexchange.com/questions/461545",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/192143/"
] | **Π ΠΊΠ°ΡΠ΅ΡΡΠ²Π΅ ΠΎΡΠ²Π΅ΡΠ°**
ΠΠ°ΠΊ Ρ ΡΠ΅Π±Π΅ ΠΏΡΠ΅Π΄ΡΡΠ°Π²Π»ΡΡ Ρ
ΠΎΡΠΎΡΠΈΠΉ ΠΎΡΠ²Π΅Ρ?
Π‘ ΠΎΠ΄Π½ΠΎΠΉ ΡΡΠΎΡΠΎΠ½Ρ, ΠΌΡ ΠΎΡΠ²Π΅ΡΠ°Π΅ΠΌ **ΠΊΠΎΠ½ΠΊΡΠ΅ΡΠ½ΠΎΠΌΡ**, Π° Π½Π΅ Π°Π±ΡΡΡΠ°ΠΊΡΠ½ΠΎΠΌΡ Π°Π²ΡΠΎΡΡ, ΠΏΠΎΡΡΠΎΠΌΡ ΠΆΠ΅Π»Π°ΡΠ΅Π»ΡΠ½ΠΎ ΠΏΠΎΠ½ΡΡΡ Ρ
ΠΎΠ΄ Π΅Π³ΠΎ ΠΌΡΡΠ»Π΅ΠΉ.
Π‘ Π΄ΡΡΠ³ΠΎΠΉ ΡΡΠΎΡΠΎΠ½Ρ, ΠΈΠ½ΡΠΎΡΠΌΠ°ΡΠΈΠΎΠ½Π½Π°Ρ ΡΠ°ΡΡΡ ΠΎΡΠ²Π΅ΡΠ° Π΄ΠΎΠ»ΠΆΠ½Π° ΠΈΠΌΠ΅ΡΡ **Π±Π΅Π·ΠΎΡΠ½ΠΎΡΠΈΡΠ΅Π»ΡΠ½ΡΡ ΡΠ΅Π½Π½ΠΎΡΡΡ**, ΡΠ°ΠΊ ΠΊΠ°ΠΊ ΠΏΠΎ Π±ΠΎΠ»ΡΡΠΎΠΌΡ ΡΡΠ΅ΡΡ ΠΊΠ°ΠΆΠ΄ΡΠΉ ΠΎΡΠ²Π΅Ρ Π²Π»ΠΈΡΠ΅Ρ Π½Π° ΠΊΠ°ΡΠ΅ΡΡΠ²Π΅Π½Π½ΡΠΉ ΡΡΠΎΠ²Π΅Π½Ρ ΠΈ ΠΏΡΠ΅ΡΡΠΈΠΆΠ½ΠΎΡΡΡ ΡΠ΅ΡΡΡΡΠ°.
**1. ΠΠΎΡΠ΅ΠΌΡ Π°Π²ΡΠΎΡ Π·Π°Π΄Π°Π΅Ρ ΠΏΠΎΠ΄ΠΎΠ±Π½ΡΠΉ Π²ΠΎΠΏΡΠΎΡ?** ΠΠ± ΡΡΠΎΠΌ Π²Π°ΠΆΠ½ΠΎ ΠΏΠΎΠ΄ΡΠΌΠ°ΡΡ ΠΏΡΠΈ ΠΎΡΠ²Π΅ΡΠ΅, ΠΈΠ½Π°ΡΠ΅ ΠΎΠ½ Π±ΡΠ΄Π΅Ρ ΡΠΎΡΠΌΠ°Π»ΡΠ½ΡΠΌ.
ΠΡΠΎ ΠΏΡΠΎΠ±Π»Π΅ΠΌΠ° **Β«Π»ΠΈΡΠ½ΠΈΡ
Π·Π°ΠΏΡΡΡΡ
Β»**, ΠΊΠΎΡΠΎΡΡΠ΅ ΡΡΠ°Π²ΡΡΡΡ Π½Π° ΠΌΠ΅ΡΡΠ΅ ΠΏΡΠΎΠΈΠ·Π½ΠΎΡΠΈΡΠ΅Π»ΡΠ½ΡΡ
ΠΏΠ°ΡΠ·. Π ΠΏΡΠΈΡΠΈΠ½Π° ΡΠ°ΠΊΠΎΠΉ ΠΏΠ°ΡΠ·Ρ Π² Π΄Π°Π½Π½ΠΎΠΌ ΡΠ»ΡΡΠ°Π΅ β **Π½Π΅ΡΠ΄Π°ΡΠ½ΠΎ ΠΏΠΎΡΡΡΠΎΠ΅Π½Π½ΠΎΠ΅ ΠΏΡΠ΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΠ΅**. ΠΠ½ΠΎ ΡΠ»ΠΎΠΆΠ½ΠΎ ΡΠΈΡΠ°Π΅ΡΡΡ ΠΈ Π½Π΅ ΡΡΠ°Π·Ρ ΠΏΠΎΠ½ΠΈΠΌΠ°Π΅ΡΡΡ, Π² ΡΠΎΠΌ ΡΠΈΡΠ»Π΅ Π½Π° ΡΠ»ΡΡ
.
ΠΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΠ΅ ΡΠ΅Π΄Π°ΠΊΡΠΈΡΠΎΠ²Π°Π½ΠΈΠ΅: *Π‘Π»ΠΈΡΠΊΠΎΠΌ Π±ΡΡΡΡΠΎ ΠΎΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ **Π΄ΡΠ°Π³ΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΡΠ΅ΠΏΠ»ΠΎ** Ρ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ, // Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ ΡΠ΅Π»ΡΡΠ°.*
Π ΡΡΠΎΠΌ Π²Π°ΡΠΈΠ°Π½ΡΠ΅ Π΄Π²Π΅ ΡΡΠ°Π·Ρ, Π·Π°ΠΏΡΡΠ°Ρ ΡΡΠ°Π²ΠΈΡΡΡ Π½Π° ΠΌΠ΅ΡΡΠ΅ ΠΏΠ°ΡΠ·Ρ. Π ΠΏΠΎΡΡΠ΄ΠΎΠΊ ΡΠ»ΠΎΠ² ΠΎΠ±ΠΎΡΠ½ΠΎΠ²Π°Π½Π½ΡΠΉ: ΡΠ½Π°ΡΠ°Π»Π° ΠΏΡΡΠΌΠΎΠ΅ Π΄ΠΎΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ (ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ ΡΡΠΎ?), Π° ΠΏΠΎΡΠΎΠΌ ΠΊΠΎΡΠ²Π΅Π½Π½ΠΎΠ΅ (ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ Ρ ΠΊΠΎΠ³ΠΎ?)
Π‘ΡΠ°Π²Π½ΠΈΠΌ: *Π‘Π»ΠΈΡΠΊΠΎΠΌ Π±ΡΡΡΡΠΎ ΠΎΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ Ρ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ, // **Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ ΡΠ΅Π»ΡΡΠ° Π΄ΡΠ°Π³ΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΡΠ΅ΠΏΠ»ΠΎ**.*
ΠΠ΄Π΅ΡΡ ΡΠΎΠΆΠ΅ Π΄Π²Π΅ ΡΡΠ°Π·Ρ, Π½ΠΎ Π²ΡΠΎΡΠ°Ρ ΡΡΠ°Π·Π° (ΠΏΠΎΡΠ»Π΅ Π·Π°ΠΏΡΡΠΎΠΉ) ΠΈΠΌΠ΅Π΅Ρ **Π½Π΅ΠΊΠΎΡΡΠ΅ΠΊΡΠ½ΡΡ ΠΏΠΎ ΡΠΎΡΠ΅ΡΠ°Π΅ΠΌΠΎΡΡΠΈ ΡΡΡΡΠΊΡΡΡΡ.**
ΠΠΎΡΡΠΎΠΌΡ ΠΏΡΠΈ ΠΎΡΠ²Π΅ΡΠ΅ ΠΆΠ΅Π»Π°ΡΠ΅Π»ΡΠ½ΠΎ ΠΎΠ±ΡΠ°ΡΠΈΡΡ Π²Π½ΠΈΠΌΠ°Π½ΠΈΠ΅ Π½Π° Π΄Π°Π½Π½ΡΠΉ ΡΠ°ΠΊΡ.
**2. Π ΡΠ°ΠΌΠΎΠΌ Π°Π½Π°Π»ΠΈΠ·Π΅**
ΠΡΠ°ΠΌΠΌΠ°ΡΠΈΠΊΠ° ΠΈ ΡΡΡΡΠΊΡΡΡΠ° ΠΏΡΠ΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΡ ΡΡΠ°Π½ΠΎΠ²ΡΡΡΡ ΡΡΠ½ΡΠΌΠΈ, Π΅ΡΠ»ΠΈ ΠΌΡ ΠΏΡΠΎΡΡΠΎ **ΡΠ±Π΅ΡΠ΅ΠΌ ΡΠ°ΡΠΏΡΠΎΡΡΡΠ°Π½Π΅Π½Π½ΠΎΠ΅ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅,** ΡΠΎΠ³Π΄Π° ΠΏΠΎΠ»ΡΡΠΈΡΡΡ:
*Π‘Π»ΠΈΡΠΊΠΎΠΌ Π±ΡΡΡΡΠΎ ΠΎΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ Ρ (**ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ, Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ**) ΡΠ΅Π»ΡΡΠ° Π΄ΡΠ°Π³ΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΡΠ΅ΠΏΠ»ΠΎ.*
ΠΡΠ΅Π΄Π»ΠΎΠ³ **Π£ ΠΎΡΠ½ΠΎΡΠΈΡΡΡ ΠΊ ΡΡΡΠ΅ΡΡΠ²ΠΈΡΠ΅Π»ΡΠ½ΠΎΠΌΡ**, ΠΏΠΎΡΡΠΎΠΌΡ ΠΌΡ Π½Π΅ ΠΌΠΎΠΆΠ΅ΠΌ ΡΠ°Π·Π΄Π΅Π»ΠΈΡΡ ΠΈΡ
Π·Π°ΠΏΡΡΠΎΠΉ. ΠΠΎΡ ΠΈ Π²ΡΡ Π΄ΠΎΠΊΠ°Π·Π°ΡΠ΅Π»ΡΡΡΠ²ΠΎ. ΠΠ½ Π½Π°ΠΌΠ½ΠΎΠ³ΠΎ ΠΏΡΠΎΡΠ΅ ΠΏΡΠΈΠ²Π΅Π΄Π΅Π½Π½ΠΎΠ³ΠΎ.
ΠΡΡΠ°ΡΠΈ, ΠΎΠ΄Π½ΠΎΡΠΎΠ΄Π½ΠΎΡΡΡ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠΉ Π·Π΄Π΅ΡΡ **Π½Π΅ΠΎΡΠ΅Π²ΠΈΠ΄Π½Π°**, Π·Π½Π°ΡΠ΅Π½ΠΈΡ ΡΠ°Π·Π½ΡΡ
ΠΏΡΠΈΠ·Π½Π°ΠΊΠΎΠ² ΡΠ±Π»ΠΈΠΆΠ°ΡΡΡΡ Π² Π΄Π°Π½Π½ΠΎΠΌ ΡΠ΅ΠΊΡΡΠ΅ (ΠΌΠ°Π»Π΅Π½ΡΠΊΠΈΠΉ ΠΏΡΠ΅Π΄ΠΌΠ΅Ρ Ρ Π½Π΅Π·Π°ΡΠΈΡΠ΅Π½Π½ΠΎΠΉ ΠΏΠΎΠ²Π΅ΡΡ
Π½ΠΎΡΡΡΡ ΠΎΡΡΡΠ²Π°Π΅Ρ Π±ΡΡΡΡΠ΅Π΅). | ***Π‘Π»ΠΈΡΠΊΠΎΠΌ Π±ΡΡΡΡΠΎ ΠΎΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ Ρ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ, Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ ΡΠ΅Π»ΡΡΠ° Π΄ΡΠ°Π³ΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΡΠ΅ΠΏΠ»ΠΎ***.
ΠΠΎΠ½Π΅ΡΠ½ΠΎ, Π²ΡΠΎΡΠΎΠΉ Π²Π°ΡΠΈΠ°Π½Ρ ΠΊΠΎΡΡΠ΅ΠΊΡΠ½ΡΠΉ β Π·Π°ΠΏΡΡΠ°Ρ ΠΏΠΎΡΠ»Π΅ ΡΠ»ΠΎΠ²Π° *ΡΠ΅Π»ΡΡΠ΅* Π½Π΅ Π½ΡΠΆΠ½Π°.
ΠΠ°Π²Π΅ΡΠ½ΠΎΠ΅, Π΅ΡΠ»ΠΈ Ρ Π²Π°Ρ Π²ΠΎΠ·Π½ΠΈΠΊ ΡΠ°ΠΊΠΎΠΉ Π²ΠΎΠΏΡΠΎΡ, ΡΠΎ Π²Ρ Π½Π΅ ΠΎΡΠ΅Π½Ρ ΡΠ°Π·ΠΎΠ±ΡΠ°Π»ΠΈΡΡ ΡΠΎ ΡΡΡΡΠΊΡΡΡΠΎΠΉ ΠΏΡΠ΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΡ, Ρ ΠΏΠΎΡΡΠ½Ρ:
*ΠΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ* (Π§ΡΠΎ?) *ΡΠ΅ΠΏΠ»ΠΎ* (Π£ ΠΊΠΎΠ³ΠΎ?) *Ρ ΡΠ΅Π»ΡΡΠ°* (ΠΠ°ΠΊΠΎΠ³ΠΎ?) *ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ ΠΈ Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ.*
*ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ ΠΈ Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ* β ΡΡΠΎ ΠΎΠ΄Π½ΠΎΡΠΎΠ΄Π½ΡΠ΅ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ. ΠΡΠΈ ΠΎΡΡΡΡΡΡΠ²ΠΈΠΈ ΡΠΎΡΠ·Π° ΠΌΠ΅ΠΆΠ΄Ρ Π½ΠΈΠΌΠΈ (ΠΊΠ°ΠΊ Π² Π²Π°ΡΠ΅ΠΌ ΡΠ»ΡΡΠ°Π΅) ΠΌΡ ΡΡΠ°Π²ΠΈΠΌ Π·Π°ΠΏΡΡΡΡ.
ΠΠΎΠ»ΡΡΠ΅ Π½ΠΈΠΊΠ°ΠΊΠΈΡ
Π·Π½Π°ΠΊΠΎΠ² ΠΏΡΠ΅ΠΏΠΈΠ½Π°Π½ΠΈΡ **ΠΠ Π’Π ΠΠΠ£ΠΠ’Π‘Π―**!
Π£ Π²Π°Ρ ΠΆΠ΅ Π² ΠΏΠ΅ΡΠ²ΠΎΠΌ Π²Π°ΡΠΈΠ°Π½ΡΠ΅ ΠΏΡΠ΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΡ Π²ΡΡΠ΅Π» ΡΠ²ΠΎΠ΅Π³ΠΎ ΡΠΎΠ΄Π° ΠΎΠ±ΠΎΡΠΎΠ±Π»Π΅Π½Π½ΡΠΉ ΠΎΠ±ΠΎΡΠΎΡ, ΠΊΠΎΡΠΎΡΠΎΠ³ΠΎ, ΠΊΠΎΠ½Π΅ΡΠ½ΠΎ ΠΆΠ΅, ΡΠ°ΠΌ Π±ΡΡΡ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ.
**ΠΠ°ΠΏΠΎΠΌΠ½ΠΈΡΠ΅:** ΠΎΠ±ΠΎΡΠΎΠ±Π»Π΅Π½Π½ΡΠ΅ ΠΎΠ±ΠΎΡΠΎΡΡ, ΠΊΠ°ΠΊ ΠΏΡΠ°Π²ΠΈΠ»ΠΎ, ΠΌΠΎΠΆΠ½ΠΎ Π²ΡΠ½ΡΡΡ ΠΈΠ· ΠΏΡΠ΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΡ, Π½Π΅ Π½Π°ΡΡΡΠΈΠ² ΠΏΡΠΈ ΡΡΠΎΠΌ Π΅Π³ΠΎ ΡΡΡΡΠΊΡΡΡΡ ΠΈ ΡΠΌΡΡΠ»!
ΠΠΎΠΏΡΠΎΠ±ΡΠΉΡΠ΅ ΠΈΠ· ΠΏΠ΅ΡΠ²ΠΎΠ³ΠΎ ΠΏΡΠ΅Π΄Π»ΠΎΠΆΠ΅Π½ΠΈΡ ΠΈΠ·ΡΡΡΡ ΠΎΠ±ΠΎΡΠΎΡ, ΠΊΠΎΡΠΎΡΡΠΉ Ρ Π²Π°Ρ Π²ΡΡΠ΅Π»:
**Π‘Π»ΠΈΡΠΊΠΎΠΌ Π±ΡΡΡΡΠΎ ΠΎΠ½ΠΈ ΠΎΡΠ½ΠΈΠΌΠ°ΡΡ Ρ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ** *, Π΅Π΄Π²Π° ΠΏΠΎΠΊΡΡΡΠΎΠ³ΠΎ ΠΏΠ΅ΡΡΡΠΌΠΈ ΡΠ΅Π»ΡΡΠ°,* **Π΄ΡΠ°Π³ΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΡΠ΅ΠΏΠ»ΠΎ**.
Π£ ΠΌΠ°Π»Π΅Π½ΡΠΊΠΎΠ³ΠΎ ΡΠ΅Π³ΠΎ?? ΠΠ°ΠΊ Π²ΠΈΠ΄ΠΈΡΠ΅, ΡΡΡΡΠΊΡΡΡΠ° Π½Π°ΡΡΡΠ΅Π½Π° ΠΈ ΡΠΌΡΡΠ» ΠΏΡΠΎΠΏΠ°Π», Π° ΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎ, Π²ΡΠΎΡΠ°Ρ Π·Π°ΠΏΡΡΠ°Ρ ΡΠ°ΠΌ Π»ΠΈΡΠ½ΡΡ. |
56,223 | I've noticed from titles of songs and poems, a definite article is used such as:
>
> 'An die Hoffnung'
>
> 'An die Freude'
>
> 'An die Musik'
>
>
>
A few websites give examples of the use of definite articles before nouns like
>
> 'Der Winter kommt'
>
>
>
rather than
>
> 'Winter kommt'
>
>
>
, but they don't explain why that's the case. I hope the question makes sense. | 2020/01/30 | [
"https://german.stackexchange.com/questions/56223",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/41488/"
] | German word order is not as strict as English word order. You may place subjects and objects as you like. The case markers tell the reader if a noun is a subject or an object, and which type of object.
German has no case markers on nouns apart from some exceptions (genitive singular and dative plural of some declination classes). Instead, it puts the case markers on the words describing a noun further. Adjectives, pronouns, number words. The indefinite article in German is identical with the number word Β»oneΒ«.
If there is no such describing word in front of a noun, you still need a case marker most times. That's when German puts the definite article in front of it.
Whereas, in English the definite article is only put in front of a noun as a pointing finger βa small demonstrativeβ. This use does exist in German, too, but it's not the only use of the definite article. | See section 3 of this link for where the definite article is used in German (but not in English)
<https://www.google.co.uk/amp/s/grammar.collinsdictionary.com/amp/german-easy-learning/articles> |
26,153 | I have a Channel Form set up which is working fine and inserting entries into a Channel with the default status.
Now there is a requirement to allow the status to be changed when creating the entry via the Channel Form but for the life of me I can't get it to work.
I have tried using the Channel Form {status} tags and also tried hardcoding the select drop down but no matter what I do the default status is applied.
Here's the EE tag version
```
<select id="status" name="status">
{statuses}
<option value="{status}"{selected}>{status}</option>
{/statuses}
</select>
```
And here's the HTML
```
<select name="status">
<option value="Pending">Pending</option>
<option value="Approved">Approved</option>
<option value="Declined">Declined</option>
</select>
```
The only thing I can think of is that I'm trying to set a custom status and not the normal "open" or "closed". Even using standard "open" and "closed" (via the EE generated drop down) doesn't work.
The site is using EE 2.9.0.
Has anyone run into this problem? | 2014/10/10 | [
"https://expressionengine.stackexchange.com/questions/26153",
"https://expressionengine.stackexchange.com",
"https://expressionengine.stackexchange.com/users/159/"
] | I've encountered exactly the same problem with 2.10.1. No matter what I set the status to, it always writes as 'Open'. I'm sure I've got the proper group assigned and title-casing for 'Pending'... I can only conclude it's a system bug. | Silly question, but you're sure the custom status group is assigned to that channel, right?
Have you tried {status\_menu} ?
<https://ellislab.com/expressionengine/user-guide/add-ons/channel/channel_form/#status>
Although the second code you tried looks like it should work. |
26,153 | I have a Channel Form set up which is working fine and inserting entries into a Channel with the default status.
Now there is a requirement to allow the status to be changed when creating the entry via the Channel Form but for the life of me I can't get it to work.
I have tried using the Channel Form {status} tags and also tried hardcoding the select drop down but no matter what I do the default status is applied.
Here's the EE tag version
```
<select id="status" name="status">
{statuses}
<option value="{status}"{selected}>{status}</option>
{/statuses}
</select>
```
And here's the HTML
```
<select name="status">
<option value="Pending">Pending</option>
<option value="Approved">Approved</option>
<option value="Declined">Declined</option>
</select>
```
The only thing I can think of is that I'm trying to set a custom status and not the normal "open" or "closed". Even using standard "open" and "closed" (via the EE generated drop down) doesn't work.
The site is using EE 2.9.0.
Has anyone run into this problem? | 2014/10/10 | [
"https://expressionengine.stackexchange.com/questions/26153",
"https://expressionengine.stackexchange.com",
"https://expressionengine.stackexchange.com/users/159/"
] | I've encountered exactly the same problem with 2.10.1. No matter what I set the status to, it always writes as 'Open'. I'm sure I've got the proper group assigned and title-casing for 'Pending'... I can only conclude it's a system bug. | i've this hardcoded checkbox tag working, didn't did anything special, try this..
```
<label for="open"><input name="status" type="radio" value="open" id="open" {if "{status}" == 'open'}Checked{/if}> <strong>Public</strong> </label>
<label for="draft"><input name="status" type="radio" value="draft" id="draft" {if "{status}" == 'draft'}Checked{/if}> <strong>Private</strong> </label>
```
Cheers. |
26,153 | I have a Channel Form set up which is working fine and inserting entries into a Channel with the default status.
Now there is a requirement to allow the status to be changed when creating the entry via the Channel Form but for the life of me I can't get it to work.
I have tried using the Channel Form {status} tags and also tried hardcoding the select drop down but no matter what I do the default status is applied.
Here's the EE tag version
```
<select id="status" name="status">
{statuses}
<option value="{status}"{selected}>{status}</option>
{/statuses}
</select>
```
And here's the HTML
```
<select name="status">
<option value="Pending">Pending</option>
<option value="Approved">Approved</option>
<option value="Declined">Declined</option>
</select>
```
The only thing I can think of is that I'm trying to set a custom status and not the normal "open" or "closed". Even using standard "open" and "closed" (via the EE generated drop down) doesn't work.
The site is using EE 2.9.0.
Has anyone run into this problem? | 2014/10/10 | [
"https://expressionengine.stackexchange.com/questions/26153",
"https://expressionengine.stackexchange.com",
"https://expressionengine.stackexchange.com/users/159/"
] | I've encountered exactly the same problem with 2.10.1. No matter what I set the status to, it always writes as 'Open'. I'm sure I've got the proper group assigned and title-casing for 'Pending'... I can only conclude it's a system bug. | i assume from your hard coded example you've set up the Status group with those entries? status is validated against the status group...
As Marc Miller illudes to, have you linked your custom status group to the channel you are posting in (Admin -> Channel Administration -> Channels -> Edit Group Assignments (on the desired channel))?
Lastly, using your hard coded example, haveyou double checked the casing on your statuses? They are case sensative! Worse still when you edit statuses in the CP Open and Closed are displayed *proper case*, however the value you need to submit in *lowercase* (notice this in lincolnpixel's example above?).
If you create a new status the value submitted should match the case you typed in on custom statuses editing screen, if its the default Open and Closed, these values must be lowercase. for the ultimate check look at your `exp_statuses` table. |
23,654 | My neighbor who lives across the hall from me in my apartment building is clearly trying to extend an olive branch of friendship. We met at a community gathering for residents a little over a month ago and got along splendidly, but due to opposing work schedules we have not seen each other since. I gather he has some social or professional contact wherein he can get free tickets to sporting events, because for the second time since we exchanged numbers, I've had to politely decline an invitation to a football game. I travel a lot for work, so I legitimately was and will be out of town on the dates in question.
Having just moved here recently, I don't have any friends and would welcome the companionship. My problem is twofold:
1. I don't want him to think that I'm blowing him off. People who consistently refuse invites -- even with good excuses -- stop getting invitations after a while.
2. I have a non-obvious, hard-to-explain visual impairment that makes sporting events *in particular* a no-go for me. It's a neurological condition that affects motion tracking and object recognition, so playing or watching sports is nearly impossible for me to enjoy. Aside from that (or maybe because of it), I'm not much of a sports guy anyway.
I want to let him know I appreciate the overture, and I figure the best thing to do would be to make a counter-proposal. But I don't really know how to do that. Personality-wise I'm an ambivert, so I do well in social situations most of the time; I just don't know how to initiate them.
* I have a very spartan, bachelor-esque studio apartment, so inviting him across the hall is out. I don't have anywhere to entertain guests. I don't even own a TV; I work in IT for a living, so my computer provides all my entertainment needs.
* I don't know what his interests are. Sporting events are such a stereotypical "guy" thing, so no real insight there. He's a lawyer professionally, so I don't know how our social spheres would intersect.
* I'm a homebody by nature and a recent transplant to the area, so I don't know much about what there is to do around town. I've found a few bars and restaurants that I like, but one-on-one those options sound like a date and I don't want to make things awkward. I have no idea what his intentions are.
* I'm rarely available on weekends, so any get-together would likely need to happen in the evening during the week. That precludes most festivals or block party-type events as those typically happen on Friday or Saturday nights.
I don't really know how to ask people to do things with me. How can I reciprocate or otherwise display that I am interested?
Also, how do I respond if he invites me to a game again and I'm actually free to go? | 2019/12/04 | [
"https://interpersonal.stackexchange.com/questions/23654",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/284/"
] | Honesty is the best policy here. He's only going to feel like you're "blowing him off" if your refusals are without reason. If you think more offers are forthcoming, your next response should be something like:
>
> Yes!
>
>
>
Or, if you can't, then:
>
> I'm sorry I keep turning down your invites, I really want to hang out but weekends are usually difficult for me. Can we do something on a weeknight instead?
>
>
>
As you are new in town and want to make friends, you should make an extra effort to take up this offer of friendship, no matter what the event. Unless being at a sports match is physically uncomfortable for you, why not just go along anyway and be honest - say something like "actually, I can't really follow sports because of a vision problem, but I appreciate the company". You can perhaps talk, have a few beers, and find something in common that you can bond over even if the sport doesn't hold any interest for you. In fact, most friendships/relationships rely on some give and take when it comes to choosing places to go, events to attend etc. If you are worried about the fact you've turned down his offers before, he might actually really appreciate it when he learns you came along to a sports match you can't watch properly just for the friendship.
Even if you don't think you're going to be best buddies with this guy because you have different interests, you'll soon meet other people through him, and you may get along better with them. That doesn't mean you're using him to meet people - if he attends things like the community event you met at and *still* wants to make new friends he sounds a pretty gregarious person that is welcoming you, not just into his life, but into his social group.
If you think you've already refused him too many times to get another invite, why not initiate contact and still say the above - that you'd like to hang, but weekends are difficult. See what happens. As he's contacted you several times with offers, he won't think it unusual that you've reached out to him.
If he suggests a one-to-one meeting rather than some social event, let him also suggest the venue - it's unlikely he will invite himself to your house, and if he suggests a bar or restaurant then it shouldn't be any place or setting that will make him feel weird. There are restaurants that feel like a date, but there are loads of places that are casual and normal places for platonic dates. | **My answers to you questions**
I am one of those people readily sending invitations to new acquaintances until I am tired of getting only "No, no" 's. I made a rule out of it: You're out at three no's in a row. You know too well why:
>
> I make him think that I'm blowing him off.
>
>
>
I have a second rule though: Back on track after the first invitation I get. So:
>
> How can I reciprocate or otherwise display that I am interested?
>
>
>
Show interest! Send an invitation. That easy.
>
> How do I respond if he invites me to a game again and I'm actually free to go?
>
>
>
Send him your point 2. Crystal clear for him.
You should not let him lose his time with invitations that you can't even *physiologically* accept.
**My own two cents on top of that**
To be honest, I am quite surprised to see how long your list of expectations, requirements, wonderings or fears (?) is. I find it quite interesting too - if not quite revealing - that you managed to put eleven "don't" or "don't know" in one single post.
I don't think there are many ways to put it:
Stop asking yourself too many questions. You don't go gambling with your life, you go for a nice chat with a good guy. You want to talk to him, he obviously does too, so go for it! It'll be fine.
If you really want to take all those parameters into account, here is my call: copy the link to your SE question and send it to him. You show interest. He knows what he should know. And you two can plan together your first common activity. |
63,983,714 | What would a piece of code look like which checks today's date, and if it's a particular date, it will print out a message?
The context is that I'm making a birthday cake for my son who codes and I want to write a themed Happy Birthday message on top correctly. (Sorry, not as clever or serious as a lot of the things on here!)
I'd like something which is basically:
```
johnsBirthday = 01/01/1998
johnsAge = todaysdate - johnsBirthday (in years)
if todays date == 01/01/XXXX then print("Happy Birthday John!" + johnsAge + " today!")
```
My knowledge of python is very limited (as I'm sure you can tell from the above) but I vaguely know how to do this in Excel, so I figure there must be a way to do it in python too?
I know could always just write out:
```
print("Happy Birthday, John!")
```
and he'd appreciate that, but I think it would really make him smile to go a little further than that! | 2020/09/20 | [
"https://Stackoverflow.com/questions/63983714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14311302/"
] | ```
# Import datetime class from datetime module
from datetime import datetime
birthday = "20/09/1998"
# Parses the string into a datetime object
birthday_obj = datetime.strptime(birthday, '%d/%m/%Y')
# Gets todays date
now = datetime.now()
# Checks the day and month to verify birthday status
if(birthday_obj.day == now.day and birthday_obj.month == now.month):
johns_age = str(now.year - birthday_obj.year)
print("Happy Birthday John! " + johns_age + " today!")
``` | For your purpose, it might be easier to use regular expressions if you are familiar with them. You can search any patterns you like, after converting datetimes to string, or better yet if you already have datetimes in string formats.
For datetime to string format conversion codes, check out -
[format-codes](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)
Example code
```
import re
from datetime import datetime
pattern = re.compile(r'^01/01/')
today_date = datetime.now().strftime(r'%d/%m/%Y')
some_date = '01/01/2021'
print(re.match(pattern, some_date)) # <re.Match object; span=(0, 6), match='01/01/'>
print(today_date) # 20/09/2020
print(pattern.match(today_date)) # None
```
Edit - Had forgotten that age needs to be calculated!
```
import re
from datetime import datetime
johns_birthday = '01/01/1998'
if (re.match('^01/01/', johns_birthday)):
johns_age = datetime.now().year - datetime.strptime(johns_birthday, r'%d/%m/%Y').year
print("Happy Birthday John! " + str(johns_age) + " today!")
``` |
4,200,359 | I want to βrankβ [primitive] Pythagorean triples by some metric that could reasonably be referred to as βsizeβ.
Naturally, there are a huge number of options: size of hypotenuse, size of smallest leg, perimeter, area, radius of incircle, etc. etc. etc. (Note: One thing I *donβt* want to use is the row index from the tripleβs position in one of the infinite ternary trees.)
Is there a widely-accepted βsizingβ of triples? What are the pros and cons of various metrics?
EDIT (inspired by Gerry Myersonβs comment): The βHoly Grailβ in this investigation would be a strictly βlinearβ ordering of the Pythagorean triples. Does (or can) such a thing exist?
EDIT #2: Let $(p,q)$ be the Euclid generating pair for a primitive Pythagorean triple. Applying the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) with $p-q$ and $q$ gives a unique integer value for each triple, which *generally* correlates with βsizeβ; and I have yet to find anything more compact (*e.g.,* in a set of $38$ of the βsmallestβ triples, the area-divided-by-6 range is $1β1820$, while the Cantor function for the same set has a range of $4β106$). Whatβs clearly missing is any obvious way to βdescendβ through this ordered set.
EDIT #3: The inradius is the most obvious βsizeβ ranking, since the only gaps in the sequence are the powers of $2$. The issue here is the fact that inradius isnβt unique. | 2021/07/16 | [
"https://math.stackexchange.com/questions/4200359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/93271/"
] | Given that side-A is odd, side-B is even, and side-C is odd, they take the form of $A = (2x+1), B=4y, C=4z+1), x,y,z\in\mathbb{N}.\quad$ Finding them is a relatively easy but pick any of the three and the solution seems incomplete without the other two. Also, side-A is larger than side-B for half of all triples. (I can demonstrate this if you want.)
Here are some other ratings and methods of finding them. Beginning with Euclid's formula shown here as
$ \qquad A=m^2-k^2\qquad B=2mk \qquad C=m^2+k^2.\qquad$ Note: any m-value that yields an integer k-value yields a valid Pythagorean triple.
$\bullet\space$ Perimeter in sizes shown [here](https://oeis.org/A024364)
\begin{equation}
P=2m^2+2mk\implies k=\frac{P-2m^2}{2m}\\
\text{for} \quad \biggl\lfloor\frac{\sqrt{4P+1}+1}{4}\biggr\rfloor\le m \le \biggl\lfloor\frac{\sqrt{2P+1}-1}{2}\biggr\rfloor
\end{equation}
The lower limit ensures that $m>k$ and the upper limit insures that $k\ge1$.
$$P=286\implies \biggl\lfloor\frac{\sqrt{1144+1}+1}{4}\biggr\rfloor =8\le m \le \biggl\lfloor\frac{\sqrt{572+1}-1}{2}\biggr\rfloor=11\\
\land\quad m\in\{11\}\implies k\in\{2\}$$
$$F(11,2)=(117,44,125)\qquad P=(117+44+125)=286$$
$\bullet\space$ Area:perimeter ratio$\space$ (All are multiples of $\frac{1}{2}$ and here is a way to find them)
$$R=\frac{area}{perimeter}=\frac{AB}{2P}=\frac{2mk(m^2-k^2)}{2(2m^2+2mk)}=\frac{mk-k^2}{2}
$$
\begin{equation}
R=\frac{mk-k^2}{2}\quad\implies k=\frac{m\pm\sqrt{m^2-8R}}{2}\\\text{for}\quad \big\lceil\sqrt{8R}\big\rceil\le m \le (2R+1)
\end{equation}
The lower limit insures that $k\in \mathbb{N}$ and the upper limit ensures that $m> k$.
$$R=1\implies \lceil\sqrt{8}\rceil=3\le m \le (2+1)=3 \\\land\qquad m\in\{ 3\}\implies k\in\{ 2,1\}$$
$$F(3,2)=(5,12,13)\space\land\space \frac{30}{30}=1\qquad F(3,1)=(8,6,10)\space\land\space \frac{24}{24}=1$$
$\bullet\space$ Area (Sizes are multiples of $6$ listed in [this](https://oeis.org/A009112) series). Up to $3$ distinct triples can have the same area.
\begin{equation}
k\_0=\sqrt{\frac{4m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\cos^{-1}{\biggl(-\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}
\\ k\_1=\sqrt{\frac{4m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\cos^{-1}{\biggl(\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}
\\ k\_2=k\_1-k\_0
\\\qquad\text{ for }\quad\bigg\lfloor\sqrt[\LARGE{4}]{\frac{8D}{3}}\bigg\rfloor
\le m \le\big\lceil\sqrt[\LARGE{3}]{D}\big\rceil
\end{equation}
$$D=840\implies \lfloor\sqrt[\LARGE{4}]{2(840)}\rfloor=7 \le m \le \lceil\sqrt[\LARGE{3}]{840}\rceil=10\quad\text {and we find}$$
$$m\in \{7\}\implies k\in\{5,8,3\}\qquad\land\qquad m\in\{8\}\implies k\in\{7\}$$
$$\text{We find }\qquad S\_{mk}=\{(7,5), (7,8), (7,3), (8,7)\}$$
$$F(7,5)=(24,70,74)\quad F(7,8)=(-15,112,113)\\ F(7,3)=(40,42,58)\quad F(8,7)=(15,112,113)$$
$\bullet\space$ A,B,C product sizes seen [here](https://oeis.org/A057096)
( All are multiples of $60$. Finding them requires a more convoluted solution available on request.)
$\bullet\space B-A=1$ side difference.
An interesting solution to $B-A=1$ was provided by WacΕaw SierpiΕski, $\textit{Pythagorean triangles}$,
THE SCRPTA MATHEMATICA STUDIES Number NINE, ,
GRADUATE SCHOOL OF SCIENCE YESHIVA UNIVERSITY, NEW YORK, 1962, pp. 17-22
with a formula that generates these triples $(T\_n)$ sequentially with a starting "seed" of $T\_0=(0,0,1)$.
\begin{equation}T\_{n+1}=3A\_n+2C\_n+1\qquad B\_{n+1}=3A\_n+2C\_n+2 \qquad C\_{n+1}=4A\_n+3C\_n+2\end{equation}
$$T\_1=(3,4,5)\qquad T\_2=(20,21,29)\qquad T\_3=(119,120,169)\qquad \textbf{ ...}$$
In casual testing, it appears that only the sums and products of A,B,C have unique solutions (only one triple per value) and Area/Perimeter ratio is a pleasing set
$\big(R=\big\{\frac{1}{2},\frac{2}{2},\frac{3}{2},\cdots\big\}\big)$
so perhaps one of these are the most "natural" series to pursue.
$\textbf{Update:}$ Gerry Myerson has shown below that perimeter does not map to a unique triple. | Concerning the so-called sign issue with the ternary tree:
The Wikipedia essay cited elsewhere on this page gives the three matrices $$A=\pmatrix{1&-2&2\cr2&-1&2\cr2&-2&3\cr},\qquad B=\pmatrix{1&2&2\cr2&1&2\cr2&2&3\cr},\qquad C=\pmatrix{-1&2&2\cr-2&1&2\cr-2&2&3\cr}$$ with the properties that 1) if $v$ is a (positive) primitive pythagorean triple then so are $Av$, $Bv$, and $Cv$, 2) every primitive pythagorean triple can be obtained from $v=(3,4,5)$ in exactly one way by multiplying by a (finite) sequence of matrices, each matrix in the sequence being $A$ or $B$ or $C$.
We calculate the inverses, $$A^{-1}=\pmatrix{1&2&-2\cr-2&-1&2\cr-2&-2&3\cr},\qquad B^{-1}=\pmatrix{1&2&-2\cr2&1&-2\cr-2&-2&3\cr},\qquad C^{-1}=\pmatrix{-1&-2&2\cr2&1&-2\cr-2&-2&3\cr}$$ It follows that given any (positive) primitive pythagorean triple $w$, exactly one of the three vectors $A^{-1}w,B^{-1}w,C^{-1}w$ is a positive pythagorean triple.
For example, for $w=(165,52,173)$, we get $A^{-1}w=(-77,-36,85)$, $B^{-1}w=(-77,36,85)$, and $C^{-1}w=(77,36,85)$, so $C^{-1}w$ is the direct ancestor of $w$ on the tree. |
4,200,359 | I want to βrankβ [primitive] Pythagorean triples by some metric that could reasonably be referred to as βsizeβ.
Naturally, there are a huge number of options: size of hypotenuse, size of smallest leg, perimeter, area, radius of incircle, etc. etc. etc. (Note: One thing I *donβt* want to use is the row index from the tripleβs position in one of the infinite ternary trees.)
Is there a widely-accepted βsizingβ of triples? What are the pros and cons of various metrics?
EDIT (inspired by Gerry Myersonβs comment): The βHoly Grailβ in this investigation would be a strictly βlinearβ ordering of the Pythagorean triples. Does (or can) such a thing exist?
EDIT #2: Let $(p,q)$ be the Euclid generating pair for a primitive Pythagorean triple. Applying the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) with $p-q$ and $q$ gives a unique integer value for each triple, which *generally* correlates with βsizeβ; and I have yet to find anything more compact (*e.g.,* in a set of $38$ of the βsmallestβ triples, the area-divided-by-6 range is $1β1820$, while the Cantor function for the same set has a range of $4β106$). Whatβs clearly missing is any obvious way to βdescendβ through this ordered set.
EDIT #3: The inradius is the most obvious βsizeβ ranking, since the only gaps in the sequence are the powers of $2$. The issue here is the fact that inradius isnβt unique. | 2021/07/16 | [
"https://math.stackexchange.com/questions/4200359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/93271/"
] | In all the series I searched, I could not find anything suggesting that any $A\times B\times C$ product represents more than one Pythagorean triple. [Here](https://oeis.org/A063011) are primitive triple product values.
$$P=(m^2-k^2)(2mk)(m^2+k^2) =2 m^5k - 2 mk^5\implies 2mk^5- 2 m^5k + P=0$$
One method of finding these triples is to find the hypotenuse, divide the product by the hypotenuse to find area, and then find the [one-and-only] triple (by area) that has that hypotenuse. This method was provide by [Yuri Negometyanov](https://www.facebook.com/yuri.negometyanov)
of Kyiv, Ukraine
[here](https://math.stackexchange.com/questions/3502266/how-do-i-solve-the-quintic-n5-m4n-fracp2m-0-for-n?rq=1).
His logic shows how, for $C$ as a factor of P, we can feel confident that
\begin{equation}
\sqrt[3]{2P} < C < \frac{\sqrt{(4P)^{\frac{4}{5}}+1 } + 1}{2}\quad \land \quad C\bigg |\frac{P}{12}
\end{equation}
Any "candidate" factor in this range must take the form of $(4x+1)$ and must also divide $\dfrac{P}{12}$.
For an example, we will use a product: $P=192720$.
$$P=192720\implies \big\lfloor\sqrt[3]{2(192720)}\big\rfloor = 72 \le C \le \left\lfloor\frac{\sqrt{\big(4(192720)\big)^{\frac{4}{5}}+1 } + 1}{2}\right\rfloor=113$$
$$\land\quad
\frac{P}{12} =\frac{192720}{12}=16060$$
Only $4$ of the factors of $192720$ and $2$ of the factors of $16060$ are between $72$ and $113$.
In this case only 73 is in "C-format" where $\quad \big(C=4x+1\big)\quad$ and only 73 divides P/12 where $\quad \bigg(\dfrac{16060}{73}=1320\bigg).\quad$ We now substitute $1320$ into the area-formula
\begin{equation}
k\_0=\sqrt{\frac{4m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\cos^{-1}{\biggl(-\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}
\\ k\_1=\sqrt{\frac{4m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\cos^{-1}{\biggl(\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}
\\ k\_2=k\_1-k\_0
\\\qquad\text{ for }\quad\bigg\lfloor\sqrt[4]{\frac{8D}{3}}\bigg\rfloor
\le m \le\big\lceil\sqrt[3]{D}\big\rceil
\end{equation}
$$D=1320\implies \lfloor\sqrt[4]{1320}\rfloor=6 \le m \le \lceil\sqrt[3]{1320}\space\rceil=11\quad\land\quad m\in \{8,11\}\implies k\in\{3,1\}$$
$$F(8,3)=(55,48,73)\qquad F(11,1)=(120,22,122)$$
Of these findings, we can see that only one triple has $C=73$ and that $P=55\times48\times73=192720$. | Concerning the so-called sign issue with the ternary tree:
The Wikipedia essay cited elsewhere on this page gives the three matrices $$A=\pmatrix{1&-2&2\cr2&-1&2\cr2&-2&3\cr},\qquad B=\pmatrix{1&2&2\cr2&1&2\cr2&2&3\cr},\qquad C=\pmatrix{-1&2&2\cr-2&1&2\cr-2&2&3\cr}$$ with the properties that 1) if $v$ is a (positive) primitive pythagorean triple then so are $Av$, $Bv$, and $Cv$, 2) every primitive pythagorean triple can be obtained from $v=(3,4,5)$ in exactly one way by multiplying by a (finite) sequence of matrices, each matrix in the sequence being $A$ or $B$ or $C$.
We calculate the inverses, $$A^{-1}=\pmatrix{1&2&-2\cr-2&-1&2\cr-2&-2&3\cr},\qquad B^{-1}=\pmatrix{1&2&-2\cr2&1&-2\cr-2&-2&3\cr},\qquad C^{-1}=\pmatrix{-1&-2&2\cr2&1&-2\cr-2&-2&3\cr}$$ It follows that given any (positive) primitive pythagorean triple $w$, exactly one of the three vectors $A^{-1}w,B^{-1}w,C^{-1}w$ is a positive pythagorean triple.
For example, for $w=(165,52,173)$, we get $A^{-1}w=(-77,-36,85)$, $B^{-1}w=(-77,36,85)$, and $C^{-1}w=(77,36,85)$, so $C^{-1}w$ is the direct ancestor of $w$ on the tree. |
4,200,359 | I want to βrankβ [primitive] Pythagorean triples by some metric that could reasonably be referred to as βsizeβ.
Naturally, there are a huge number of options: size of hypotenuse, size of smallest leg, perimeter, area, radius of incircle, etc. etc. etc. (Note: One thing I *donβt* want to use is the row index from the tripleβs position in one of the infinite ternary trees.)
Is there a widely-accepted βsizingβ of triples? What are the pros and cons of various metrics?
EDIT (inspired by Gerry Myersonβs comment): The βHoly Grailβ in this investigation would be a strictly βlinearβ ordering of the Pythagorean triples. Does (or can) such a thing exist?
EDIT #2: Let $(p,q)$ be the Euclid generating pair for a primitive Pythagorean triple. Applying the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) with $p-q$ and $q$ gives a unique integer value for each triple, which *generally* correlates with βsizeβ; and I have yet to find anything more compact (*e.g.,* in a set of $38$ of the βsmallestβ triples, the area-divided-by-6 range is $1β1820$, while the Cantor function for the same set has a range of $4β106$). Whatβs clearly missing is any obvious way to βdescendβ through this ordered set.
EDIT #3: The inradius is the most obvious βsizeβ ranking, since the only gaps in the sequence are the powers of $2$. The issue here is the fact that inradius isnβt unique. | 2021/07/16 | [
"https://math.stackexchange.com/questions/4200359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/93271/"
] | Too big for a comment.
In 2009, I arranged the smallest primitives in a pattern where the same values of $C-B$ were all in the same respective rows. All were odd squares $(2n-1)^2$ and each A-value increment was $(2n-1)$.
It was then easy develop a new formula $F(n,k)$ and, later, to see that it was the same as Euclid's formula $F(m,k)\quad$ if $\quad F(n,k)=F(2m-1+k,k).$
\begin{align\*}
A=(2n-1)^2+ &\quad 2(2n-1)k \\
B= \qquad &\quad 2(2n-1)k+ \space 2k^2\\
C=(2n-1)^2+ &\quad 2(2n-1)k+ 2k^2\\
\end{align\*}
and here is a sample of the "sets" of triples it produces.
\begin{array}{c|c|c|c|c|c|}
n & k=1 & k=2 & k=3 & k=4 & k=5 \\ \hline
Set\_1 & 3,4,5 & 5,12,13& 7,24,25& 9,40,41& 11,60,61 \\ \hline
Set\_2 & 15,8,17 & 21,20,29 &27,36,45 &33,56,65 & 39,80,89 \\ \hline
Set\_3 & 35,12,37 & 45,28,53 &55,48,73 &65,72,97 & 75,100,125 \\ \hline
Set\_{4} &63,16,65 &77,36,85 &91,60,109 &105,88,137 &119,120,169 \\ \hline
Set\_{5} &99,20,101 &117,44,125 &135,72,153 &153,104,185 &171,140,221 \\ \hline
Set\_{6} &43,24,145 &165,52,173 &187,84,205 &209,120,241 &231,160,281 \\ \hline
\end{array}
Note that row$\_1$ and column$\_1$ are all primitives but, for example, $F(2,3)=(27,36,45)$ is non-primitive. This happens any time $k$ is a multiple of any factor of $(2n-1)$. Aside from $Set\_1$
where $(2n-1)=1$, if $(2n-1)$ is prime, the following formula will produce only primitives by generating $(2n-1)-(1)$ primitives and then skipping a triple.
\begin{align\*}
&A=(2n-1)^2+&2(2n-1)\bigg(k+\bigg\lfloor\frac{(k-1)}{(2n-2)}\bigg\rfloor\bigg)&\qquad\\
&B=&2(2n-1)\bigg(k+\bigg\lfloor\frac{(k-1)}{(2n-2)}\bigg\rfloor\bigg)&\qquad+2\bigg(k+\bigg\lfloor\frac{(k-1)}{(2n-2)}\bigg\rfloor\bigg)^2\\
&C=(2n-1)^2+&2(2n-1)\bigg(k+\bigg\lfloor\frac{(k-1)}{(2n-2)}\bigg\rfloor\bigg)&\qquad+2\bigg(k+\bigg\lfloor\frac{(k-1)}{(2n-2)}\bigg\rfloor\bigg)^2
\end{align\*}
If $(2n-1)$ is composite, a primitives will occur more often and, perhaps, they may only be counted using the inclusion exclusion principal. For example, we use $Set\_{53}, (2n-1)=105$ which has prime factors $3,5,$ and $7$. Below we let X,Y, and Z be "prime counts" when $k=107$.
\begin{equation} (X\cup Y\cup Z)=(X)+(Y)+(Z)-(X\cap Y)-(X\cap Z)-(Y\cap Z)+(X\cap Y\cap Z) \end{equation}
$$X=\biggl\lfloor\frac{107}{3}\biggr\rfloor=35\qquad Y=\biggl\lfloor\frac{107}{5}\biggr\rfloor=21\qquad X=\biggl\lfloor\frac{107}{7}\biggr\rfloor=15$$
$$X\cap Y=\biggl\lfloor\frac{107}{3\*5}\biggr\rfloor=7\quad X\cap Z=\biggl\lfloor\frac{107}{3\*7}\biggr\rfloor=5\quad Y\cap Z=\biggl\lfloor\frac{107}{5\*7}\biggr\rfloor=3$$
$$ X\cap Y\cap Z=\biggl\lfloor\frac{107}{3\*5\*7}\biggr\rfloor=1$$
$$\text{The "multiple count" is }\quad X\cup Y\cup Z=35+21+15-7-5-3+1=57$$
\par
Out of $107$ triples for $n=53\land k=107$ the number of primitives is $107-57=50$.
But the whole point of this presentation is to show how these triples may be related to natural numbers and made ordinal using Cantor's pairing function. A simple technique does not produce triples in size order but it does follow Cantor's function and is helped by the fact the $F(n,k)$ produces no trivial triples or the doubles and even-square multiples that Euclid's formula does.
If we increment $n$ and $k$ in specific patterns, we get
$(1,1),\\
(1,2),\space (2,1),\\
(1,3),\space (2,2),\space (3,1),\\
(1,4),\space (2,3),\space (3,2),\space (4,1)$
Note that $F(2,3)=(27,36,45)$ and others are non-primitive but I don't know what to do about that. Whether that is addressed or not, perhaps you can find the "products" of all these, and see what order $(n,k)$ can be arranged to selected for ascending size. Here are a few that I believe are arranged in "product" order.
$$(3,4,5)\quad
(5,12,13)\quad
(15,8,17)\quad
(7,24,25)\quad
(21,20,29)\\
(35,12,37)\quad
(9,40,41)\quad
(11,60,61)\quad
(63,16,65)\quad
(45,28,53)$$
Aside: I have proven (not here) that the formula generates all primitives by assuming some increment added to or subtracted from the $k$ components. Expansion shows that any other increment results in non-integer values for B and C. | Concerning the so-called sign issue with the ternary tree:
The Wikipedia essay cited elsewhere on this page gives the three matrices $$A=\pmatrix{1&-2&2\cr2&-1&2\cr2&-2&3\cr},\qquad B=\pmatrix{1&2&2\cr2&1&2\cr2&2&3\cr},\qquad C=\pmatrix{-1&2&2\cr-2&1&2\cr-2&2&3\cr}$$ with the properties that 1) if $v$ is a (positive) primitive pythagorean triple then so are $Av$, $Bv$, and $Cv$, 2) every primitive pythagorean triple can be obtained from $v=(3,4,5)$ in exactly one way by multiplying by a (finite) sequence of matrices, each matrix in the sequence being $A$ or $B$ or $C$.
We calculate the inverses, $$A^{-1}=\pmatrix{1&2&-2\cr-2&-1&2\cr-2&-2&3\cr},\qquad B^{-1}=\pmatrix{1&2&-2\cr2&1&-2\cr-2&-2&3\cr},\qquad C^{-1}=\pmatrix{-1&-2&2\cr2&1&-2\cr-2&-2&3\cr}$$ It follows that given any (positive) primitive pythagorean triple $w$, exactly one of the three vectors $A^{-1}w,B^{-1}w,C^{-1}w$ is a positive pythagorean triple.
For example, for $w=(165,52,173)$, we get $A^{-1}w=(-77,-36,85)$, $B^{-1}w=(-77,36,85)$, and $C^{-1}w=(77,36,85)$, so $C^{-1}w$ is the direct ancestor of $w$ on the tree. |
59,608,312 | I am trying to set up the workspace for creating mods for Minecraft. I installed JRE, installed JDK 8. I installed eclipse. I downloaded the latest mdk file of minecraft forge. I setup the environment variables for JDK. I extracted the forge zip file. I opened powershell in the extracted forge folder. I ran the command `.\gradlew setupDecompWorkspace`. I am getting the following error:
```
> FAILURE: Build failed with an exception.
>
> * What went wrong: A problem occurred configuring root project 'First Mod'.
> > Could not resolve all files for configuration ':_compileJava_1'.
> > Could not resolve com.mojang:patchy:1.1.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve oshi-project:oshi-core:1.1.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.ibm.icu:icu4j-core-mojang:51.2.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:javabridge:1.0.22.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:brigadier:1.0.17.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:datafixerupper:2.0.24.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:authlib:1.5.25.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:text2speech:1.11.3.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
>
> * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
>
> * Get more help at https://help.gradle.org
>
> Deprecated Gradle features were used in this build, making it
> incompatible with Gradle 5.0. Use '--warning-mode all' to show the
> individual deprecation warnings. See
> https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings
```
How do I fix this error? I even tried the other command that I found online. ".\gradlew genEclipseRuns` this gives the following error:
```
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'First Mod'.
> Could not resolve all files for configuration ':_compileJava_1'.
> Could not resolve com.mojang:patchy:1.1.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve oshi-project:oshi-core:1.1.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.ibm.icu:icu4j-core-mojang:51.2.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:javabridge:1.0.22.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:brigadier:1.0.17.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:datafixerupper:2.0.24.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:authlib:1.5.25.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:text2speech:1.11.3.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 44s
```
This is the gradle.build file present in the minecraft forge folder:
```
buildscript {
repositories {
maven { url = 'https://files.minecraftforge.net/maven' }
jcenter()
mavenCentral()
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true
}
}
apply plugin: 'net.minecraftforge.gradle'
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'eclipse'
apply plugin: 'maven-publish'
version = '1.0'
group = 'com.yourname.modid' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'modid'
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.
minecraft {
// The mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD Snapshot are built nightly.
// stable_# Stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'snapshot', version: '20190719-1.14.3'
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
server {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/')
mods {
examplemod {
source sourceSets.main
}
}
}
}
}
dependencies {
// Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed
// that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.15.1-30.0.26'
// You may put jars on which you depend on in ./libs or you may define them like so..
// compile "some.group:artifact:version:classifier"
// compile "some.group:artifact:version"
// Real examples
// compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
// compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
// provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// These dependencies get remapped to your current MCP mappings
// deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// Example for how to get properties into the manifest for reading by the runtime..
jar {
manifest {
attributes([
"Specification-Title": "examplemod",
"Specification-Vendor": "examplemodsareus",
"Specification-Version": "1", // We are version 1 of ourselves
"Implementation-Title": project.name,
"Implementation-Version": "${version}",
"Implementation-Vendor" :"examplemodsareus",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
}
// Example configuration to allow publishing using the maven-publish task
// we define a custom artifact that is sourced from the reobfJar output task
// and then declare that to be published
// Note you'll need to add a repository here
def reobfFile = file("$buildDir/reobfJar/output.jar")
def reobfArtifact = artifacts.add('default', reobfFile) {
type 'jar'
builtBy 'reobfJar'
}
publishing {
publications {
mavenJava(MavenPublication) {
artifact reobfArtifact
}
}
repositories {
maven {
url "file:///${project.projectDir}/mcmodsrepo"
}
}
}
``` | 2020/01/06 | [
"https://Stackoverflow.com/questions/59608312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10551333/"
] | I think the gradle version you are using is too high.Youre currently using gradle 5.0 and you should try to use gradle 4.9. | The solution that worked for me is simple instead of `gradlew setupDecompWorkspace`, use `gradlew eclipse`. For those of you who found this as a result on google, it won't with Intellij. |
59,608,312 | I am trying to set up the workspace for creating mods for Minecraft. I installed JRE, installed JDK 8. I installed eclipse. I downloaded the latest mdk file of minecraft forge. I setup the environment variables for JDK. I extracted the forge zip file. I opened powershell in the extracted forge folder. I ran the command `.\gradlew setupDecompWorkspace`. I am getting the following error:
```
> FAILURE: Build failed with an exception.
>
> * What went wrong: A problem occurred configuring root project 'First Mod'.
> > Could not resolve all files for configuration ':_compileJava_1'.
> > Could not resolve com.mojang:patchy:1.1.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve oshi-project:oshi-core:1.1.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.ibm.icu:icu4j-core-mojang:51.2.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:javabridge:1.0.22.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:brigadier:1.0.17.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:datafixerupper:2.0.24.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:authlib:1.5.25.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
> > Could not resolve com.mojang:text2speech:1.11.3.
> Required by:
> project : > net.minecraft:client:1.15.1
> > Skipped due to earlier error
>
> * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
>
> * Get more help at https://help.gradle.org
>
> Deprecated Gradle features were used in this build, making it
> incompatible with Gradle 5.0. Use '--warning-mode all' to show the
> individual deprecation warnings. See
> https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings
```
How do I fix this error? I even tried the other command that I found online. ".\gradlew genEclipseRuns` this gives the following error:
```
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'First Mod'.
> Could not resolve all files for configuration ':_compileJava_1'.
> Could not resolve com.mojang:patchy:1.1.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve oshi-project:oshi-core:1.1.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.ibm.icu:icu4j-core-mojang:51.2.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:javabridge:1.0.22.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:brigadier:1.0.17.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:datafixerupper:2.0.24.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:authlib:1.5.25.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
> Could not resolve com.mojang:text2speech:1.11.3.
Required by:
project : > net.minecraft:client:1.15.1
> Skipped due to earlier error
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 44s
```
This is the gradle.build file present in the minecraft forge folder:
```
buildscript {
repositories {
maven { url = 'https://files.minecraftforge.net/maven' }
jcenter()
mavenCentral()
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true
}
}
apply plugin: 'net.minecraftforge.gradle'
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'eclipse'
apply plugin: 'maven-publish'
version = '1.0'
group = 'com.yourname.modid' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'modid'
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.
minecraft {
// The mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD Snapshot are built nightly.
// stable_# Stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'snapshot', version: '20190719-1.14.3'
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
server {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/')
mods {
examplemod {
source sourceSets.main
}
}
}
}
}
dependencies {
// Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed
// that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.15.1-30.0.26'
// You may put jars on which you depend on in ./libs or you may define them like so..
// compile "some.group:artifact:version:classifier"
// compile "some.group:artifact:version"
// Real examples
// compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
// compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
// provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// These dependencies get remapped to your current MCP mappings
// deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// Example for how to get properties into the manifest for reading by the runtime..
jar {
manifest {
attributes([
"Specification-Title": "examplemod",
"Specification-Vendor": "examplemodsareus",
"Specification-Version": "1", // We are version 1 of ourselves
"Implementation-Title": project.name,
"Implementation-Version": "${version}",
"Implementation-Vendor" :"examplemodsareus",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
}
// Example configuration to allow publishing using the maven-publish task
// we define a custom artifact that is sourced from the reobfJar output task
// and then declare that to be published
// Note you'll need to add a repository here
def reobfFile = file("$buildDir/reobfJar/output.jar")
def reobfArtifact = artifacts.add('default', reobfFile) {
type 'jar'
builtBy 'reobfJar'
}
publishing {
publications {
mavenJava(MavenPublication) {
artifact reobfArtifact
}
}
repositories {
maven {
url "file:///${project.projectDir}/mcmodsrepo"
}
}
}
``` | 2020/01/06 | [
"https://Stackoverflow.com/questions/59608312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10551333/"
] | Replacing every instance of "http://files.minecraftforge.net/maven" with "https://libraries.minecraft.net" in build.gradle fixed it for me. | The solution that worked for me is simple instead of `gradlew setupDecompWorkspace`, use `gradlew eclipse`. For those of you who found this as a result on google, it won't with Intellij. |
55,665,395 | I am supposed to solve Problem 25 from Projecteuler. Below is my code, I have no clue, why it is not working.
Can anyone help me?
```
n <- 0
a <- 1
b <- 1
c <- 0
while (nchar(a)<1000)
n <- n+1
c <- b
b <- a
a <- a + c
```
Thanks | 2019/04/13 | [
"https://Stackoverflow.com/questions/55665395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10432814/"
] | Generation of non-repeatable numbers is not an easy task compared to a simple shuffling the array or a collection using [`Collections::shuffle`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#shuffle-java.util.List-).
```
final String[] fruitArray = new String[]{"apple", "orange", "pear", "banana",
"cherry", "blueberry", "papaya", "litchi"};
// SHUFFLE
final List<String> fruitList = Arrays.asList(fruitArray);
Collections.shuffle(fruitList);
// TEST IT
fruitList.stream()
.limit(4) // sets the count to 4
.forEach(System.out::println); // prints qualified random items without repetition
``` | You can use Random() object in java.
Below is an example of getting 3 random elements from an ArrayList hope this help you.
```
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GFG {
// Drive Function
public static void main(String[] args)
{
// create a list of Integer type
List<Integer> list = new ArrayList<>();
// add 5 element in ArrayList
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
GFG obj = new GFG();
// boundIndex for select in sub list
int numberOfElements = 3;
// take a random element from list and print them
System.out.println(obj.getRandomElement(list,
numberOfElements));
}
// Function select an element base on index and return
// an element
public List<Integer> getRandomElement(List<Integer> list,
int totalItems)
{
Random rand = new Random();
// create a temporary list for storing
// selected element
List<Integer> newList = new ArrayList<>();
for (int i = 0; i < totalItems; i++) {
// take a raundom index between 0 to size
// of given List
int randomIndex = rand.nextInt(list.size());
// add element in temporary list
newList.add(list.get(randomIndex));
// Remove selected element from orginal list
list.remove(randomIndex);
}
return newList;
}
}
```
Output:
```
[50, 40, 30]
``` |
55,665,395 | I am supposed to solve Problem 25 from Projecteuler. Below is my code, I have no clue, why it is not working.
Can anyone help me?
```
n <- 0
a <- 1
b <- 1
c <- 0
while (nchar(a)<1000)
n <- n+1
c <- b
b <- a
a <- a + c
```
Thanks | 2019/04/13 | [
"https://Stackoverflow.com/questions/55665395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10432814/"
] | Generation of non-repeatable numbers is not an easy task compared to a simple shuffling the array or a collection using [`Collections::shuffle`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#shuffle-java.util.List-).
```
final String[] fruitArray = new String[]{"apple", "orange", "pear", "banana",
"cherry", "blueberry", "papaya", "litchi"};
// SHUFFLE
final List<String> fruitList = Arrays.asList(fruitArray);
Collections.shuffle(fruitList);
// TEST IT
fruitList.stream()
.limit(4) // sets the count to 4
.forEach(System.out::println); // prints qualified random items without repetition
``` | Create an array of random integers and use them as index for the array
```
int[] indexes = new Random().ints(4, 0, fruitsArray.length).toArray();
for (int i = 0; i < indexes.length; i++) {
System.out.println(fruitsArray[i]);
}
``` |
318,005 | When you actually read what's written in the [Help Center](https://meta.stackexchange.com/help/referencing), it strongly implies that only *answers* need to give attribution (see added emphasis):
>
> Plagiarism - posting the work of others with no indication that it is not your own - is frowned on by our community, and may result in your **answer** being down-voted or deleted.
>
>
> When you find a useful resource that can help **answer** a question (from another site or in an answer on Stack Overflow) make sure you do all of the following
>
>
>
Can this be changed to be more inclusive of questions (and perhaps tag wikis)?
---
My best suggestion:
>
> Plagiarism - posting the work of others with no indication that it is not your own - is frowned on by our community, and may result in your **post** being down-voted or deleted.
>
>
> When you use a resource in your post (e.g. from another site or in an answer on Stack Overflow) make sure you do all of the following
>
>
> | 2018/11/08 | [
"https://meta.stackexchange.com/questions/318005",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/323179/"
] | This was finally changed, though the help page still lives under the "answering" category. To quote (emphasis added):
>
> Plagiarism - posting the work of others with no indication that it is not your own - is frowned on by our community, and may result in your **content** being down-voted or deleted.
>
>
> If you copy (or closely rephrase/reword) content that you did not create into **something you post** on Meta Stack Exchange (e.g. from another site or elsewhere on Meta Stack Exchange) make sure you do all of the following
>
>
>
And since I must reference the author, [shoutout to Catija](https://meta.stackoverflow.com/a/416676/6083675). | I can't imagine any possible reason for disallowing plagiarism in answers but not in questions. Whatever the reasons are for not allowing it in the one should apply equally to the other. It doesn't matter where you post somethingβif it's obvious it's from somebody else, but you haven't provided attribution, then that's not right.
The Help Center article ["How to reference material written by others"](https://meta.stackexchange.com/help/referencing) does indeed refer to answers specifically. I'll note that it seems to located in a section of the Help Center *for* answers (if I go by the navigation breadcrumb of *Meta Stack Exchange > Help center > Answering* at the top of the page), which might explain the specific focus. However, I find it odd that anybody would be interpreting it so strictly that they would only consider it valid policy for answers. The *intent* behind the policy is the same, regardless of where unattributed material is found. However it's handled in answers, it should be handled in the same way in questions.
I know that in the specific sites I follow, people who post quotations in questionsβespecially those that are obviously from another authorβare very frequently asked to provide proper attribution, if not actual links, so that the validity and context of the quotations can be determined. Frequently, at least on those sites, context is quite important, and the simple text itself isn't necessarily sufficient to provide an answer. (Let alone the other issues surrounding plagiarism in general.)
In my opinion, the text should be changed from its reference to answers specifically to a reference to posts in general. Then, it should be linked to from the *Asking* section in addition to the *Answering* sectionβassuming that the Help Center navigation works that way. |
14,884,516 | I have a table formatted like the one below, i want to split it up so theres a column for month and year ie. January 2014 then another column for cost. So effectively each row would be split into 12 different rows, but i cant for the life of me figure out how to approach it. Any help would be greatly appreciated
```
CREATE TABLE dbo.Line14(
ItemID int IDENTITY(1,1) NOT NULL,
Detail nvarchar(max) NULL,
Type nvarchar(255) NULL,
Cat nvarchar(255) NULL,
Jan_14 money NULL,
Feb_14 money NULL,
Mar_14 money NULL,
Apr_14 money NULL,
May_14 money NULL,
Jun_14 money NULL,
Jul_14 money NULL,
Aug_14 money NULL,
Sep_14 money NULL,
Oct_14 money NULL,
Nov_14 money NULL,
Dec_14 money NULL
) ON PRIMARY TEXTIMAGE_ON PRIMARY
GO
``` | 2013/02/14 | [
"https://Stackoverflow.com/questions/14884516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902540/"
] | You should be able to use the [`UNPIVOT`](http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) function which converts the data from columns into rows:
```
select itemid,
detail,
type,
cat,
Month,
2014 as Year,
value
from Line14
unpivot
(
value
for Month in (Jan_14, Feb_14, Mar_14, Apr_14,
May_14, Jun_14, Jul_14, Aug_14,
Sep_14, Oct_14, Nov_14, Dec_14)
) unpiv
```
See [SQL Fiddle with Demo](http://www.sqlfiddle.com/#!6/b4b6a/1).
The result would be similar to this:
```
| ITEMID | DETAIL | TYPE | CAT | MONTH | YEAR | VALUE |
---------------------------------------------------------
| 1 | Test | C | blah | Jan_14 | 2014 | 10 |
| 1 | Test | C | blah | Feb_14 | 2014 | 12 |
| 1 | Test | C | blah | Mar_14 | 2014 | 45 |
| 1 | Test | C | blah | Apr_14 | 2014 | 56 |
| 1 | Test | C | blah | May_14 | 2014 | 89 |
| 1 | Test | C | blah | Jun_14 | 2014 | 78 |
| 1 | Test | C | blah | Jul_14 | 2014 | 96 |
| 1 | Test | C | blah | Aug_14 | 2014 | 35 |
| 1 | Test | C | blah | Sep_14 | 2014 | 55 |
| 1 | Test | C | blah | Oct_14 | 2014 | 30 |
| 1 | Test | C | blah | Nov_14 | 2014 | 99 |
| 1 | Test | C | blah | Dec_14 | 2014 | 120 |
``` | build the new table as you describe - then write 12 `insert as select` statements grabbing each month's money value and hardcoding the month value. |
7,328 | I have a very High resolution image in illustrator, which leads to a very heavy eps file size, I'm asking for a batch tool or a script to compress the eps image , in other words reduce its resolution without affecting the width and height of the image.I don't want to export the image as a separated Jpg file | 2012/05/08 | [
"https://graphicdesign.stackexchange.com/questions/7328",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/4501/"
] | Object > Rasterize and choose a lower resolution setting.
This will embed any linked image, however. | What if you exported the files as PDFs? As part of the process, you can change the resolution of all images in the document. They're scaled so that the positioning is kept in tact.
From there, you could resave as EPS, if required (although I can't think of many situations where a EPS would be required over a PDF?).
Here's how to change the resolution of images as you save as a Illustrator PDF:

To keep the document fully editable in Illustrator, turn on `Preserve Illustrator Editing Capabilities`.

Most things in Illustrator can be Actioned, so depending on your exact requirements, you may be able to reduce some of the repetition.
OS X's Automator can also reduce images in EPS and PDF files, but you don't have any control over how much they're reduced. If that sounds interesting, `Apply Quartz Filter to PDF Documents` is the action is the one you want, because it contains a `Reduce File Size` filter. |
7,328 | I have a very High resolution image in illustrator, which leads to a very heavy eps file size, I'm asking for a batch tool or a script to compress the eps image , in other words reduce its resolution without affecting the width and height of the image.I don't want to export the image as a separated Jpg file | 2012/05/08 | [
"https://graphicdesign.stackexchange.com/questions/7328",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/4501/"
] | Object > Rasterize and choose a lower resolution setting.
This will embed any linked image, however. | Built into Bridge is a handy script called "Image Processor" (`Tools > Photoshop > Image Processor...`). This allows you to select a bunch of images and run them through Photoshop to save PSD, JPEG or PNG copies. You can specify the maximum size (horizontal and vertical) in the dialog.
For even more sophistication and options, you can install some of [Dr. Brown's Services](http://russellbrown.com/scripts.html), which include Image Processor Pro v2.2.8 (scroll down to find it). Russel Brown has a fantastic collection of scripts and other Photoshop add-ons.
To eliminate the problem of slow processing with complex vector files, go with Illustrator CS6, which has the new "Mercury Performance Engine" (works best with NVidia GPUs) and is blindingly fast compared with any previous version. |
24,408,248 | Recently I downloaded qemu, and ran configure, make and make install.
when I run
```
qemu-system-sparc linux-0.2.img
```
I just see a message below
>
> VNC server running on `::1:5900'
>
>
>
At this state, when I open vncviewer window by typing `vncviewer :5900`, then I see the window.
The window shows the emulated screen
>
> Welcome to OpenBIOS v1.1 build on Mar 10 2014 08:41
>
> Type 'help'
> for detailed information
>
> Trying disk...
>
> No valid state has been
> set by load or init-program
>
> 0>
>
>
>
How can I make the vnc window come up automatically? and how do I supply right linux image?
when I build my linux image, I can get sImage.elf or sImage.bin which contains the file system too. | 2014/06/25 | [
"https://Stackoverflow.com/questions/24408248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1511337/"
] | I solved this problem by installing sdl-devel to my CentOS.
I reran ./configure --target-list=sparc-softmmu --enable-sdl
and did make, make install
and the problem is gone! | first
according to what @Chan Kim said, but there is nothing about `qemu-system-i386` and `qemu-system-x86_64` in `qemu/bin`.
then
run `./configure --prefix=/data/local/qemu --target-list=i386-softmmu,arm-softmmu,x86_64-softmmu --disable-vnc --enable-sdl`, then I find all about qemu-system. |
46,877 | I'm trying to enable my polystrips addon but I receive this error every time I try to check the enable addon box.[](https://i.stack.imgur.com/04VOC.png) | 2016/02/13 | [
"https://blender.stackexchange.com/questions/46877",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/21819/"
] | It appears you need to grab the code from here <https://github.com/CGCookie/retopology-lib> and put the source files (ie `__init__.py, common_utilities.py, common_drawing.py, common_classes.py`) into the empty retopology-polystrips-master/lib folder | Most commonly, these kinds of errors have been solved by disabling any old versions of the addon, deleting them from your addons directory, re-installing the addon, saving user preferences and re-starting blender.
best,
Patrick |
336,692 | I'm having a lot of trouble to find lore.
I exhausted the bookstore, the auction, Mansur until the Stag door and the expeditions I could find. Where else can I find lore? | 2018/07/28 | [
"https://gaming.stackexchange.com/questions/336692",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/116230/"
] | This is the way I see to be the quickest path to acquire Lore:
1. Keep buying everything from Morland's Shop. It will keep bringing books to study that will become Lore.
2. When Morland's shop closes, start buying books at Oriflamme's Auction House until it doesn't have any more books to sell. Oriflamme can also be found by a believer **Exploring**.
3. If you **Explore** with Secret Histories Lore, they will convert into Aspect: Location+Vault. Those might bring back more Lore. [Here is](https://steamcommunity.com/sharedfiles/filedetails/?id=1402554171) a comprehensive description and requirements for all expeditions.
4. **Dream** with Passion and in the slot add a Lantern or Knock Lore. It will bring you **Way: The wood**. [This guide](https://www.reddit.com/r/weatherfactory/comments/8ohdsw/a_mostly_comprehensive_guide_to_cultist_simulator/) at *The Mansus* section has a great explanation on how to open each location further and what you will find there. The idea here is to grab all the Secret Histories you can find and transform them into expeditions (as commented above). Expeditions bring a lot of Lore.
5. If you already made/have all the expeditions of a certain level (they start to repeat the location), start to "merge" the same Secret Histories to get advanced levels of them.
6. Some Lore books need to be translated. Some Patrons can translate those books if you pay them with Spintria. Patrons pays their commissions with Spintria or you can get it from expeditions. [You will have to summon](https://cultistsimulator.gamepedia.com/Spirits) Teresa, King Crucible and Ezeem to learn Fucine, Deep Mandaic and Phrygian respectively. | maybe this will help:
>
> Lore Fragments are a resource that can be obtained from studying some books, and some interactions. They can be upgraded by studying it with a fragment same aspect and level(or, for knock fragments, upgraded with any same level fragment except for secret histories). All fragments(except Secret Histories and Knock) can be subverted into another type of lore.
>
>
>
[source](https://cultistsimulator.gamepedia.com/Lore) |
9,561,093 | I have an XML column with this value
```
<sso_links>
<linktype>mytype</linktype>
<url>http://mydomain.com</url>
<linktype>mytype2</linktype>
<url>http://somedomain.com</url>
</sso_links>
```
I've tried using SQL to query this by value but this only returns scalar type
```
SELECT XMLCOLUMN.value('//linktype[1]', varchar(max)),
XMLCOLUMN.value('//url[1]', varchar(max))
from table
where someid = '1'
```
This produced 2 rows from the XML. How can I output all values? | 2012/03/05 | [
"https://Stackoverflow.com/questions/9561093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1248945/"
] | Oftentimes such patterns are evaluated in order, with the first prefix matching being the one chosen.
Try moving your most general regex to the end:
```
application = webapp.WSGIApplication([
('/(\w+)',MainMain)],
('/', MainMain),
debug=True)
``` | ```
>>> url = 'http://example.appspot.com/abc%20asd'
>>> import urllib
>>> import urlparse
>>> urllib.unquote_plus(urlparse.urlparse(url)[2][1:])
'abc asd'
``` |
65,441,773 | Here's the workflow:
Get a https link --> write to filesystem --> read from filesystem --> Get the sha256 hash.
*It works all good on my local machine running node 10.15.3 But when i initiate a lambda function on AWS, the output is null.* Some problem may lie with the readable stream. Here's the code. You can run it directly on your local machine. It will output a sha256 hash as required. If you wish to run on AWS Lambda, Comment/Uncomment as marked.
```
//Reference: https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries
var https = require('https');
var fs = require('fs');
var crypto = require('crypto')
const url = "https://upload.wikimedia.org/wikipedia/commons/a/a8/TEIDE.JPG"
const dest = "/tmp/doc";
let hexData;
async function writeit(){
var file = fs.createWriteStream(dest);
return new Promise((resolve, reject) => {
var responseSent = false;
https.get(url, response => {
response.pipe(file);
file.on('finish', () =>{
file.close(() => {
if(responseSent) return;
responseSent = true;
resolve();
});
});
}).on('error', err => {
if(responseSent) return;
responseSent = true;
reject(err);
});
});
}
const readit = async () => {
await writeit();
var readandhex = fs.createReadStream(dest).pipe(crypto.createHash('sha256').setEncoding('hex'))
try {
readandhex.on('finish', function () { //MAY BE PROBLEM IS HERE.
console.log(this.read())
fs.unlink(dest, () => {});
})
}
catch (err) {
console.log(err);
return err;
}
}
const handler = async() =>{ //Comment this line to run the code on AWS Lambda
//exports.handler = async (event) => { //UNComment this line to run the code on AWS Lambda
try {
hexData = readit();
}
catch (err) {
console.log(err);
return err;
}
return hexData;
};
handler() //Comment this line to run the code on AWS Lambda
``` | 2020/12/24 | [
"https://Stackoverflow.com/questions/65441773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10845323/"
] | I'm not sure why std::map is necessary, but this should do what you want.
```
for (const auto& s : synonyms) {
auto object = s.begin();
if (object->first == word || object->second == word) {
++amount;
}
}
```
Since each element in your set `s` is a map of size 1, you can access its element by using an iterator on its beginning. | ```
for (const std::map<string, string>& m : synonyms)
{
for (const std::pair<string, string>& p : m)
{
if (p->first == word || p->second == word)
{
++amount;
}
}
}
``` |
20,388,634 | I want to print doubles so that the decimals line up. For example:
```
1.2345
12.3456
```
should result in
```
1.2345
12.3456
```
I have looked everywhere, and the top recommendation is to use the following method (the 5s can be anything):
```
printf(%5.5f\n");
```
I have tried this with the following (very) simple program:
```
#include <stdio.h>
int main() {
printf("%10.10f\n", 0.523431);
printf("%10.10f\n", 10.43454);
return 0;
}
```
My output is:
```
0.5234310000
10.4345400000
```
Why doesn't this work? | 2013/12/04 | [
"https://Stackoverflow.com/questions/20388634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813111/"
] | The number before the `.` is minimum characters *total*, not just before the radix point.
```
printf("%21.10f\n", 0.523431);
``` | When you use `"%10.10f"` you are telling `printf()` "use 10 character positions to print the number (optional minus sign, integer part, decimal point and decimal part). From these 10 positions, reserve 10 for decimal part. If this is not possible, ignore the first number and use whatever positions needed to print the number so that the number of decimal positions is kept"
So that's what's `printf()` is doing.
So you need to indicate how many positions you are going to use, for example, 15, and how many positions from these are going to be decimals.... for example, 9. That will leave you with 5 positions for the minus sign and integer part and one position for the decimal point.
That is, try `"%15.9f"` in your printf's |
725,261 | I have a word doc where when you look at the file preview in the Finder window on a mac (osx), it shows the first page and on the upper right corner of the page, theres a Qlikview logo (im guessing Qlikview contributed to the creation of the document). However when you open the document itself, the logo is not there and the document is in the correct/desired formatting.
I've tried
-saving it as a new file
-saving it as a .doc instead of .docx
-converting to google doc then downloading as .docx but the formatting is affected
-changing security settings on MS Word to "remove personal information from this file upon saving"
-checking for water marks/settings
-copy/pasting entire doc onto a new doc and saving
and none of these got rid of the mark.
Anyone know how to fix this or get around it? Or how to disable doc preview for this file only? Any help would be appreciated. Thanks! | 2014/03/06 | [
"https://superuser.com/questions/725261",
"https://superuser.com",
"https://superuser.com/users/305427/"
] | I found this page after having the same issue. Solution:
Click into your header /footer. Click > Different First Page.
The logo and header will come up from an old source.
Delete it, and then unselect Different First Page.
Problem solved! | This is not proper answer using MS Word, but Works.
Open your Document with LibreOffice.org (I have Cent OS 7 in another machine), You will see the "watermark" select it and delete. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.