text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Visual Studio will not recognize addTagHelper in razor file I've used @addTagHelper in previous projects in the _ViewImports for MVC and not had a problem, but now its saying that the name 'addTagHelper' does not exist in current context. This is in a WCF Service Application using MVC.
Any ideas?
A: @Bsharp Sadly TagHelpers are only an ASP.NET Core feature and wont work in non-core versions of MVC.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49801811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to intellisense alias module path in VSCode I would like VSCode to IntelliSense the module path so I can access it by click.
For example, after configurating jsconfig.json I'm able to access ./src/styled/index by importing its global path.
But I couldn't figure out how to make it work with an alias @styles
// VSCode Intellisene Works
import { mixins, theme } from 'styles';
// VSCode Intellisene Doesn't work
import { mixins, theme } from '@styles';
My current jsconfig.json:
{
"compilerOptions": {
"baseUrl": "./",
"jsx": "react",
"paths": {
"@styles": ["src/styles/index"]
}
}
}
A: In the settings.json file, add this line:
"typescript.preferences.importModuleSpecifier": "non-relative"
If this property is removed, then the ugly relative auto-import is the default option. Simply change 'typescript' to 'javascript' if you're currently using JS. To know more about this setting option, just hover on it like this:
(Bonus tip) Prefix @app/ to all import paths with the following compiler options in tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@app/*": ["./*"]
}
},
}
A: Seems I had to restart VSCode.
Javascript (javascript,javascriptreact file types in VSCode)
An example of jsconfig.json file for reference:
{
"compilerOptions": {
"baseUrl": "./src",
"jsx": "react",
"paths": {
"@styles": ["styles/index"],
"@fonts": ["fonts/index"],
"@components": ["components/index"],
"@atoms": ["components/atoms/index"],
"@molecules": ["components/molecules/index"],
"@organisms": ["components/organisms/index"],
"@templates": ["components/templates/index"],
"@icons": ["components/atoms/Icons/index"],
"@config": ["config/index"],
"@utils": ["utils/index"],
"@hooks": ["hooks/index"],
"@constants": ["constants/index"],
"@queries": ["queries/index"],
"@reducers": ["state/store/reducers"],
"@actions": ["state/store/actions"],
"@slices": ["state/slices/"],
"@storybookHelpers": ["../.storybook/helpers"]
}
}
}
An example of how styles/index looks like:
export * from './colors';
export * from './GlobalStyle.styles';
export * from './mixins.styles';
// Or
export { COLORS } from './colors';
export { default as GlobalStyle } from './GlobalStyle.styles';
export { default as mixins } from './mixins.styles';
Will allow import (with IntelliSense):
import { COLORS, mixins, GlobalStyle } from '@styles';
For a bonus: aliases.js, which is a helper which I use to define aliases in webpack config files, it helps to not repeat yourself, for example when using the same aliases in storybook and for the application itself.
// Remember to update `jsconfig.json`
const aliases = (prefix = `src`) => ({
'@actions': `${prefix}/state/store/actions`,
'@atoms': `${prefix}/components/atoms`,
'@molecules': `${prefix}/components/molecules`,
'@organisms': `${prefix}/components/organisms`,
'@templates': `${prefix}/components/templates`,
'@components': `${prefix}/components`,
'@config': `${prefix}/config`,
'@constants': `${prefix}/constants`,
'@hooks': `${prefix}/hooks`,
'@icons': `${prefix}/components/atoms/Icons`,
'@queries': `${prefix}/queries`,
'@reducers': `${prefix}/state/store/reducers`,
'@slices': `${prefix}/state/slices`,
'@styles': `${prefix}/styles`,
'@utils': `${prefix}/utils`,
'@storybookHelpers': `../.storybook/helpers`,
});
module.exports = aliases;
// usage example at .storybook/webpack.config.js file
const path = require("path");
const alias = require(`../src/config/aliases`);
const SRC = "../src";
const aliases = alias(SRC);
const resolvedAliases = Object.fromEntries(
Object.entries(aliases).map(([key, value]) => [
key,
path.resolve(__dirname, value),
])
);
module.exports = ({ config }) => {
config.resolve.modules.push(path.resolve(__dirname, SRC));
config.resolve.alias = resolvedAliases;
return config;
};
Typescript (typescript,typescriptreact files)
At tsconfig.json use the compilerOptions.paths option, notice that the paths are relative to baseUrl:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@components/*": ["components/*"],
"@config": ["config"],
"@constants": ["constants"],
"@hooks": ["hooks"],
"@styles": ["styles"],
"$types/*": ["types/*"],
"@utils": ["utils"]
}
}
This allows aliases (with IntelliSense), for example:
// Example of hooks/index.ts file
export * from './useLogin';
export * from './useLocalStorage';
export * from './useAuth';
// Usage examples
import {ROUTES} from '@constants';
import {Text} from '@components/atoms';
import {mixins} from '@styles';
import {useLocalStorage} from '@hooks';
A: I had the right configuration as described by the other answers. In VS code I restarted the TypeScript server using Ctrl + Shift + P -> TypeScript: Restart TS server command and it fixed the editor highlighting the import path error.
Just for completeness here is what my tsconfig.json looks like:
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src/**/*"]
}
A: As a side note, make sure the include in your jsconfig/tsconfig is pointing to correct paths.
A: For anyone like me who the other answers aren't working for, these are the tsconfig bits that worked for me, in addition to the settings addition in the accepted answer and ensuring you're setting includes/excludes properly:
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
}
}
Full credit to this gist: https://gist.github.com/EmilyRosina/eef3aa0d66568754a98382121fefa154
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58249053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Loop through an XML object with SimpleXML I am trying to use SimpleXML in PHP to loop through a XML object - the object format is below:-
I get the following error when I try to get the element tags by name - can anyone explain what I am doing wrong?
Call to undefined method SimpleXMLElement::getElementsByTagName() on ...
Below is the XML file I am reading from:
<?xml version="1.0" encoding="utf-8"?>
<response>
<products>
<item>
<product_id>32417</product_id>
<manufacturer>Alcatel</manufacturer>
<model>Sparq 2</model>
<deeplink>http://www.mysite.com/sc_offer?gid=32417</deeplink>
<thumbnail_URL>http://www.mysite.com/images/devices/thumbs/Alcatel-Sparq-II.jpg</thumbnail_URL>
<image_URL>http://www.mysite.com/images/devices/Alcatel-Sparq-II.jpg</image_URL>
<price_not_working>0.00</price_not_working>
<price_poor>0.00</price_poor>
<price_fair>20.00</price_fair>
<price_good>25.00</price_good>
<price_perfect>25.00</price_perfect>
<price_new>25.00</price_new>
<battery_new>1.00</battery_new>
<battery_perfect>1.00</battery_perfect>
<battery_good>1.00</battery_good>
<battery_fair>1.00</battery_fair>
<battery_poor>0.00</battery_poor>
<charger_new>1.00</charger_new>
<charger_perfect>1.00</charger_perfect>
<charger_good>1.00</charger_good>
<charger_fair>1.00</charger_fair>
<charger_poor>0.00</charger_poor>
<packaging_new>1.00</packaging_new>
<packaging_perfect>1.00</packaging_perfect>
<packaging_good>1.00</packaging_good>
<packaging_fair>1.00</packaging_fair>
<packaging_poor>0.00</packaging_poor>
</item>
<item>
<product_id>31303</product_id>
<manufacturer>Apple</manufacturer>
<model>iPhone 3G 8gb</model>
<deeplink>http://www.mysite.com/sc_offer?gid=31303</deeplink>
<thumbnail_URL>http://www.mysite.com/images/devices/thumbs/iPhone 8 3G.jpg</thumbnail_URL>
<image_URL>http://www.mysite.com/images/devices/iPhone 8 3G.jpg</image_URL>
<price_not_working>0.00</price_not_working>
<price_poor>0.00</price_poor>
<price_fair>7.00</price_fair>
<price_good>2.00</price_good>
<price_perfect>2.00</price_perfect>
<price_new>2.00</price_new>
<battery_new>1.00</battery_new>
<battery_perfect>1.00</battery_perfect>
<battery_good>1.00</battery_good>
<battery_fair>1.00</battery_fair>
<battery_poor>0.00</battery_poor>
<charger_new>1.00</charger_new>
<charger_perfect>1.00</charger_perfect>
<charger_good>1.00</charger_good>
<charger_fair>1.00</charger_fair>
<charger_poor>0.00</charger_poor>
<packaging_new>1.00</packaging_new>
<packaging_perfect>1.00</packaging_perfect>
<packaging_good>1.00</packaging_good>
<packaging_fair>1.00</packaging_fair>
<packaging_poor>0.00</packaging_poor>
</item>
</products>
</response>
My PHP code is below:
$devices = $xml->getElementsByTagName( "response" ); // error on this line
I am trying to make devices an array so I can use the data in a foreach loop.
A: SimpleXML doesn't have a getElementsByTagName() method (DOMDocument does).
In SimpleXML, the object (e.g $xml) is treated as the root element. So you can loop through the product items like so:
$xml = simplexml_load_string($xmlString);
foreach($xml->products->item as $item)
{
echo (string)$item->product_id;
echo (string)$item->model;
}
Example of building a devices associative array:
$devices = array();
$xml = simplexml_load_string($xmlString);
foreach($xml->products->item as $item)
{
$device = array();
foreach($item as $key => $value)
{
$device[(string)$key] = (string)$value;
}
$devices[] = $device;
}
print_r($devices);
Outputs:
Array
(
[0] => Array
(
[product_id] => 32417
[manufacturer] => Alcatel
[model] => Sparq 2
[deeplink] => http://www.mysite.com/sc_offer?gid=32417
[thumbnail_URL] => http://www.mysite.com/images/devices/thumbs/Alcatel-Sparq-II.jpg
[image_URL] => http://www.mysite.com/images/devices/Alcatel-Sparq-II.jpg
[price_not_working] => 0.00
[price_poor] => 0.00
[price_fair] => 20.00
[price_good] => 25.00
[price_perfect] => 25.00
[price_new] => 25.00
[battery_new] => 1.00
[battery_perfect] => 1.00
[battery_good] => 1.00
[battery_fair] => 1.00
[battery_poor] => 0.00
[charger_new] => 1.00
[charger_perfect] => 1.00
[charger_good] => 1.00
[charger_fair] => 1.00
[charger_poor] => 0.00
[packaging_new] => 1.00
[packaging_perfect] => 1.00
[packaging_good] => 1.00
[packaging_fair] => 1.00
[packaging_poor] => 0.00
)
[1] => Array
(
[product_id] => 31303
[manufacturer] => Apple
[model] => iPhone 3G 8gb
[deeplink] => http://www.mysite.com/sc_offer?gid=31303
[thumbnail_URL] => http://www.mysite.com/images/devices/thumbs/iPhone 8 3G.jpg
[image_URL] => http://www.mysite.com/images/devices/iPhone 8 3G.jpg
[price_not_working] => 0.00
[price_poor] => 0.00
[price_fair] => 7.00
[price_good] => 2.00
[price_perfect] => 2.00
[price_new] => 2.00
[battery_new] => 1.00
[battery_perfect] => 1.00
[battery_good] => 1.00
[battery_fair] => 1.00
[battery_poor] => 0.00
[charger_new] => 1.00
[charger_perfect] => 1.00
[charger_good] => 1.00
[charger_fair] => 1.00
[charger_poor] => 0.00
[packaging_new] => 1.00
[packaging_perfect] => 1.00
[packaging_good] => 1.00
[packaging_fair] => 1.00
[packaging_poor] => 0.00
)
)
A: I don't want to spoil the existing answer as it is answering correct an in a general fashion.
For your concrete requirements as with your XML there aren't any attributes and you're just looking for the element-name => node-value pairs here, there is one function that comes to mind in conjunction with SimpleXMLElement here: get_object_vars.
It is useful whenever you convert an object into an array and as SimpleXMLElement turns element names into object property names and the node-values as those property values it's pretty straight forward here:
$xml = simplexml_load_string($buffer);
$items = $xml->products->item;
$devices = array_map('get_object_vars', iterator_to_array($items, FALSE));
print_r($devices);
The output is as suggested in the existing answer. And the online demo is here: https://3v4l.org/iQKQP
You will likely able to achieve similar results with casting to arrays (if not exactly the same with SimpleXML), however in this case as I wanted to map it, I needed a true function.
There is also the json-en- and -de-code doubling for converting complete trees, which comes in handy here, too:
$xml = simplexml_load_string($buffer);
$items = $xml->products;
$devices = json_decode(json_encode($items), TRUE)['item'];
The output then again is exactly as the existing answer. And the online demo again is here: https://3v4l.org/ToWOs
Hope this is helpful and widens the view a bit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19561657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How should one make a class with dependencies unit testable without bloat? So I have a class (part of a library) that facilitates two-way TCP communication. Part of that is accepting incoming connections.
My implementation consists of using a TCPListener object and a multithreaded method to accept connections. To make it testable, I decided to instead create an "INetworkListener" interface, which contains only a single event, "OnClientAccepted". This way, I can use dependency injection to mock a fake version of TCPListener and avoid multithreaded unit tests.
The problem is that I need a way to test the class using a fake INetworkListener, but I want my users to not have the option to use other implementations of this interface.
Here is some stripped down sample code:
class TcpMessenger
{
// Various properties
private INetworkListener _tcpListener;
public TcpMessenger(int port, string friendlyName) // This is the ONLY constructor I want available to users
{
ServerPort = port;
FriendlyName = friendlyName;
_isRunning = false;
_tcpListener = new ConcreteExample(port); // This prevents unit testing because it opens threads and such
}
public TcpMessenger(int port, string friendlyName, INetworkListener listener) // I need this to test
{
ServerPort = port;
FriendlyName = friendlyName;
_isRunning = false;
_tcpListener = listener; // No dependency here :)
}
}
Why can't I just leave both constructors?
My library acts as sort of a facade. It makes TCP communication easier, but doesn't add much functionality. Therefore, my target audience would never need to inject that dependency. And if I don't want them to do it, then proper design tells me to enforce it.
Why not just test it as a public-facing API? Integration Testing!
I actually did this with a previous version of my library, which was extremely coupled. The results were terrible. I had a dozen tests that involved multiple threads, and worse, actual sockets. Unit tests shouldn't be dependent on outside factors like that.
Do you really need to test this?
Yes. This library has high-level functionality, such as exception handling, error reporting, failsafes for connection issues, and algorithms to maintain two-way connections (meaning each node is a client and server). This functionality can be tested without opening actual sockets, so I definitely want that.
I also want the unit tests to be public. Meaning anyone can grab the source, run them, and see all the green check marks.
Concluding Question:
How do I test two classes independently, while simultaneously forcing dependencies in real-world scenarios?
A: You can make your constructor internal and expose your internals to your tests using InternalsVisibleTo:
[assembly: InternalsVisibleTo("YourNamespace.YourTests")]
See: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44992101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to add tap gesture on each segment of a Piechart using UIGraphicsGetCurrentContext arc I am trying to create a Piechart using UIGraphicsGetCurrentContext for drawing, I want to add tap gesture on the piechart to recognize if the tap point inside each segment. Please find the code below for drawing Piechart and the ViewController where the clas . is used,
PiechartView.swift
import UIKit
private extension CGFloat {
/// Formats the CGFloat to a maximum of 1 decimal place.
var formattedToOneDecimalPlace : String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 1
return formatter.string(from: NSNumber(value: self.native)) ?? "\(self)"
}
}
/// Defines a segment of the pie chart
struct Segment {
/// The color of the segment
var color : UIColor
/// The name of the segment
var name : String
/// The value of the segment
var value : CGFloat
}
class PieChartView: UIView {
/// An array of structs representing the segments of the pie chart
var segments = [Segment]() {
didSet { setNeedsDisplay() } // re-draw view when the values get set
}
/// Defines whether the segment labels should be shown when drawing the pie chart
var showSegmentLabels = true {
didSet { setNeedsDisplay() }
}
/// Defines whether the segment labels will show the value of the segment in brackets
var showSegmentValueInLabel = false {
didSet { setNeedsDisplay() }
}
/// The font to be used on the segment labels
var segmentLabelFont = UIFont.systemFont(ofSize: 20) {
didSet {
textAttributes[NSFontAttributeName] = segmentLabelFont
setNeedsDisplay()
}
}
private let paragraphStyle : NSParagraphStyle = {
var p = NSMutableParagraphStyle()
p.alignment = .center
return p.copy() as! NSParagraphStyle
}()
private lazy var textAttributes : [String : Any] = {
return [NSParagraphStyleAttributeName : self.paragraphStyle, NSFontAttributeName : self.segmentLabelFont]
}()
override init(frame: CGRect) {
super.init(frame: frame)
isOpaque = false // when overriding drawRect, you must specify this to maintain transparency.
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
// get current context
let ctx = UIGraphicsGetCurrentContext()
// radius is the half the frame's width or height (whichever is smallest)
let radius = min(frame.width, frame.height) * 0.5
// center of the view
let viewCenter = CGPoint(x: bounds.size.width * 0.5, y: bounds.size.height * 0.5)
// enumerate the total value of the segments by using reduce to sum them
let valueCount = segments.reduce(0, {$0 + $1.value})
// the starting angle is -90 degrees (top of the circle, as the context is flipped). By default, 0 is the right hand side of the circle, with the positive angle being in an anti-clockwise direction (same as a unit circle in maths).
var startAngle = -CGFloat.pi * 0.5
// loop through the values array
for segment in segments {
// set fill color to the segment color
ctx?.setFillColor(segment.color.cgColor)
// update the end angle of the segment
let endAngle = startAngle + .pi * 2 * (segment.value / valueCount)
// move to the center of the pie chart
ctx?.move(to: viewCenter)
// add arc from the center for each segment (anticlockwise is specified for the arc, but as the view flips the context, it will produce a clockwise arc)
ctx?.addArc(center: viewCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
// fill segment
ctx?.fillPath()
if showSegmentLabels { // do text rendering
// get the angle midpoint
let halfAngle = startAngle + (endAngle - startAngle) * 0.5;
// the ratio of how far away from the center of the pie chart the text will appear
let textPositionValue : CGFloat = 0.67
// get the 'center' of the segment. It's slightly biased to the outer edge, as it's wider.
let segmentCenter = CGPoint(x: viewCenter.x + radius * textPositionValue * cos(halfAngle), y: viewCenter.y + radius * textPositionValue * sin(halfAngle))
// text to render – the segment value is formatted to 1dp if needed to be displayed.
let textToRender = showSegmentValueInLabel ? "\(segment.name) (\(segment.value.formattedToOneDecimalPlace))" : segment.name
// get the color components of the segement color
guard let colorComponents = segment.color.cgColor.components else { return }
// get the average brightness of the color
let averageRGB = (colorComponents[0] + colorComponents[1] + colorComponents[2]) / 3
// if too light, use black. If too dark, use white
textAttributes[NSForegroundColorAttributeName] = (averageRGB > 0.7) ? UIColor.black : UIColor.white
// the bounds that the text will occupy
var renderRect = CGRect(origin: .zero, size: textToRender.size(attributes: textAttributes))
// center the origin of the rect
renderRect.origin = CGPoint(x: segmentCenter.x - renderRect.size.width * 0.5, y: segmentCenter.y - renderRect.size.height * 0.5)
// draw text in the rect, with the given attributes
textToRender.draw(in: renderRect, withAttributes: textAttributes)
}
// update starting angle of the next segment to the ending angle of this segment
startAngle = endAngle
}
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
let pieChartView = PieChartView()
override func viewDidLoad() {
super.viewDidLoad()
pieChartView.frame = CGRect(x: 0, y: 40, width: UIScreen.main.bounds.size.width, height: 400)
pieChartView.segments = [
Segment(color: UIColor(red: 1.0, green: 31.0/255.0, blue: 73.0/255.0, alpha: 1.0), name:"Red", value: 57.56),
Segment(color: UIColor(red:1.0, green: 138.0/255.0, blue: 0.0, alpha: 1.0), name: "Orange", value: 30),
Segment(color: UIColor(red: 122.0/255.0, green: 108.0/255.0, blue: 1.0, alpha: 1.0), name: "Purple", value: 27),
Segment(color: UIColor(red: 0.0, green: 222.0/255.0, blue: 1.0, alpha: 1.0), name: "Light Blue", value: 40),
Segment(color: UIColor(red: 100.0/255.0, green: 241.0/255.0, blue: 183.0/255.0, alpha: 1.0), name: "Green", value: 25),
Segment(color: UIColor(red: 0.0, green: 100.0/255.0, blue: 1.0, alpha: 1.0), name: "Blue", value: 38)
]
pieChartView.segmentLabelFont = UIFont.systemFont(ofSize: 18)
pieChartView.showSegmentValueInLabel = true
view.addSubview(pieChartView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Please let me know how do I add tap gesture on each segment. Thanks in advance.
A: Found a solution at https://github.com/dilipajm/piechart
Though it's in Objective C but we can try to do the same with swift too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50307641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: std::stoul not throwing std::out_of_range Consider following code:
#include <iostream>
#include <cstring>
#include <cerrno>
int main() {
unsigned long num = strtoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", NULL, 16);
std::cout << std::strerror(errno) << "\n";
unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF");
std::stoul("hello world");
return 0;
}
This code is expected to print some "Out of range" from strerror and then to throw out_of_range exception according to documentation. It should never reach the last stoul line.
In practice, it does not throw on the second stoul statement. I have tried GCC 4.8.5 and MinGW 8.2.0, both failed to throw the out_of_range exception and only delivered invalid_argument on the last stoul statement.
Is this a bug that should be reported or am I missing something and this is expected behaviour?
A: Default base for std::stoul is 10.
stoul reads 0, x is invalid so the rest of the string is ignored and numeric value 0 is returned.
Use similar syntax as in strtoul:
unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", nullptr, 16);
Or with automatic deduction of numeric base:
unsigned long num2 = std::stoul("0xFFFFFFFFFFFF11223344556677889900AABBCCDDEEFF", nullptr, 0);
Both of the above versions will throw. See it online!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56649437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I change the text of a label after clicking a button using GtkAda I have this code which has 1 label and 3 buttons. What I want is to change the text of the label if I press a certain button. If I click the first button the label text will change to "Hello" and if I click the second button the label text will change to "World" and lastly if I click the third button the label text should become "Hello World".
with Gdk.Event; use Gdk.Event;
with Gtk.Box; use Gtk.Box;
with Gtk.Label; use Gtk.Label;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Main;
with Gtk.Window; use Gtk.Window;
with Gtk.Button; use Gtk.Button;
with Gtk.Grid; use Gtk.Grid;
procedure Main is
Win : Gtk_Window;
Label : Gtk_Label;
Box : Gtk_Vbox;
Button: Gtk_Button;
Button2: Gtk_Button;
Button3: Gtk_Button;
Grid : Gtk_Grid;
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean;
---------------------
-- Delete_Event_Cb --
---------------------
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean
is
pragma Unreferenced (Self, Event);
begin
Gtk.Main.Main_Quit;
return True;
end Delete_Event_Cb;
begin
-- Initialize GtkAda.
Gtk.Main.Init;
-- Create a window with a size of 100x120
Gtk_New (Win);
Win.Set_Default_Size (100, 120);
-- Create a box to organize vertically the contents of the window
Gtk_New_Vbox (Box);
Win.Add (Box);
-- Add a label
Gtk_New (Label, "Hello world.");
Box.Add (Label);
-- Add a Grid
Gtk_New (Grid);
Box.Add (Grid);
-- Add the first button to the grid
Gtk_New (Button, "Hello");
Grid.Attach (Button, 0, 0, 1, 1);
-- Add Second button to the grid
Gtk_New (Button2, "World");
Grid.Attach (Button2, 1, 0, 1, 1);
-- Add the third button to the grid
Gtk_New (Button3, "Hello World!");
Grid.Attach (Button3, 0, 1, 2, 1);
-- Stop the Gtk process when closing the window
Win.On_Delete_Event (Delete_Event_Cb'Unrestricted_Access);
-- Show the window and present it
Win.Show_All;
Win.Present;
-- Start the Gtk+ main loop
Gtk.Main.Main;
end Main;
What should I add to make that happen?
A: @thindil gave me an idea on how to change the label text using the set_text procedure, however whenever I run his code this message always shows: "subprogram must not be deeper than access type".
Instead of getting a nested procedure, I created a new package. Here's the updated code:
main.adb
with Gdk.Event; use Gdk.Event;
with Gtk.Box; use Gtk.Box;
with Gtk.Label; use Gtk.Label;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Main;
with Gtk.Window; use Gtk.Window;
with Gtk.Button; use Gtk.Button;
with button_click; use button_click;
procedure Main is
Win : Gtk_Window;
Box : Gtk_Vbox;
Box2 : Gtk_Vbox;
Box3 : Gtk_Hbox;
Box4 : Gtk_Hbox;
Box5 : Gtk_Hbox;
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean;
---------------------
-- Delete_Event_Cb --
---------------------
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean
is
pragma Unreferenced (Self, Event);
begin
Gtk.Main.Main_Quit;
return True;
end Delete_Event_Cb;
begin
-- Initialize GtkAda.
Gtk.Main.Init;
-- Create a window with a size of 400x400
Gtk_New (Win);
Win.Set_Default_Size (400, 400);
-- Create a box to organize vertically the contents of the window
Gtk_New_Vbox (Box);
Win.Add (Box);
-- Add a label inside Vbox Box
Gtk_New (button_click.Label, "Try Pressing the buttons :)");
Box.Add (button_click.Label);
-- Adding Vbox Box2 inside Box
Gtk_New_Vbox (Box2);
Box.Add (Box2);
-- Adding Hbox Box3 inside Box2
Gtk_New_Hbox (Box3);
Box2.Add (Box3);
-- Adding Hbox Box4 inside Vbox Box3
Gtk_New_Hbox (Box4);
Box3.Add (Box4);
-- Adding Hbox Box5 inside Vbox Box3
Gtk_New_Hbox (Box5);
Box3.Add (Box5);
-- Placing Button inside Hbox Box3
Gtk_New (button_click.Button, "Hello");
Box4.Add (button_click.Button);
On_Clicked(button_click.Button, button_clicked'Access);
-- Placing Button2 inside Hbox Box4
Gtk_New (button_click.Button2, "World");
Box5.Add (button_click.Button2);
On_Clicked(button_click.Button2, button_clicked'Access);
-- Placing Button3 inside Vbox Box2
Gtk_New (button_click.Button3, "Hello World");
Box2.Add (button_click.Button3);
On_Clicked(button_click.Button3, button_clicked'Access);
-- Stop the Gtk process when closing the window
Win.On_Delete_Event (Delete_Event_Cb'Unrestricted_Access);
-- Show the window and present it
Win.Show_All;
Win.Present;
-- Start the Gtk+ main loop
Gtk.Main.Main;
end Main;
button_click.ads
with Gtk.Button; use Gtk.Button;
with Gtk.Label; use Gtk.Label;
package button_click is
Button: Gtk_Button;
Button2: Gtk_Button;
Button3: Gtk_Button;
Label : Gtk_Label;
procedure button_clicked (Self : access Gtk_Button_Record'Class);
end button_click;
button_click.adb
with Gtk.Button; use Gtk.Button;
with Gtk.Label; use Gtk.Label;
package body button_click is
procedure button_clicked (Self : access Gtk_Button_Record'Class) is
begin
if Self = Button then
Set_Text(Label, "Hello");
elsif Self = Button2 then
Set_Text(Label, "World");
else
Set_Text(Label, "Hello World");
end if;
end button_clicked;
end button_click;
A: You have to add a callback to buttons to modify the label, in a very similar way like it is done in GTK. I didn't use GTKAda by some time, but it should work:
with Gdk.Event; use Gdk.Event;
with Gtk.Box; use Gtk.Box;
with Gtk.Label; use Gtk.Label;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Main;
with Gtk.Window; use Gtk.Window;
with Gtk.Button; use Gtk.Button;
with Gtk.Grid; use Gtk.Grid;
procedure Main is
Win : Gtk_Window;
Label : Gtk_Label;
Box : Gtk_Vbox;
Button: Gtk_Button;
Button2: Gtk_Button;
Button3: Gtk_Button;
Grid : Gtk_Grid;
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean;
---------------------
-- Delete_Event_Cb --
---------------------
function Delete_Event_Cb
(Self : access Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event)
return Boolean
is
pragma Unreferenced (Self, Event);
begin
Gtk.Main.Main_Quit;
return True;
end Delete_Event_Cb;
-- Callback to update label when buttons were clicked
procedure Update_Label(Self : access Gtk_Button_Record'Class) is
begin
if Self = Button then
Set_Text(Label, "Hello");
elsif Self = Button2 then
Set_Text(Label, "World");
else
Set_Text(Label, "Hello World");
end if;
end Update_Label;
begin
-- Initialize GtkAda.
Gtk.Main.Init;
-- Create a window with a size of 100x120
Gtk_New (Win);
Win.Set_Default_Size (100, 120);
-- Create a box to organize vertically the contents of the window
Gtk_New_Vbox (Box);
Win.Add (Box);
-- Add a label
Gtk_New (Label, "Hello world.");
Box.Add (Label);
-- Add a Grid
Gtk_New (Grid);
Box.Add (Grid);
-- Add the first button to the grid
Gtk_New (Button, "Hello");
-- Attach the callback to the button's event On_Click
On_Clicked(Button, Update_Label'Access);
Grid.Attach (Button, 0, 0, 1, 1);
-- Add Second button to the grid
Gtk_New (Button2, "World");
-- Attach the callback to the second button's event On_Click
On_Clicked(Button2, Update_Label'Access);
Grid.Attach (Button2, 1, 0, 1, 1);
-- Add the third button to the grid
Gtk_New (Button3, "Hello World!");
-- Attach the callback to the third button's event On_Click
On_Clicked(Button3, Update_Label'Access);
Grid.Attach (Button3, 0, 1, 2, 1);
-- Stop the Gtk process when closing the window
Win.On_Delete_Event (Delete_Event_Cb'Unrestricted_Access);
-- Show the window and present it
Win.Show_All;
Win.Present;
-- Start the Gtk+ main loop
Gtk.Main.Main;
end Main;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66953035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python - write headers to csv Currently i am writing query in python which export data from oracle dbo to .csv file. I am not sure how to write headers within file.
try:
connection = cx_Oracle.connect('user','pass','tns_name')
cursor = connection.cursor()
print "connected"
try:
query = """select * from """ .format(line_name)
tmp = cursor.execute(query)
results = tmp.fetchall()
except:
pass
except:
print IOError
filename='{0}.csv'.format(line_name)
csv_file = open(filename,'wb')
if results:
myFile = csv.writer(csv_file)
myFile.writerows(results)
else:
print "null"
csv_file.close()
A: you can ethier do this after executing your query:
columns = [i[0] for i in cursor.description]
so you get
query = """select * from """ .format(line_name)
tmp = cursor.execute(query)
columns = [i[0] for i in cursor.description]
results = tmp.fetchall()
and then do:
if results:
myFile = csv.writer(csv_file)
myFile.writerow(columns)
myFile.writerows(results)
or you can convert result to a dictionary and use DictWriter witch accepts fieldnames
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32536873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: reply to call back query in telepot I have created inline keyboard and am trying to answer the callback query with a message. The terminal is recieving the query but i do not know the correct syntax for replying to it with messages and ultimately photos and other things.
I sometimes get a telegram error 400. After googling they said i should confirm my token in conf.py and i have done that
import sys
import time
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
from telepot.delegate import (
per_chat_id, create_open, pave_event_space, include_callback_query_chat_id)
def on_chat_message(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == 'text':
if msg['text'] == '/start':
bot.sendMessage(chat_id, 'Welcome to @UK_Cali Teleshop\n Created by JonSnow 2021',reply_markup = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="Feedback",callback_data='a'), InlineKeyboardButton(text="You",callback_data='b'),InlineKeyboardButton(text="PGP",callback_data='c'), InlineKeyboardButton(text="Cunt",callback_data='d')],
[InlineKeyboardButton(text="Products",callback_data='e')]
]
))
def on_callback_query(msg):
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
print('Callback Query:', query_id, from_id, query_data)
if query_data == 'a':
bot.answerCallbackQuery(query_id, text='Welcome to @UK_Cali Teleshop')
bot = telepot.Bot('1646167995:AAGsOwfjcryYYkoah69QJ6XGA7koUywmuRk')
MessageLoop(bot, {'chat': on_chat_message,
'callback_query': on_callback_query}).run_as_thread()
print('Listening ...')
while 1:
time.sleep(10)
A: to reply to a callback query with a msg, photo, audio, video document you have to do:
import time
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
TOKEN = "super secret bot token"
def on_chat_message(msg):
#here you handel messages and create the iniline keyboard
content_type, chat_type, chat_id = telepot.glance(msg)
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='button text', callback_data='callback query data for reconizing it')],
])
def on_callback_query(msg):
#here you handels callback querys,
#the event that are fired when user clickan inline keyboard'sbutton
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
#do something HERE based on the callback query to reply,
#to recognize the button pressed check query_data,
#that corresponds to he callback_data setted when creating the button
#to send text messages:
bot.sendMessage(chat_id, "your test message")
#to send photo:
bot.sendPhoto(chat_id, "C:/path/to/your/photo or https://link.to/your/photo")
#to send video:
bot.sendPhoto(chat_id, "C:/path/to/your/video or https://link.to/your/video")
#to send audio:
bot.sendPhoto(chat_id, "C:/path/to/your/audio or https://link.to/your/audio")
#to send document:
bot.sendPhoto(chat_id, "C:/path/to/your/document or https://link.to/your/document")
#please note that you can do the exactly above thing
#in the on_chat_message to reply to a txt message
#ans that in any case you can use if...else statement to make the
#reply different by the msg/inline button pressed
bot = telepot.Bot(TOKEN)
MessageLoop(bot, {'chat': on_chat_message,
'callback_query': on_callback_query}).run_as_thread()
while True:
time.sleep(10)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66424794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: R Tidy method for creating factor variable based on multiple conditions I have a dataset like this:
Gender<-c("Male","Female","Male","Male","Female")
PlaceA<-c("","","","1600","")
PlaceB<-c("","200","211","326","")
PlaceC<-c("1111","2222","","","45")
PlaceD<-c("1000","","","1600","210")
DF<-tibble(Gender,PlaceA,PlaceB,PlaceC,PlaceD)
I'd like to create a new variable that is categorical, and based on several rules about the "place_" variables.
For example:
This new variable could be called "category" and would behave like so:
*
*If there is ANYTHING in "PlaceA", this new "category" variable would be "First"
*If they only have values in PlaceC and PlaceD, they are "Second"
*If they only have values in PlaceB they are "Third"
*If there is a larger number in Place C than PlaceB they are "Fourth"
*There will be a few more rules like that
*If they didn't fit any of the other rules they are "last"
*In the real data there shouldn't be overlap between cases fitting two different scenarios, but if there is I can deal with that later.
Any ideas? If there was never overlap I'd think gather and spread, but since there will be times where there are values in both, or I am comparing numbers to each other, I was at a loss.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62521731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multiple Verifications on Mysql ExpressJS NodeJS I'm new in NodeJS and i'm working on ExpressJS in an API for use it with angular2
I have the next problem: I need do checks in db (mysql) before make an insert and can handle the errors correctly... my ugly code is:
http://pastebin.com/iuBMhUeb
And it doesn't work, becouse it execute the insert ignoring the verify(s) ...
Any help or suggestion will be appreciated
A: Welcome to Asynchronous Javascript, friend!
All your connection.query methods are actually running at the same time, because they are asynchronous functions. This is something you're going to have to get used to, along with callbacks. As a result, none of your "check" queries have actually finished before the "insert" queries begin.
You will have to define the precise order which your functions have to follow, and then use the Async library accordingly (look for Async.series, Async.parallel and Async.waterfall).
Asynchronous JS can be tough to grasp at first, but can do wonders on your response time once you get the hang of it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40557698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FastAPI DB dependency get_repo as a generic fucntion I am trying to find out if it is possible to use the FastAPI dependency injection commonly used to get repository instances as a generic callable, rather than having to get every repo independently in the router and then passing them through to services used later on.
An example of how it is currently done:
Dependencies
from app.db.repositories.base import BaseRepository
def get_database(request: Request) -> Database:
return request.app.state._db
def get_repository(Repo_type: Type[BaseRepository]) -> Callable:
def get_repo(db: Database = Depends(get_database)) -> Type[BaseRepository]:
return Repo_type(db)
return get_repo
Router
@router.get("/", response_model=List[TodoPublic], name="todo:get-all-todos")
async def get_all_todos(
todos_repo: TodoRepository = Depends(get_repository(TodoRepository))
) -> List[TodoPublic]:
return await todos_repo.get_all_todos()
What would be ideal is to be able to pass a generic get_repo object through into a service and within that service be able to get any repo that i need
example
Router
@router.get("/", response_model=List[TodoPublic], name="todo:get-all-todos")
async def get_all_todos(
get_repo = Depends(get_repository())
) -> List[TodoPublic]:
return await app.services.todo_service.get_todos(get_repo)
Service
async def get_all_todos(get_repository) -> List[TodoPublic]:
todos_repo: TodoRepository = get_repository(TodoRepository)
return await todos_repo.get_all_todos()
This is a bad example because there is only 1 repo needed, but if i were dependent on many repos, i would have to get them all in the router and pass each one through to the service, rather than just passing the single get_repo callable into the service and handling it in the service.
Thanks in advance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74627871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php ews, get sent items more info I use jamesiarmes/php-ews to connect with Exchange server to get an email list.
$ews = new ExchangeWebServices('[host]', '[username]', '[password]');
$request = new EWSType_FindItemType();
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;
$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::SENT_ITEMS;
// sort order
$request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();
// sorts mails so that oldest appear first
// more field uri definitions can be found from types.xsd (look for UnindexedFieldURIType)
$order->FieldURI->FieldURI = 'item:DateTimeReceived';
$order->Order = 'Ascending';
$request->SortOrder->FieldOrder[] = $order;
$response = $ews->FindItem($request);
echo '<pre>'.print_r($response, true).'</pre>';
I'd like to get sent items:
EWSType_DistinguishedFolderIdNameType::SENT_ITEMS;
This script prints
[0] => stdClass Object
(
[ItemId] => stdClass Object
(
[Id] => AQAeAGptYXJzY2hhbGwAQGdyb3VwLm1va2F0ZS5jb20ucGwARgAAA9S15wLis8lApRvdnAdC+XoHAC51TyudPmVDoXWXKV00MAYAAAIBCgAAAC51TyudPmVDoXWXKV00MAYAAAIedwAAAA==
[ChangeKey] => CQAAABYAAAAudU8rnT5lQ6F1lyldNDAGAAAAAB6h
)
[Subject] => test
[Sensitivity] => Normal
[Size] => 3534
[DateTimeSent] => 2014-07-03T06:56:17Z
[DateTimeCreated] => 2014-07-03T06:56:17Z
[HasAttachments] =>
[From] => stdClass Object
(
[Mailbox] => stdClass Object
(
[Name] => [name]
[EmailAddress] => /O=GROUP TEST/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=59219DC26E6D463AB22C558CC646227D-name
[RoutingType] => EX
)
)
[IsRead] => 1
)
So, my question is how can I get an e-mail address for recipient? Is it possible?
Thanks a lot for your help.
A: The Recipients of a Message (and a number of other properites) aren't returned when you use a FindItem request you need to make a GetItem request http://msdn.microsoft.com/en-us/library/office/aa565934(v=exchg.150).aspx on the particular ItemId you want to get the recipients for. If you need to do this for a large number of Items you can batch the GetItems Request eg http://blogs.msdn.com/b/exchangedev/archive/2010/03/16/loading-properties-for-multiple-items-with-one-call-to-exchange-web-services.aspx
Cheers
Glen
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24549111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I terminate Javascript execution, á la exit/die/fatal assertion, etc.? I have a loop in Javascript, I want to run console.log() in a specific iteration, and then terminate. What is the best method to go about doing this?
I'm wanting something like Perl's
die Dumper \@foo;
A: You can throw an exception:
throw "Help I have fallen and cannot get up";
Not exactly the same, but (in my experience) it's not too common to see exception handling in ordinary DOM-wrangling sorts of JavaScript code, so that usually will blow out of any event loop. However, it's not really the same thing as any surroundling try block will catch what you throw.
A: you mean terminate loop?
while(true) {
console.log()
if(condition) {break};
}
the break command exits the loop
but there is no kill or exit function in javascript.
A: Since JavaScript is event-based, a script doesn't control when it terminates — there's no die or exit.
If it's not one already, the best option is to refactor the code into a function that you can return from, or use a named block:
foo: {
// do work
break foo;
// not executed;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5250037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: VS 2015 TACO - build broke on Xcode 8 / iOS 10 Here are the issues I encountered and fixed:
*
*Code signing: downloaded the xcode8.js hook and added the following to build.json, per http://www.dpogue.ca/articles/cordova-xcode8.html:
"ios": {
"debug": {
"developmentTeam": "VZ4B5XSP9U"
},
"release": {
"developmentTeam": "VZ4B5XSP9U",
"codeSignIdentity": "iPhone Developer"
}
}
*On my Mac, deleted the ~/.taco_home/node_modules/taco-remote-lib/2.2.1 and .../2.2.0 folders, per https://github.com/Microsoft/remotebuild/issues/5.
*On my Mac, tried uninstalling and reinstalling remotebuild, and different versions of node and npm (0.12.9 and 4.6, and respective npm versions).
*In Visual Studio, tried changing the targeted Cordova version: 6.3.1, 6.2, 6.1.1, and back to 5.4.1.
No matter what I do though, the build gets stuck either on extracted - Extracted app contents from uploaded build request, or building - Updating platform forever.
Earlier, when I tried opening the Xcode project in Xcode on the Mac, it successfully built and deployed the app to the device. I was then facing issues using WebRTC (using cordova-plugin-iosrtc) and it was giving me privacy violation exceptions. I tried adding the cordova-custom-config plugin and appropriate Cocoa keys (NSCameraUsageDescription and NSMicrophoneUsageDescription) per App crashes with __CRASHING_DUE_TO_PRIVACY_VIOLATION__ when trying to access contacts, and then it stopped working altogether.
Can anyone please advise what are the latest versions of all of the components I should be using to make it work again? Some sources advise to use Node 0.12.9 on the Mac, others 0.12.7; most people claim that with Cordova >= 5.3.3, any Node version should suffice, however using Node 4.6 didn't work either.
Thanks in advance for any help!
Update: After performing the brew update etc. as suggested by Jordan, the remote deploy works, but the build sets "Main interface" setting under project's General tab to "NSMainNibFile~ipad", which causes the app to crash on launch, until I open the project in Xcode and clear that field, then an incremental build creates a functioning app.
A: This is a known issue with Apache Cordova 6.3.1 and for the Visual Studio tools we've been working on a fix for this. To work around the issue for now, you'll need to perform the following steps:
*
*Add a developmentTeam property to the ios build settings in your project's build.json file (an example is shown below).
*Set the build.json file's codeSignIdentity property to the static value iPhone Developer.
*Setup a before_compile hook in your project to copy the developmentTeam property into the project's platforms/ios/cordova/build.xcconfig file.
The project's build.json file should look something like the following:
{
"ios": {
"debug": {
"developmentTeam": "DEVELOPMENT_TEAM_NAME"
},
"release": {
"developmentTeam": "DEVELOPMENT_TEAM_NAME",
"codeSignIdentity": "iPhone Developer"
}
}
}
To simplify the process, Darryl Pogue published a sample hook that makes the required changes to the project's build.xconfig file based on the build.json example shown above. To use this hook, copy the sample xcode8.js file to your project's hooks folder, and then modify the project's config.xml to execute it before the compilation step using the following code:
<platform name="ios">
<hook type="before_compile" src="hooks/xcode8.js" />
</platform>
Creating a Distribution Build
At this point, the Cordova build process works, and you can run, test and debug your app. Unfortunately, the app isn't being signed with the correct development certificate needed for distribution. In order to sign them with a distribution certificate, you'll need to create an archive of the app by following the instructions found in: Uploading Your App to iTunes Connect.
iOS 10
Developers building Cordova applications for iOS 10 may encounter the following errors:
Http 404: Error mounting developer disk image
Http 500: No devices found to debug. Please ensure that a device is connected and awake and retry.
This is caused by the Mac development environment needing an update to several modules. To fix the issue, on Mac OS, open a terminal window and issue the following command:
brew update && brew upgrade libimobiledevice --HEAD && brew upgrade ios-webkit-debug-proxy ideviceinstaller
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40091788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Time limit exceeded error when doing left shift with boost::multiprecision cpp_int I am trying the following:
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
int main()
{
using namespace boost::multiprecision;
cpp_int v = 1;
unsigned int a = 4294967295;
std::cout << (v << a) << std::endl;
return 0;
}
How to prevent errors in the same?
What is the upper limit of bit shift that we can do with cpp_int.
A: This is allocating huge amounts of (wasted) memory.
Since you can use decimal floating numbers to represent this number without any loss of precision, I'd do that:
Note that 1 << n is equal to 2^n (pow(2, n)), so you can write:
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
namespace bmp = boost::multiprecision;
using number = bmp::number<bmp::cpp_dec_float<50, intmax_t> >;
int main() {
int64_t a = 0xffffffff;
std::cout << pow(number(2), a) << std::endl;
}
Which gets the correct
1.55164e+1292913986
You can verify it is correct:
for (intmax_t const a : { -8888ll, 0xFFFFll, 0xFFFFFFFFll, }) {
std::cout << pow(number(2), a) << std::endl;
auto roundtrip_exponent = bmp::log2(pow(number(2), a));
auto reverse = round(roundtrip_exponent).convert_to<intmax_t>();
std::cout << "Reverse: " << std::hex << std::showbase << reverse << std::dec << "\n";
std::cout << "Match: " << std::boolalpha << (a == reverse) << "\n";
}
Prints Live On Coliru
2.78868e-2676
Reverse: 0xffffffffffffdd48
Match: true
1.00176e+19728
Reverse: 0xffff
Match: true
1.55164e+1292913986
Reverse: 0xffffffff
Match: true
You'll inevitably lose some precision on the inexact operations (log2) in the extreme cases.
If you're curious you may want to try to print the full precision by setting std::fixed:
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
namespace bmp = boost::multiprecision;
using number = bmp::number<bmp::cpp_dec_float<50, intmax_t> >;
int main() {
std::cout << std::fixed << pow(number(2), 0xFFFFFFFFll) << std::endl;
}
Redirect the output to a file! It's gonna write 1.3GiB in decimal digits. This should explain why it didn't work too well with the arbitrary precision integer representation.
All of the output compresses to:
0000000 3531 3135 3436 3230 3137 3339 3631 3334
0000020 3730 3130 3934 3439 3535 3737 3339 3831
0000040 3232 3937 3535 3631 3334 3936 3939 3038
0000060 3737 3938 3631 3338 3737 3030 3532 3339
0000100 3533 3538 3636 3230 3935 3039 3030 3030
0000120 3030 3030 3030 3030 3030 3030 3030 3030
*
11504046500 3030 2e30 3030 3030 3030 000a
11504046513
Where the * denotes lines with only 0 digits. Then you can see why I called it wasteful
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62334346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bash: Why is my read command not ending after pressing return? I have a bash script that I need to run when I'm building and running a docker container. When I run the script independently, it runs fine. The read command ends after I hit return. However, when I put in the docker run command to run the script through docker, the read command never ends even after I press return multiple times.
#!/bin/bash
read -p "Enter = IP Address: " ip
export Ip=$ip
Here are the contents of my Dockerfile
FROM mono:5.20
RUN mono --version
ADD ./game-logic-csharp /gl
RUN msbuild /gl/sol.sln
EXPOSE 80
RUN ["chmod", "+x", "/gl/startup.sh"]
ENTRYPOINT [ "/gl/startup.sh"]
Console Output
The read command should end after I press return to end the input. However, I keep pressing return but the process never moves on.
A: Use next command:
docker run -it your_image
The root cause is you missed -i, see this which make the container can't receive your input:
--interactive , -i Keep STDIN open even if not attached
And if you use docker-compose, remember to add next to compose file:
stdin_open: true
tty: true
stdin_open same to -i in docker run and tty same to -t.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56930908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to empty recycling bin in batch I need a code to empty the recycling bin without conformation I have tried the simple del $Recycle.Bin but it says access denied even when elevated does any one know a code I could use.
A: This emptied my bin without any confirmation.
@ECHO OFF
start /b /wait powershell.exe -command "$Shell = New-Object -ComObject Shell.Application;$RecycleBin = $Shell.Namespace(0xA);$RecycleBin.Items() | foreach{Remove-Item $_.Path -Recurse -Confirm:$false}"
A: Above answers are ok for cmd batch files but for the new powershell there is a better way
Simply use the cmdlet
Clear-RecycleBin
Optionally you can use the -Force or -Confirm:$false parameters so it won't ask for confirmation
For more info open powershell and type
Get-Help Clear-RecycleBin
A: I have just found this.
erase /s/q/f "C:\$RECYCLE.BIN\*">nul
A: Guaranteed to delete all content in the Recycle Bin for the selected drive while leaving the folder itself intact:
C:\$Recycle Bin\>rd . /q /s
*
*Change to the required drive
*Change into the $Recycle Bin folder
*Run the command rd . /q /s [remove-dir (currentdir) /quiet /subdir]
You will get an error that the current directory is still in use (because that is your current location) and can't be deleted. This is expected behaviour because I want the $Recycle Bin folder to remain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21110143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: State Manager not persisting/retrieving data NiFi 1.1.1
I am trying to persist a byte [] using the State Manager.
private byte[] lsnUsedDuringLastLoad;
@Override
public void onTrigger(final ProcessContext context,
final ProcessSession session) throws ProcessException {
...
...
...
final StateManager stateManager = context.getStateManager();
try {
StateMap stateMap = stateManager.getState(Scope.CLUSTER);
final Map<String, String> newStateMapProperties = new HashMap<>();
newStateMapProperties.put(ProcessorConstants.LAST_MAX_LSN,
new String(lsnUsedDuringLastLoad));
logger.debug("Persisting stateMap : "
+ newStateMapProperties);
stateManager.replace(stateMap, newStateMapProperties,
Scope.CLUSTER);
} catch (IOException ioException) {
logger.error("Error while persisting the state to NiFi",
ioException);
throw new ProcessException(
"The state(LSN) couldn't be persisted", ioException);
}
...
...
...
}
I don't get any exception or even a log error entry, the processor continues to run.
The following load code always returns a null value(Retrieved the statemap : {})for the persisted field :
try {
stateMap = stateManager.getState(Scope.CLUSTER);
stateMapProperties = new HashMap<>(stateMap.toMap());
logger.debug("Retrieved the statemap : "+stateMapProperties);
lastMaxLSN = (stateMapProperties
.get(ProcessorConstants.LAST_MAX_LSN) == null || stateMapProperties
.get(ProcessorConstants.LAST_MAX_LSN).isEmpty()) ? null
: stateMapProperties.get(
ProcessorConstants.LAST_MAX_LSN).getBytes();
logger.debug("Attempted to load the previous lsn from NiFi state : "
+ lastMaxLSN);
} catch (IOException ioe) {
logger.error("Couldn't load the state map", ioe);
throw new ProcessException(ioe);
}
I am wondering if the ZK is at fault or have I missed something while using the State Map !
A: The docs for replace say:
"Updates the value of the component's state to the new value if and only if the value currently is the same as the given oldValue."
https://github.com/apache/nifi/blob/master/nifi-api/src/main/java/org/apache/nifi/components/state/StateManager.java#L79-L92
I would suggest something like this:
if (stateMap.getVersion() == -1) {
stateManager.setState(stateMapProperties, Scope.CLUSTER);
} else {
stateManager.replace(stateMap, stateMapProperties, Scope.CLUSTER);
}
The first time through when you retrieve the state, the version should be -1 since nothing was ever stored before, and in that case you use setState, but then all the times after that you can use replace.
A: The idea behind replace() and the return value is, to be able to react on conflicts. Another task on the same or on another node (in a cluster) might have changed the state in the meantime. When replace() returns false, you can react to the conflict, sort out, what can be sorted out automatically and inform the user when it can not be sorted out.
This is the code I use:
/**
* Set or replace key-value pair in status cluster wide. In case of a conflict, it will retry to set the state, when the given
* key does not yet exist in the map. If the key exists and the value is equal to the given value, it does nothing. Otherwise
* it fails and returns false.
*
* @param stateManager that controls state cluster wide.
* @param key of key-value pair to be put in state map.
* @param value of key-value pair to be put in state map.
* @return true, if state map contains the key with a value equal to the given value, probably set by this function.
* False, if a conflict occurred and key-value pair is different.
* @throws IOException if the underlying state mechanism throws exception.
*/
private boolean setState(StateManager stateManager, String key, String value) throws IOException {
boolean somebodyElseUpdatedWithoutConflict = false;
do {
StateMap stateMap = stateManager.getState(Scope.CLUSTER);
// While the next two lines run, another thread might change the state.
Map<String,String> map = new HashMap<String, String>(stateMap.toMap()); // Make mutable
String oldValue = map.put(key, value);
if(!stateManager.replace(stateMap, map, Scope.CLUSTER)) {
// Conflict happened. Sort out action to take
if(oldValue == null)
somebodyElseUpdatedWithoutConflict = true; // Different key was changed. Retry
else if(oldValue.equals(value))
break; // Lazy case. Value already set
else
return false; // Unsolvable conflict
}
} while(somebodyElseUpdatedWithoutConflict);
return true;
}
You can replace the part after // Conflict happened... with whatever conflict resolution you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42902718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add scripts and styles for EXACT page in Wordpress admin panel I am well aware of the WP hooks admin_print_scripts-$mypage, admin_print_styles-$mypage but they seem to trigger only for pages registered with $mypage = add_management_page( ... ), add_options_page(), etc. It's quite clear you won't be able to use these for sub-generated pages with totally different markup unless you keep the URL intact (pass data using POST).
As it's my first encounter, i came up with solution which is quite simple - conditions for $_GET['page'],$_GET['action'](for ex.) and $_SERVER['PHP_SELF'] then hook admin_print_scripts/styles with wp_enqueue_script/style () . It works just well but is it the way to go?
A: I am a little confused as to why you have any pages which are not registered using the WordPress functions. If the plugin/theme is complicated enough to need several distinct pages (not just one page with some tabs) then I suggest you add a standalone page using: http://codex.wordpress.org/Function_Reference/add_menu_page and then have several sub pages using: http://codex.wordpress.org/Function_Reference/add_submenu_page
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4077136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sparql Transaction I want to insert multiple objects into a triplestore like Jena fuseki or virtuoso.
In my case, the subject equal to a primary key. It is similar to a relational database. How can I make sure that the subject is only present once or is already in use? Can an ASK be combined with an insert in Sparql? Or can a key be generated?
As long as you use an instance of the backend you can make sure that the subject only exists once, but with more instance the query and insert must occur simultaneously to save the transaction.
A: The SPARQL standards themselves do not provide any support for transactions. However, Virtuoso and many other RDF databases support the Eclipse RDF4J APIs, which have full transactional support (disclosure: I'm on the RDF4J development team). An example using RDF4J transactions in Java would be something like this:
Repository rep = ... ; // the Repository object is your database
// open a connection to the database
try(RepositoryConnection conn = rep.getConnection) {
conn.begin(); // start a new transaction
...
// do a query
boolean success = conn.prepareBooleanQuery("ASK ...").evaluate();
if (!success) {
conn.rollback();
}
else {
// add some data
conn.add(...);
conn.commit();
}
}
For more information on how transactions work with RDF4J, see the documentation.
If you're not working in Java, you can also work with transaction via the RDF4J REST API, which is an extension of the SPARQL Protocol.
As an aside: the above is just to answer the "how do I do transactions" part of your question really. There may be other, better mechanisms available than doing an ASK query for the kind of constraint validation you're looking for. SHACL, the shapes constraint language, might be what you need. Various tools and platforms have (partial or full) support for SHACL validation. You can read more about RDF4J SHACL support here.
A: An update can be of the form INSERT .. WHERE and the WHERE part can include a test of whether to update or not.
The SPARQL protocol for update requires actions to be atomic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54581081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I turn a directory of images into video? (node.js) I'm trying to create a screen recording video by using a module to create multiple images and then somehow use these images to export to an mp4. However I don't know how to turn the directory of images into a video. Can anyone help with this?
Here is what I have so far:
const screenshot = require('desktop-screenshot');
let i = 0;
while(i <= 100){
screenshot("screens/" + i + "_shot.png", function(error, complete) {
if(error){
console.log("Screenshot failed", error);
}
else{
console.log("Screenshot succeeded");
}
});
i++;
}
A: Why don't you use an npm package for screen recording?
Also your while loop doesn't represent seconds but discrete steps. If you want a time based recording you need some implementation which respects time based steps with step delta to allow adjustment for different rendering speeds. (This is similar to game loops, the only difference is that your action is screen captures and not moving game characters.)
A good screen recording package should do that, as well as providing an API for export. Save your time and effort and use a package for that.
Good point to start: https://www.npmjs.com/search?q=screen+recording
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44914274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Set operations in batch files I have two files and want to check whether one 'contains' the other in a batch script. By 'contains' I mean that the SET of lines in the first file contains the SET of lines in the second file.
For example this file:
a
b
c
d
e
f
g
contains this file:
a
b
d
g
but does not contain this file:
a
b
z
I realize that the task is not very complex but I wonder whether there exists a command line tool that supports set-like operations out of the box. For example, as an alternative for writing a for loop that searches each line from the second file in the first file...
A: edited most of the code in the original post is not needed, so ...
With your set of files, named (in the same order) fullList.txt, list1.txt and list2.txt, this should work
@echo off
setlocal enableextensions disabledelayedexpansion
set "mainFile=.\fullList.txt"
for %%f in (list*.txt) do (
findstr /l /x /v /g:"%mainFile%" "%%~ff" >nul && (
echo %%f is not included
) || (
echo %%f is included
)
)
How does it work? It is just a findstr command for each file. It searchs the "small list" file for strings not contained in the "big list" file. If any line is found, the file is not contained, else it is contained
A: @ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
PUSHD "%sourcedir%"
SET "is_subset=Y"
FOR /f "delims=" %%a IN (subset_file.txt) DO (
FIND "%%a" "superset_file.txt">NUL
IF ERRORLEVEL 1 ECHO fail ON "%%a"&SET "is_subset=N"&GOTO done
)
:done
POPD
ECHO subset IN superset : %is_subset%
GOTO :EOF
This should work - but your question is unclear. This will check that the superset contains every member of the subset, but you may be searching for some members.
I used test files on my U: drive - you would need to modify to suit.
A: The solution below solve the problem in a very fast way. As additional data, it show the lines from the small file not contained in the large file:
@echo off
setlocal
for /F "delims=" %%a in (smallFile.txt) do set "line[%%a]=1"
for /F "delims=" %%a in (largeFile.txt) do set "line[%%a]="
set "anyLine="
for /F %%a in ('set line[ 2^>NUL') do set "anyLine=1"
if defined anyLine (
echo Large file does NOT "contain" the small file. Lines not contained:
echo/
for /F "tokens=2 delims=[]" %%a in ('set line[') do echo %%a
) else (
echo Large file "contain" the small file.
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26231298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Quantile R unused argument error I want to use the quantile function, the example shown under "help"
x <- rnorm(1001)
quantile(x <- rnorm(1001)) # Extremes & Quartiles by default
quantile(x, probs = c(0.1, 0.5, 1, 2, 5, 10, 50, NA)/100)
I get the following error:
Error in quantile(x, probs = c(0.1, 0.5, 1, 2, 5, 10, 50, NA)/100) :
unused argument (probs = c(0.1, 0.5, 1, 2, 5, 10, 50, NA)/100)
The argument probs does not seems to work. I tried many other variations. Does anybody have an idea?
Thanks, Felix
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25854477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I return from a mobile application to a web page? We have a groovy web app for mobile devices. Now we want to "do some stuff" locally that can't be done in a browser, and return the result to the web app. On Android, this page describes how to launch an activity from an intent url, but forgets to tell me how to return a result to the web page. Can this be done? The example given is a barcode scanner, so I presume the web page eventually gets to know the scanned code?
For bonus points, is there an equivalent mechanism for IOS? For windows phone? Would we better making a request for media capture? Or an ajax request for a local url?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33777418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sort part of javascript object I have a javascript object as below. I have to sort data under AddressTotal only checking in below sequence.
1. if any element has "Prime":true then put it at first under AddressTotal.
2. If no "Prime":true , then sort descending order on "Createdate".
Please note it's fine about "Createdate" format as I can handle that.
var x = {
"accts": [{
"Id": "Acc1",
"Person": true,
"Name": "Hello Roy",
"ExternalID": "123456",
"AddressTotal": [{
"Account": "Acc1",
"Id": "Ad3",
"Name": "1 camac Street",
"City": "Chennai",
"State": "KN",
"Zip": "23451",
"AddType": "office",
"Prime": false,
"RecTypeId": "R3",
"Createdate": "5th Feb 2018"
}, {
"Account_vod__c": "Acc2",
"Id": "Ad2",
"Name": "1 strand Road",
"City": "Mumbai",
"State": "JK",
"Zip": "12345",
"AddType": "College",
"Prime": false,
"RecTypeId": "R2",
"Createdate": "2nd Feb 2018"
}, {
"Account": "Acc1",
"Id": "Ad1",
"Name": "1 Park Street",
"City": "Bangalore",
"State": "TN",
"Zip": "74324",
"AddType": "School",
"Prime": true,
"RecTypeId": "R1",
"Createdate": "1st Feb 2018"
}
],
"Rectype": {
"Name": "ABC",
"Id": "Id1"
}
}
],
"hasAccess": ["A1"]
}
Can someone please suggest me a wayout?
A: This is a pretty standard sorting problem.
Start with a test for prime on both elements and end with a comparison of the Date value of the created date.
You cannot compare Createdate directly as this would result in an alphabetical comparison of two string, not the mathematical comparison of timestamps.
var x = {
"accts": [{
"Id": "Acc1",
"Person": true,
"Name": "Hello Roy",
"ExternalID": "123456",
"AddressTotal": [{
"Account": "Acc1",
"Id": "Ad3",
"Name": "1 camac Street",
"City": "Chennai",
"State": "KN",
"Zip": "23451",
"AddType": "office",
"Prime": false,
"RecTypeId": "R3",
"Createdate": "5th Feb 2018"
}, {
"Account_vod__c": "Acc2",
"Id": "Ad2",
"Name": "1 strand Road",
"City": "Mumbai",
"State": "JK",
"Zip": "12345",
"AddType": "College",
"Prime": false,
"RecTypeId": "R2",
"Createdate": "2nd Feb 2018"
}, {
"Account": "Acc1",
"Id": "Ad1",
"Name": "1 Park Street",
"City": "Bangalore",
"State": "TN",
"Zip": "74324",
"AddType": "School",
"Prime": true,
"RecTypeId": "R1",
"Createdate": "1st Feb 2018"
}],
"Rectype": {
"Name": "ABC",
"Id": "Id1"
}
}],
"hasAccess": ["A1"]
};
//TEST
var arr = x.accts[0].AddressTotal.sort(function sorter(a, b) {
if (a.Prime) {
return -1;
}
if (b.Prime) {
return 1;
}
return new Date(a.Createdate).getTime() - new Date(b.Createdate).getTime();
});
console.log(arr);
By the way, is there any reason accts is an array and not just an object?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51816931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: ios - iPad emulator seems to have height that is too much I followed the advice of this question:
Converting Storyboard from iPhone to iPad
and it worked, but my iPad screens seem to be too tall...maybe about 150% too tall. And the user has to scroll down to see the UITabBar.
Would anyone happen to know why that happened and how it can be fixed?
Thanks!
A: That sounds that the simulator is just too big for your monitor. Try going to the Window menu and changing the scale to something smaller. You could also try setting the device to the non-retina iPad.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11993630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to make the bot respond to a message that has one of the elements in an Array I am trying to make my Bot I am currently developing able to respond to a message, Which i really did it.
However I want the bot to respond to one of the elements/strings in an Array, so i don't have to repeatedly write (message.includes('example')) || (message.includes('example2')).
I tried doing this with an if statement as that is the only way i know how to. :
client.on('message', message =>{
if (message.author.bot) return;
const fixgreet = message.content.slice();
const greetings = fixgreet.toLowerCase();
const gnvars = fs.readFileSync('./commands/urls/gn.txt').toString('utf-8');
const gnraw = gnvars.split('\n');
if (greetings.includes(gnraw)) {
client.responds.get('gn').execute(message, fixgreet);
}
Which doesn't return an error at all, but also won't respond.
gnraw is the Array which contains the elements, and greetings is the message content sent by the user, the if statement should be true when the message content contains one of the elements in gnraw and it should send a response.
gn.txt is a TEXT file with strings, which i created it into an array (gnraw) by using :
const gnvars = fs.readFileSync('./commands/urls/gn.txt').toString('utf-8');
const gnraw = gnvars.split('\n');
Here is an example of what would they look.
the TEXT file could be:
gm
good morning
good day
Then gnraw will be ['gm', 'good morning', 'good day'] which is formatted from the TEXT file.
As an example of what i would like to happen.
User A : "Good morning." *sends a message, which then identified as greetings
User B : "GM" *identified as greetings aswell.
if one of the elements in gnraw is included in greetings then
the Bot should respond with 'Good morning'.
Please tell me how do i make the bot respond to a message that has one of the elements in the array.
I am fairly new to JavaScript.
A: The code I suggested in the comments would work (not sure what you're saying doesn't work about it) - but it has a flaw
If greetings were something "I have a lot of phlegm" - it would match with gm
so lets try another way
function fn(keywords, target) {
const res = keywords.map(s => new RegExp(`\\b${s}\\b`));
return res.some(re => target.match(re));
}
client.on('message', message =>{
if (message.author.bot) return;
const fixgreet = message.content.slice();
const greetings = fixgreet.toLowerCase();
const gnvars = fs.readFileSync('./commands/urls/gn.txt').toString('utf-8');
const gnraw = gnvars.split('\n');
if (fn(gnraw, greetings)) {
client.responds.get('gn').execute(message, fixgreet);
}
so .. fn returns a boolean, that is true if one of the gnraw values is found in the greetings string
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64004262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Celery-Django, Start and stop reminder emails for survey I'm trying to implement a recurring daily reminder email task into my program that begins at a specific date/time and is stopped only when the customer completes the required action.
Is this something that is possible with Celery and Django? I've already found a way to send a one time task email via ETA- though am unsure how to set up a recurring event that can then be cancelled.
Thanks for your time.
A: In order to send emails on a daily basis, Celery provides a scheduler for recurring task named Celery beat:
https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html
Once you have Celery beat set up, create a task to send the emails based on user information. The task could look through all users and include only recipients that have a send email flag or a datetime information for sending the next email.
If the user completes the required action, you would unset the send email flag or delete the datetime information and the recurring task would stop sending emails to this user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59093700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AppleScript Count and Remove Characters in Excel I am having issues with my applescript that removes any filename that is greater than 13 characters long. I have a list of filenames in column B and I only need the ones that are 13 characters, nothing more than. I am looking for the script to delete the row of anything more than 13. So far this has been somewhat working and but not removing all of them.
tell application "Microsoft Excel"
activate
open (choose file with prompt "Select the Excel file you wish to use.")
end tell
tell application "Microsoft Excel"
tell active sheet
autofit column "A:H"
end tell
end tell
set cellNumber to 2
tell application "Microsoft Excel"
activate
repeat
set fileName to get value of cell ("B" & cellNumber) as string
set fncount to count characters of fileName
if fncount is greater than 13 then
delete entire row of cell ("B" & cellNumber)
set endCount to 0
else
set endCount to endCount + 1
if endCount > 100 then
exit repeat
end if
end if
set cellNumber to cellNumber + 1
end repeat
end tell
set endCount to 0
A: This does not delete everything, because when the script delete a row, Excel will shift the rows up.
Example: the script delete the second row, now the second row is
the third row, so the script skip a row
To avoid that, the loop must start at the index of the last row.
Use the used range property to get the last row.
tell application "Microsoft Excel"
activate
open (choose file with prompt "Select the Excel file you wish to use.")
tell active sheet
set cellNumber to 2
autofit column "A:H"
set lastR to count rows of used range -- get the index of the last row which contains a value
repeat with i from lastR to cellNumber by -1 -- iterates backwards from the index of the last row
set fileName to string value of cell ("B" & i)
if (count fileName) > 13 then delete row i
end repeat
end tell
end tell
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43768776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Connect to NexusDB using Go or PHP Im trying to access an applications nexusDB records/tables
I cant find much information on this online, is it possible with Golang or PHP7 and if so is there any documentation on doing so.
A: A PHP driver (windows only) exists for NexusDB, currently it supports up to PHP v5.x. PHP v7.x support is being worked on.
Other drivers are either ODBC or Ado.NET. Perhaps say more about what you are trying to do?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60064338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Laravel in docker: cannot run migrations - access denied for root user I'm trying to contenairize my laravel application (not using their default docker config sail for reasons not in the scope of this question). The containers (app, server and db) seem to be built and run correctly, but when I try to run the database migrations:
docker-compose exec app php artisan migrate
I'm getting the following error:
SQLSTATE[HY000] [1045] Access denied for user 'root'@'172.28.0.4' (using password: YES) (SQL: select * from information_schema.tables where table_schema = dundermifflin and table_name = migrations and table_type = 'BASE TABLE')
This is my service configuration in docker-compose.yaml:
db:
image: mysql:8.0.31
container_name: dmc-db
restart: unless-stopped
ports:
- 3306:3306
# use the variables declared in .env file
environment:
MYSQL_HOST: ${DB_HOST}
MYSQL_DATABASE: ${DB_DATABASE}
MYSQL_ROOT_PASSWORD: abcd1234
MYSQL_PASSWORD: ${DB_PASSWORD}
MYSQL_ALLOW_EMPTY_PASSWORD: 1
MYSQL_RANDOM_ROOT_PASSWORD: 1
SERVICE_TAGS: dev
SERVICE_NAME: mysql
volumes:
- ./mysql/data:/var/lib/mysql
networks:
- dmc-net
And this are the vars defined in .env file:
DB_CONNECTION=mysql
# use mysql container name instead of 127.0.0.1 when running in docker, otherwise use the IP
DB_HOST=dmc-db
DB_PORT=3306
DB_DATABASE=dundermifflin
#DB_USERNAME=michaelscott
DB_USERNAME=root
#DB_ROOT_USERNAME=root
DB_PASSWORD="7aADMi__Cfv"
#DB_PASSWORD=root
If I connect to the container and then try running:
mysql -u root -p
using the password defined above (abcd1234) I get the same error:
ERROR 1045 (28000): Access denied for user 'root'@'192.168.0.4' (using password: YES)
Every single time I make any change to the vars or to docker-compose.yaml I'm running docker-compose build --no-cache just to make sure none of the old configuration vars stick around.
What am i missing?
Thanks
A: Have you tried runing command with more options? (especially with db name)
mysql -u root -p dundermifflin
also try maybe without defining MYSQL_HOST and then
mysql -u root -p dundermifflin
or
mysql -h localhost -u root -p dundermifflin
https://dev.mysql.com/doc/refman/8.0/en/connecting.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74511916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Retrofit2/OkHttp3: REST webservice does not specify characterset I am accessing a webservice that are not able to specify content-type nor character set for the content I consume.
Is there a way, using retrofit2 (or okhttp3 client interceptors), to add information about this so that received content can be processed correctly?
A: With Retrofit you can use the @Headers annotation:
For instance:
@Headers("Cache-Control: max-age=640000")
You could then (if you always know the Content Type) set your Interface to be:
@Headers("Content-Type: application/json")
@GET("widget/list")
Call<List<Widget>> widgetList();
https://square.github.io/retrofit/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42427499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to listen for requests and maintain "dialog" in asp.net OK, I'm quite new to web developing and this is a bit difficult to define abstractly so I'll say exactly what I'm trying to do:
I have an asp.net website running on my server. I want to have other websites to have a button which redirects to a specific URL. This URL is determined during the creation (server side) of the other website. I want the other website to request that URL by supplying certain parameters. I'll create the URL accordingly and return a response which contains the URL.
To clarify: User browses other website, gets to page which is supposed to have said button, other website requests URL, supplies params, receives URL and creates page with button with URL received.
It's important to me that this works with any platform of "other" website. What is the simplest way to do this?
Many thanks in advanced.
A: I think the simplest way would be to write a web service (WCF could be used, for example) which returns the said URL to the other web site. The "request for the URL" would just be a web service call from the other web site to your web service.
A: Sounds like your best bet would be to create a web service that would be consumed by the other websites.
The MSDN site actually has a good overview and a couple of decent tutorials: ASP.NET Web Services
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4671849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using sql to determine if the user has liked a post Use-case. We have users posts and likes tables. I am a user with id 4 who wants to get a list of posts and for each individual post I'd like to know if I liked it already or not.
I know this is sounds like a trivial problem, but I can't figure out a simple solution that does not involve using the union and the subquery..
Consider following data structure:
CREATE TABLE users(
id bigint NOT NULL PRIMARY KEY
);
CREATE TABLE posts(
id bigint NOT null PRIMARY KEY,
userId bigint NOT NULL references users(id),
name varchar(40) not null
);
CREATE TABLE likes(
userId bigint NOT NULL references users(id),
postId bigint NOT NULL references posts(id),
PRIMARY KEY(userId, postId)
);
insert into users values (1),(2),(3),(4);
insert into posts values (1, 1, 'Post 1, user 1'), (2, 1, 'Post 2, user 1');
insert into posts values (3, 2, 'Post 3, user 2'), (4, 2, 'Post 4, user 2');
insert into posts values (5, 4, 'Post 5, user 4'), (6, 4, 'Post 6, user 4');
insert into likes values (1, 1), (1, 2);
insert into likes values (2, 1);
insert into likes values (3, 5);
insert into likes values (4, 1), (4, 5);
Then, if I want to get the posts that I liked I use (I am user id=4 in this example)
-- get what I like
select
p.*
, true as isLiked
from posts p
left join likes l on l.postId = p.id
where 1=1
and l.userid = 4
order by p.id;
Then, if I want to select the rest of the posts I use:
-- get the rest of the posts
select
p.*
,false as isLiked
from posts p
where 1=1
and not exists (select 1 from likes l where l.postid = p.id and l.userid = 4)
order by p.id;
Finally, the query that accumulates both of these solutions:
-- result
select * from (
select
p.*
, true as isLiked
from posts p
left join likes l on l.postId = p.id
where 1=1
and l.userid = 4
union ALL
select
p.*
,false as isLiked
from posts p
where 1=1
and not exists (select 1 from likes l where l.postid = p.id and l.userid = 4)
) p
order by p.id;
SQL fiddle: http://sqlfiddle.com/#!17/50108b/1
Back to my question. Is this my imagination or have I overly complicated the query? instead of a single query with a JOIN I ended up with a couple of queries joined in union and a subquery.. Is there a more friendly approach for the task?
I am using postgresql of latest version, but of course since it's an sql then I guess answers in other languages are just as must welcomed..
Note: after I have written the question - stackoverflow suggested a topic with a similar question so I was able to solve the problem that way.. The answer is provided below, however, feel free to comment if you have something to say on the subject..
A: Later, following the solution in thread here: Many-to-many relationship to determine if user has liked a post
I was able to come up (copy?) with alternative solution that yields the same result:
select
p.*
,EXISTS(SELECT * FROM likes l WHERE l.postid = p.id and l.userid = 4) AS isLiked
FROM posts p
order by p.id;
While substantially reducing the complexity.
I ran the explain command and it does look to perform better on paper.. Not sure if the best solution of all but works fine in my scenario while only a few records in table are present..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71414831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Paginated array would not show I'm rather new to Ruby on Rails so would appreciate some help
Roles have Users in my application.
When showing a role I would like to render a paginated list of user names (and as a further refactor - links to users).
Currently my HAML template is as follows
...
%ul.assigned-users
- if @role.users.present?
- names = @role.users.collect {|u| u.name}
- links = Kaminari.paginate_array(names).page(params[:page]).per(20)
= paginate links
- else
%p No users have this role assigned
...
Rendering it gives me the pagination links BUT no names.
A: Kaminari's paginate_array method does not show the values in the array.
The best way to do so is get the query paginated from the database. Kaminari.paginate_array in your code takes in the whole array of users from the database and then paginates it which is highly inefficient and memory consuming.
You need to add the logic to the controller. If you paginate the @role.users query, it is generated with LIMIT which is the value you assign in the per method and OFFSET which equals to (params[:page] - 1) * per. This gets only the number of records you need from the database.
In your controller app/controllers/roles_controller.rb
class ConversationsController < ApplicationController
def show
@role = Role.find params[:id]
@users = @role.users.page(params[:page]).per(20)
end
end
In your view app/views/roles/show.html.haml
%ul.assigned-users
- if @users.present?
- @users.each do |u|
%li=u.name
= paginate @users
- else
%p No users have this role assigned
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34052040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reason for sending callback functions as argument Callback function is a special kind of function that (pointer to function) is passed to caller function as argument.
Callback function is used in event-driven scenarios i.e., callback function is called by caller function if and only if particular event happens.
My doubt is, what is the reason for sending callback function as (only) arguments?
Can't we call it inside the body of caller function as shown below?
caller()
{
.............
if(event) {
callback_function();
}
}
instead of using the following
caller(....,&callback_function)
{
.............
}
Where I am thinking in wrong direction?
A: It can be done the way you propose, but the idea for callbacks sent as an argument to another function is to make them non-static callable objects (fitted for any purpose) instead of one implementation per use-case. Also, you don't always have access to invoke the "callback" function (called the way you intend to) due to scope restrictions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49234092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQLAlchemy ORM select multiple entities from subquery I need to query multiple entities, something like session.query(Entity1, Entity2), only from a subquery rather than directly from the tables. The docs have something about selecting one entity from a subquery but I can't find how to select more than one, either in the docs or by experimentation.
My use case is that I need to filter the tables underlying the mapped classes by a window function, which in PostgreSQL can only be done in a subquery or CTE.
EDIT: The subquery spans a JOIN of both tables so I can't just do aliased(Entity1, subquery).
A: I was trying to do something like the original question: join a filtered table with another filtered table using an outer join. I was struggling because it's not at all obvious how to:
*
*create a SQLAlchemy query that returns entities from both tables. @zzzeek's answer showed me how to do that: get_session().query(A, B).
*use a query as a table in such a query. @zzzeek's answer showed me how to do that too: filtered_a = aliased(A).filter(...).subquery().
*use an OUTER join between the two entities. Using select_from() after outerjoin() destroys the join condition between the tables, resulting in a cross join. From @zzzeek answer I guessed that if a is aliased(), then you can include a in the query() and also .outerjoin(a), and it won't be joined a second time, and that appears to work.
Following either of @zzzeek's suggested approaches directly resulted in a cross join (combinatorial explosion), because one of my models uses inheritance, and SQLAlchemy added the parent tables outside the inner SELECT without any conditions! I think this is a bug in SQLAlchemy. The approach that I adopted in the end was:
filtered_a = aliased(A, A.query().filter(...)).subquery("filtered_a")
filtered_b = aliased(B, B.query().filter(...)).subquery("filtered_b")
query = get_session().query(filtered_a, filtered_b)
query = query.outerjoin(filtered_b, filtered_a.relation_to_b)
query = query.order_by(filtered_a.some_column)
for a, b in query:
...
A: from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
bs = relationship("B")
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('a.id'))
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)
s.add_all([A(bs=[B(), B()]), A(bs=[B()])])
s.commit()
# with_labels() here is to disambiguate A.id and B.id.
# without it, you'd see a warning
# "Column 'id' on table being replaced by another column with the same key."
subq = s.query(A, B).join(A.bs).with_labels().subquery()
# method 1 - select_from()
print s.query(A, B).select_from(subq).all()
# method 2 - alias them both. "subq" renders
# once because FROM objects render based on object
# identity.
a_alias = aliased(A, subq)
b_alias = aliased(B, subq)
print s.query(a_alias, b_alias).all()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14511633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Create DOUBLE PRECISION column from VARCHAR that is 99% numbers... (but includes some strings) I use Postgresql. I have a varchar column RAW_RET, mostly of numbers, and I'm trying to make a new column RET which is DOUBLE PRECISION. The problem is that a few rows of RAW_RET contain text, (Eg. character 'B' instead of numbers. Hence the following command:
update q_stock.daily set RET = cast(RAW_RET as double precision) ;
returns an error, invalid input syntax for type double precision: "B"
It seems like I need to do something like select only numeric rows, but I'm struggling at the moment to figure out how to do that...
A: For real numbers, you can use a regular expression:
update q_stock.daily
set RET = cast(RAW_RET as double precision)
where RAW_RET ~ '^[-]?[0-9]+\.?[0-9]*$';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33685697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python, mongo + spider monkey Ok, so this isn't exactly a question that I expect a full answer for but here goes...
I am currently using a python driver to fire data at a mongo instance and all it well in the world. Now I want to be able to pull data from mongo and evaluate each record in the collection. Now I need to pass in to this evaluation a script that will look at the row of data and if a condition is met return true i.e.
(PSUDO CODE)
foreach(row in resultSet)
if(row.Name=="Chris) return true
return false
Now the script that I use to evaluate each item in the row should be sandboxes somehow with limited functionality/security privileges.
In other words the code will be evaled, and I dont want it to have rights to i.e. include external libraries, call remote servers or have access any files on the server etc...
With this in mind I know that mongo uses something called spider monkey (which I gather is a JS evaluator) to write queries. I wonder would it be possible to take the result of a mongo call and pass it to an evaluated javascript function using spider monkey (somehow) to achieve what I am after? If so would this be safe enough.
To be honest, Im writing this question and I realize its sounding a lot like one of those "please help, how to code the world" type questions but any pointers would be helpful.
A: Have you looked at $where clauses in MongoDB? Seems like those would pretty much give you exactly what you're looking for. In PyMongo it would look something like:
db.foo.find().where("some javascript function that will get applied to each document matched by the find")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2285083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unnecessary repaint of following siblings I'm using react-transitive-number to achieve transitive animation of number changes [demo page]
The problem is - if you look this page in Chrome devtools, "Paint Flashing" in Rendering tab you may see that every transition cause following siblings to repaint.
Why this might happen? I can understand repaint of number, or any element relates to this plugin. But why it affects following siblings at whole website?
Are there any way to avoid these unnecessary repaints?
A: Moving every tag with number to own layer solved problem.
Solution is - adding of
translateZ(0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41243786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Gradle: try to skp sonarqube results in error I have a gradle script that uses Sonarqube plugin (org.sonarqube). If I let the publish task depends on it, it works fine.
The problem is to run sonarqube only if a condition is true. So I tried (as described in gradle documentation) all of these three statements:
sonarqube.enabled (false)
sonarqube.enabled=false
sonarqube.onlyIf { false }
Each results in an error, here the one I got trying the first statement
FAILURE: Build failed with an exception.
* Where:
Build file 'D:\Eclipse\workspace3.6\at.mic.hermes\build.gradle' line: 208
* What went wrong:
A problem occurred evaluating root project 'at.mic.hermes'.
> Could not find method enabled() for arguments [false] on org.sonarqube.gradle.SonarQubeExtension_Decorated@412196.
To be sure to have not typo in the code I tried all statements with the test task, e.g.
test.enabled(false)
and this results (as expeted) in
:test SKIPPED
Any ideas what I made wrong / what must be changed? Thx in advance!
Frank
A: I think the problem come from a name conflict. There are 2 objects named 'sonarqube':
*
*The SonarQube task
*The SonarQube extension
It seems to not break your build, but here when you write sonarqube.enabled it access to the extension (according to your stacktrace).
The solution is probably to disambiguate using tasks.sonarqube.enabled. See https://docs.gradle.org/current/userguide/more_about_tasks.html#N11143
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36333343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Insert multiple lines into a file using shell script I want to insert multiple lines into a .json file after a specific pattern using shell script. Also need to consider to insert on the nth occurrence.
Let us consider my input file contents are: input.txt:
[
{
"a": "a",
"b": "b"
},
{
"c": "c",
"d": "d"
},
{
"e": "e",
"f": "f"
}
]
In my first case, I have to insert below two lines after the first occurrence of pattern "}," and in my second case the same two lines after the second occurrence of pattern "}," in the input.txt file
After inserting my file should change like this:
First case: Inserting x & y entries
[
{
"a": "a",
"b": "b"
},
{
"x": "x",
"y": "y"
},
{
"c": "c",
"d": "d"
},
{
"e": "e",
"f": "f"
}
]
Second case: Inserting m & n entries
[
{
"a": "a",
"b": "b"
},
{
"c": "c",
"d": "d"
},
{
"m": "m",
"n": "n"
}
{
"e": "e",
"f": "f"
}
]
I am trying this with sed command in my shell scipt. But this always replaces in the first occurrence and not the nth occurrence.
sed -e '0,/},/{//a\ {\n "x",\n "y"\n },' -e '}' input.txt file
Can any one help me?
A: If you were using jq it'd as simple as
jq '.[:1] + [{"x":"x", "y":"y"}] + .[1:]' input.json
Demo
and
jq '.[:2] + [{"m":"m", "n":"n"}] + .[2:]' input.json
Demo
respectively.
A: If it's something that you are planning to reuse you can do it in python.
#! /usr/bin/env python3
import json
import sys
j = json.load(sys.stdin)
j.insert(int(sys.argv[1]), json.loads(sys.argv[2]))
print(j)
and you can invoke it passing the position and object as parameters
./json-insert 1 '{"x": "x", "y": "y"}' < input.json
A: cat file.json|tr '\n' ' '| sed 's/},/},{"x":"x", "y":"y"},/2'|json_pp
[
{
"a" : "a",
"b" : "b"
},
{
"c" : "c",
"d" : "d"
},
{
"x" : "x",
"y" : "y"
},
{
"e" : "e",
"f" : "f"
}
]
#--------------------------------------------------------------
cat file.json|tr '\n' ' '| sed 's/},/},{"x":"x", "y":"y"},/2'|json_pp > tmp.json
mv tmp.json file.json
A: This might work for you (GNU sed & Bash):
cat <<\! | sed -Ee '/\}/{x;s/^/x/;/^x{1}$/{x;r /dev/stdin' -e 'x};x}' file
{
"x": "x",
"y": "y"
},
!
or:
cat <<\! | sed -Ee '/\}/{x;s/^/x/;/^x{2}$/{x;r /dev/stdin' -e 'x};x}' file
{
"m": "m",
"n": "n"
},
!
Pipe strings to be inserted via /dev/stdin into a sed invocation, using a counter in the hold space to initiate the placement of the strings.
N.B. The r command has to be terminated by a newline, hence the reason for splitting the sed commands into two parts using the -e command option. The strings can be collected in a here-document and passed to /dev/stdin of the following pipe using the cat command.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71244184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# csproj file "Choose" element for assembly HintPaths Is it possible to use the Choose/When/Otherwise elements on a reference hintpath?
Something like this:
<ItemGroup>
<Reference Include="SharedLib...">
<SpecificVersion>False</SpecificVersion>
<Choose>
<When Condition="Exists('..\..\SharedLib\bin\Debug')">
<HintPath>..\..\SharedLib\bin\Debug\SharedLib.dll</HintPath>
</When>
<Otherwise>
<HintPath>.\SharedLib.dll</HintPath>
</Otherwise>
</Choose>
</Reference>
</ItemGroup>
But I get errors like ...required attribute "Include" is empty or missing from element "ItemGroup"
Other attempts/version have yielded similar errors such as ...The "Choose" item metadata name is reserved and cannot be used.
This makes me think I canNOT use the "Choose" element INSIDE of an ItemGroup element.
I welcome clarification. See attached samples of the errors.
Visual Studio csproj Errors when loading project
A: I don't think you can put just the HintPath in the Choose. You have to put the entire ItemGroup within the When and Otherwise. Like this:
<Choose>
<When Condition="Exists('..\..\SharedLib\bin\Debug')">
<ItemGroup>
<Reference Include="SharedLib...">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\SharedLib\bin\Debug\SharedLib.dll</HintPath>
</Reference>
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Reference Include="SharedLib...">
<SpecificVersion>False</SpecificVersion>
<HintPath>.\SharedLib.dll</HintPath>
</Reference>
</ItemGroup>
</Otherwise>
</Choose>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36480093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: VS Code %USERNAME% Wild Card in JSON Settings In the Windows Command Prompt, I can enter:
cd \Users\%USERNAME%
And it takes me to my user's home directory, e.g.: C:\User\MyName.
But in Visual Studio Code's JSON settings, the following doesn't resolve:
{
"jshint.config": "C:\\Users\\%USERNAME%\\JSHint.json",
}
Is there a trick to getting %USERNAME% to resolve in the JSON settings? Do I need to escape the percentage signs somehow? Or does the %USERNAME% wildcard simply doesn't work in VS Code?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63591046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: adding a number to a variable I am trying to get the contents of a txt file "usernum.txt", get the contents, add one to that number, and replace the current number with the new one. Here is what I have so far
#!/bin/sh
ID=0
cat ''$pwd'usernum.txt' >> $ID
count1=1
IDB=$(($ID+$count1))
rm "usernum.txt"
touch "usernum.txt"
echo $IDB >> usernum.txt
It runs but when I open the file, it stays the same. Any ideas?
Thanks,
Mike
A: You should store the output from cat into ID instead of using >>. The way you are doing that you always add to a file named '0'. To store the output of cat use:
ID=$( cat 'usernum.txt' )
I have also removed the 'pwd' as you do not need it and also it gets escaped by the single quotes.
EDIT: here is a complete working example. Note that if there is no usernum.txt file this will print some errors(cat and rm fail) but still will work(i.e. will print 1 in the file). You should perform a check to see if the file exists to avoid these errors:
ID=$( cat 'usernum.txt' )
count1=1
IDB=$(($ID+$count1))
rm "usernum.txt"
touch "usernum.txt"
echo $IDB >> usernum.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12508059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Remove a dataframe from a list of dataframes conditionally I have a list of dataframes from which I would like to remove the dataframes that have a particular value in a specific column.
Code
library(tidyverse)
combi <- function(a=c(1,2,3), b=c(2,3,4,5)){
return(expand.grid(a,b))
}
df <- pmap(list(a=c(1,2,3)), combi)
Output
df
[[1]]
Var1 Var2
1 1 2
2 1 3
3 1 4
4 1 5
[[2]]
Var1 Var2
1 2 2
2 2 3
3 2 4
4 2 5
[[3]]
Var1 Var2
1 3 2
2 3 3
3 3 4
4 3 5
Let's say I would like to remove a dataframe, if Var1==2.
How do you tackle this problem in the Tidyverse?
A: You can use discard in purrr
purrr::discard(df, ~any(.x$Var1 == 2))
#Or using keep
#purrr::keep(df, ~any(.x$Var1 != 2))
#[[1]]
# Var1 Var2
#1 1 2
#2 1 3
#3 1 4
#4 1 5
#[[2]]
# Var1 Var2
#1 3 2
#2 3 3
#3 3 4
#4 3 5
Or Filter in base R :
Filter(function(x) any(x$Var1 != 2), df)
Some variations :
df[sapply(df, function(x) any(x$Var1 != 2))]
df[purrr::map_lgl(df, ~any(.x$Var1 != 2))]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62813254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to setup and run openpaas release version in ubuntu I am trying to setup openpaas: [https://github.com/linagora/openpaas-esn ] development on ubuntu system. i am unable to setup.
before seting up locally , i tried running with docker(as in http://docs.open-paas.org/getting-started/linux/ ) it works fine.i need to setup locally (as in https://github.com/linagora/openpaas-esn/blob/master/doc/develop.md), i am facing problem.
now I am following developer documentation: https://github.com/linagora/openpaas-esn/blob/master/doc/develop.md ,after setup installation is complete and point browser to http://localhost:8080 , i get login page But after logging as admin(admin@open-paas.org), i am getting blank screen. I can see error in chrome console.How can i setup locally and run openpaas .
In documentation it says front end is vue.js , but i am getting Angular js, ng route related error .
installed angular router but this did not help .
as in https://github.com/linagora/openpaas-esn/blob/master/docker/doc/known_issues.md , i tried
docker exec esn_james java -jar /root/james-cli.jar -h localhost adddomain open-paas.org
I did checkout openpass : https://github.com/linagora/openpaas-esn to home folder.
then did
npm install
to run dependecy software as in documentation, i run docker-compose up as below. so redis,rabbitmq,mongo,elasticsearch,sabre,james,james_elastic,cassandra are running in docker,then tested , i am able to connect.
ESN_HOST="172.17.0.1" ESN_PATH="$PWD" docker-compose -f ./docker/dockerfiles/dev/docker-compose.yml up
then as per documentation , to run openpaas with below command
grunt dev
tried alternative ways
node ./bin/cli.js
openpaas is up and running, on pointing browser to http://localhost:8080/ , i get login page , after login i get blank screen. and error in chrome console
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.20/$injector/modulerr?
how do i get it running.
need to setup openpaas locally for start development/customise to my needs.
since i cannot create tag, and openpaas tag is not already present, just added angularjs tag
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55654482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Swift: Implementing Find-or-Create Efficiently So I set up some data from an API to create a managed object, How do I determine whether the managed object already exists (in my example, every object has a unique id), and create it if it does not.
// set up core data
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context:NSManagedObjectContext = appDel.managedObjectContext!
// Get data from API
let urlPath = "http://www.example.com"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let getMovies = session.dataTaskWithURL(url!, completionHandler: {
data, response, error -> Void in
if error != nil {
println(error)
} else {
// Parse the JSON data from API
var moviesResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
if let subjects = moviesResult["subjects"] as? [[NSObject:AnyObject]] {
var movies = [[String:NSString]()]
var movie:AnyObject
var newMovieItem:NSManagedObject
// Loop through the arrays returned by API to get each movie
for (var i = 0 ; i < subjects.count ; i++) {
// Initialize the movies array
movies.append([String:NSString]())
movie = subjects[i] as NSDictionary
movies[i]["title"] = movie["title"] as? NSString
movies[i]["id"] = movie["id"] as? NSString
newMovieItem = NSEntityDescription.insertNewObjectForEntityForName("Movies", inManagedObjectContext: context) as! NSManagedObject
newMovieItem.setValue(movies[i]["title"], forKey: "title")
newMovieItem.setValue(movies[i]["id"], forKey: "id")
context.save(nil)
}
var request = NSFetchRequest(entityName: "Movies")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
}
}
})
getMovies.resume()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29996727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: django how to check if a user is already exists on this app without making too much query? Assume these as django models:
class Question():
question = charfield()
choice = charfield(choices = answer_choice)
class Answer():
question = models.foreignkey(Question, related_name = 'answers')
answerer = models.foreignkey('auth.User')
answer = models.charfield()
I'm building a page where i display 100 questions, and each User can answer, but cannot change the answer for each question. For each question, i have to check whether the User already exists or not on Answerer. Then i make templatetags:
@register.filter
def this_user_exists(user,obj):
obj = obj.answers.filter(answerer_id = user.id)
return obj
Then on the template:
# obj is list of question
{% if not user|this_user_exists:obj %}
# can answer
{% else %}
# cannot answer
{% endif %}
The problem is, for every question, it generate 1 query, so for 100 question it'll generate 100 query. I tried this query to generate question Question.objects.all() and Question.objects.prefetch_related('answers'), still got the problem. Is there a better way to achieve this without making too many query?
A: To reduce queries, you can first query out your needed answers, and then fetch all related answerers,
answers = Answer.objects.select_related('answerer').filter(xxxx)
# fetch related user id's
userids_in_answer = [answer.answerer.id for answer in answers]
# fetch user ids
user_id_set = set(User.objects.filter(id__in=userids_in_answer).values('id', flat=True)
after that, you can easily know whether user exists by,
for answer in answers:
if answer.answerer.id in user_id_set:
xxx
The query num is reduced, you can check whether this helps.
A: In your view:
answered_ids = [ans.question_id for ans in Answer.objects.filter(answerer=request.user)]
In your template:
{% if not obj.id in answered_ids %}
# can answer
{% else %}
# cannot answer
{% endif %}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14048118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: retrieving data from play-scala server We want to use REACT in a scala-play project. We'll, also, use AXIOS to send request from REACT (web browser) to the server. The question is, how could be a great way to create services on the play-scala server to respond to the requests coming from the web browser which could be using React?
Thx
A: A great way would be to use the HTTP programming features of Play.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42907927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Why does a insertion/extraction operator's overloaded function need ostream/istream argument? Consider the following code with overloaded insertion & extraction operators.
#include <iostream>
using namespace std;
class CTest
{
string d_name;
public:
friend ostream & operator<<(ostream & out, CTest & test);
friend istream & operator>>(istream & in, CTest & test);
};
ostream & operator<<(ostream & out, CTest & test)
{
out << "Name: " << test.d_name;
return out;
}
istream & operator>>(istream & in, CTest & test)
{
cout << "Enter your name: ";
string name;
if(in >> name)
test.d_name = name;
return in;
}
int main()
{
CTest test;
cin >> test; // (1)
cout << test; // (2)
}
Following the question, what's the significance of arguments ostream & out and istream & in?
Since we can see only one argument (cin >> test or cout << test), where in the caller is the ostream/istream references passed at (1) or (2)?
A: Because in both cin >> test and cout << test, two arguments exist.
cin is of type istream.
cout is of type ostream.
These types could be other things than cout and cin. For example, they could be cerr, clog, or stringstream.
That's why you need two arguments, since the one is the variable for the stream and the other is the object to be streamed.
A: cin >> test;
Here, left operand is the cin object of type std::istream, and the right operand is your CTest class object.
Prototype of >> operator
friend istream& operator >> (istream& s, Your class &);
So, internally we have passed two arguments.
A: In order to get a better understanding where the two arguments come from, you may rewrite your main() function as follows:
int main()
{
CTest test;
operator>>(std::cin, test);
operator<<(std::cout, test);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46723073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Word 2010 Interop: Show the "Save As" dialog I need a way to always show the save as dialog when the user performs a certain action on a Word document. Currently, the dialog only shows when an unsaved document is saving. These documents I am working on have already been saved in one location with a particular name, but users will need to be able to change the name and the location.
A: Figured it out. Very simple, in case someone else runs into the same issue:
var wordDialog =
Globals.ThisDocument.ThisApplication.Dialogs[Word.WdWordDialog.wdDialogFileSaveAs];
wordDialog.Show();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15710235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why animation can be reusable after change display why animation can be reusable after im changing elemets display property with js
can some one explain i couldnt find any answer for this
can someone explain me this
my codes downbelow
`
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
aside {
display: none;
position: relative;
left: -100%;
height: 100vh;
background-color: red;
width: 20%;
animation: openit 800ms ease-in forwards ;
}
@keyframes openit {
to{
left: 0;
}
}
aside a {
display: block;
}
.open {
position: absolute;
z-index: -1;
}
</style>
`
A: I found this:
When we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable. That is why the transition property does not work.
form this link. I hope this help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74666969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Capturing an image From Camera Returns Empty Data While Capturing image in android app intent return null each time. Please see below the code which I am using. I have tried multiple ways to get the permission as well as intent set but still I am unable to get data.
Action For Camera
private void takePhotoFromCamera() {
if(ActivityCompat.checkSelfPermission(ObservationsView.this,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(getExternalCacheDir(),
String.valueOf(System.currentTimeMillis()) + ".jpg");fileUri = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}else {
String[] permissionRequest = {Manifest.permission.CAMERA};
requestPermissions(permissionRequest, 8675309);
checkPermission();
}
}
And Here is the Response Code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK ) {
Uri selectedImg = null;
Bitmap bmp = null;
Bundle extras;
if (requestCode == CAMERA_REQUEST) {
selectedImg = data.getData();
extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
}
else if (requestCode == CAMERA_REQUEST) {
selectedImg = fileUri;
// Bitmap mphoto = (Bitmap) data.getExtras().get("data");
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri);
if (bmp != null) {
bmp = getBitmapFromUri(fileUri);
}
}catch (IOException e) {
e.printStackTrace();
}
Uri tempUri = getImageUri(getApplicationContext(), bmp);
Intent passPhoto = new Intent(this, Photo.class);
passPhoto.putExtra("image",tempUri);
passPhoto.putExtra("Caller", getIntent().getComponent().getClassName());
startActivity(passPhoto);
}
A: Try to use the following code for getting the image in all APIs -
public void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = FileProvider.getUriForFile(mContext,
BuildConfig.APPLICATION_ID + ".provider",
getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, TAKE_IMAGE_REQUEST);
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), getString(R.string.app_folder_name));
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
return new File(mediaStorageDir.getPath() + File.separator +
PROFILE_PIC + getString(R.string.pic_type));
}
And on your onActivityResult -
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_IMAGE_REQUEST:
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
break;
default:
break;
}
}
Also, you need to define the Provider in your Manifest.xml file -
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
And finally the provider_paths.xml will be as follows -
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Let me know in case you need any clarification.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53113646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get the data from previous month in sql query I have a data of all the cost for each month. For example,
I have table of cost for each month
+--------+--------+-----+--------+--------+
| Jan | Feb | Mar | Apr | May |
+--------+--------+-----+--------+--------+
| 899.20 | 0 | 0 | 0 | 899.20 |
| 439.38 | 485.29 | 0 | 0 | 482.29 |
+--------+--------+-----+--------+--------+
Then what I want in the output for every month that is = '0', it will get the data in the previous month and so on until it's not equal = '0'
Is this possible using oracle sql or using xml.
I tried the oracle sql query below, for example is I want the value of April to be = 899.20
I used the case when condition,
case
when Apr = '0' then Mar
when Mar = '0' then Feb
when Feb = '0' then Jan
else Apr
end
and in XML is the if else condition
<?xdofx:if apr = '0' then mar
else if mar = '0' then feb
else if feb = '0' then jan
else apr
end if?>
But both conditions I know didn't work. Please help
Thank you
A: You can use:
SELECT Jan,
CASE WHEN Feb > 0 THEN Feb
ELSE Jan END
AS Feb,
CASE WHEN Mar > 0 THEN Mar
WHEN Feb > 0 THEN Feb
ELSE Jan END
AS Mar,
CASE WHEN Apr > 0 THEN Apr
WHEN Mar > 0 THEN Mar
WHEN Feb > 0 THEN Feb
ELSE Jan END
AS Apr,
CASE WHEN May > 0 THEN May
WHEN Apr > 0 THEN Apr
WHEN Mar > 0 THEN Mar
WHEN Feb > 0 THEN Feb
ELSE Jan END
AS May
FROM table_name
Which, for the sample data:
CREATE TABLE table_name ( Jan, Feb, Mar, Apr, May ) AS
SELECT 899.20, 0, 0, 0, 899.20 FROM DUAL UNION ALL
SELECT 439.38, 485.29, 0, 0, 482.29 FROM DUAL;
Outputs:
JAN | FEB | MAR | APR | MAY
-----: | -----: | -----: | -----: | -----:
899.2 | 899.2 | 899.2 | 899.2 | 899.2
439.38 | 485.29 | 485.29 | 485.29 | 482.29
db<>fiddle here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65632932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to mass / bulk PutObjectAcl in Amazon S3? I am looking for a way to update several objects ACL in one (of few request) to the AWS API.
My web application contains several sensitive objects stored in AWS S3. This object have a default ACL to "private". I sometimes need to update several objects ACL to "public-read" for some time (a couple of minutes) before going back to "private".
For a couple of objects, one request per object to PutObjectAcl is ok. But when dealing with several objects (hundreds), the operation requires to much time.
My question is : how can I "mass put object acl" or "bulk put object acl" ? The AWS API doesn't contain a specific answer, like DeleteObjects (which allows to delete several objects at once). But may be I didn't look in the right place ?!
Any tricks or way to work around that would be of great value !
A: Mixing private and public objects inside a bucket is usually a bad idea. If you only need those objects to be public for a couple of minutes, you can create a pre-signed GET URL and set a desired expiration time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68291539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Catch a html tag value with javascript I have a div tag like
<div id="123" reference="r045">
Now I wanna save the value of the reference. I tried it with
var reference = document.getElementbyName("reference");
Didnt work. Any ideas?
Thanks :)
A: getElementbyName gets an element by its name.
The reference attribute:
*
*Is not a name attribute
*Is not valid HTML at all
So start by writing valid HTML:
<div id="123" data-reference="r045">
Then get a reference to that element:
const div = document.getElementById('123');
Then get the data from it using the dataset API:
console.log(div.dataset.reference);
Live demo
const div = document.getElementById('123');
console.log(div.dataset.reference);
<div id="123" data-reference="r045"></div>
A: You can use document.querySelectorAll('[reference]') if you have multiple div with same attribute.
var reference = document.querySelectorAll('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
But if you have only one div with reference attribute then use querySelector:
var reference = document.querySelector('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
A: var reference = document.getElementById("123").getAttribute("reference");
A:
var x = document.getElementById("123").getAttribute("reference");
console.log(x);
<div id="123" reference="r045"></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51967555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Fill drop down list on selection of another drop down list I am using MVC and I am still new with MVC. Can anyone tell me if you can fill a drop down list with data on selection of another drop down list.
I want to use Jquery to avoid postbacks and therefore making the page smoother.
A:
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17013644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
}
|
Q: Macro to copy values only from one sheet to another I've this VBA code
Sheets("log").Range("A125:f1000").Copy _
Sheets("data").Cells(Rows.Count, "A").End(xlUp).Offset(1)
and it copies perfectly from sheet log to data. The only problem I'm facing is that it copies formulas with it as well whereas I only want values. I want to use same VBA code with some modifications to paste values only.
A: Need to add PasteSpecial Paste:=xlPasteValues
Next time try Recording a macro and modifying the code
Sheets("log").Range("A125:f1000").Copy
Sheets("data").Cells(Rows.Count, "A").End(xlUp).Offset(1). _
PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
A: Without using clipboard:
Sheets("data").Cells(Rows.Count, "A").End(xlUp).Offset(1).Value = Sheets("log").Range("A125:f1000").Value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17565456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Testing chef data bags I need to test chef recipe. This is using a data bag.
kitchen is using chef_zero in order to provision the machine. So, it's not able to get my data bag hosted on server. Then it's telling me that my data bag is not available.
How could I get a data bag available on test kitchen?
I've created a aws.json file on test\integration\data_bags:
{
"id": "dev",
"aws_access_key_id": "----",
"aws_secret_access_key": "----"
}
When I perform my converge I'm getting this message:
INFO: HTTP Request Returned 404 Not Found: Object not found: chefzero://localhost:8889/data/aws/dev
ERROR: Failed to load data bag item: "aws" "dev"
.kitchen.yml file content:
---
driver:
name: vagrant
provisioner:
name: chef_zero
always_update_cookbooks: true
verifier:
name: inspec
platforms:
- name: ubuntu-16.04
- name: centos-7.2
suites:
- name: default
data_bags_path: "test/integration/data_bags"
run_list:
- recipe[living-development::default]
verifier:
inspec_tests:
- test/smoke/default
attributes:
Versions:
$ vagrant -v
1.9.2
$ chef -v
Chef Development Kit Version: 1.2.22
chef-client version: 12.18.31
delivery version: master (0b746cafed65a9ea1a79de3cc546e7922de9187c)
berks version: 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.700789 5824] 2017-03-08T11:19:04.700789 5824] 5.6.0
kitchen version: 1.15.0
A: The server error indicates that is searching something called aws/dev (where aws is the data bag's name and dev is the name of the item within that data bag).
So you would have to place your JSON file under test/integration/data_bags/aws/dev.json.
Btw. you don't have to manually specify the data_bags_path, as test-kitchen will search for items at exactly this path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42667098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Having Problems Dynamically Displaying a Nested List Using Core Data Hereafter is the Problem I'm Dealing with:
*
*I am permanently storing information using iOS Core Data
*I would like to (dynamically) display the information stored in core data in a UITableView (as later described)
*I am considering the use of Core Data´s Fetched Results Controller (FRC) and the FRC Delegate in order to more efficiently handle the bridge between the permanently stored data and updates in the UI
*
*I have a Person entity with name as an attribute.
*I have two "to-many" relationships pointing from a Person to an
Employment Entity and two "to-one" inverse relationships pointing back, such that any person can have any number (0 to ∞) of employer(s) and any number of employee(s), simultaneously:
employee <—>> employmentTaken
employer <—>> employmentGiven
*
*Every Employment has a rank (Int) attribute used to display a Person´s employer(s) - if any - to the user in an order defined by the relative income generated by each Employment of that Person (each income level being subject to changes at any time).
*For the program to keep track of persons shown in the UITableView, each Employment also comes with a show (boolean) attribute where true = show on the table and false = don't show on the table.
I would like to list Persons in a UITableView, such that when the user presses on a a Person as many rows are introduced in the UITableView under the Person´s name as is needed to display the Person´s Employer(s), and so recursively (since any Person may both be an Employer and an Employee), the final view being a nested list.
Example as Follows:
Initial UI State:
Name of Person 1
Name of Person 2
Name of Person 3
...
UI State After the User Presses on Person 2, assuming that Person 2 simultaneously works for Person 4, 5, and 6:
Name of Person 1
Name of Person 2
________Name of Person 4 * // 1st Source of Income by Size of Person 2*
________Name of Person 5 * // 2nd Source of Income by Size of Person 2*
________Name of Person 6 * // 3rd Source of Income by Size of Person 2*
Name of Person 3
I am currently using NSFetchedResultsController, fetching all employments which have show = true and trying to sort them using two keys:
let rank = NSSortDescriptor(key: #keyPath(Employment.rank), ascending: true)
let employee = NSSortDescriptor(key: #keyPath(Employment.employee), ascending: true)
(Displaying the Name of the Person in the cell, I use the dot notation: employment.employer?.name)
Using those keys the order is not the desired and I'm trying to figure out if I can get the right sorting using sortDescriptor and the FRC.
Should I use the FRC at all or instead just create an array of arrays and write some extra code to take care of updating the UI myself?
(I am still somewhat fresh to coding and any help would be tremendously appreciated!)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53689363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to crop a selected picture in Outlook mail body with VBA I need VBA Code for crop picture in outlook mail body
Does anyone have code please share with me
A: After a 5 minute search on Google I found the following link https://www.experts-exchange.com/questions/27768384/Outlook-macro-to-resize-picture-s.html
to summarise though this should help you (untested):
This macro will resize all pictures, including those in your signature (if any), in the currently open message to 75% of their height and width.
Follow these instructions to add the code to Outlook.
*
*Start Outlook
*Press ALT+F11 to open the Visual Basic Editor
*If not already expanded, expand Microsoft Office Outlook Objects
*If not already expanded, expand Modules
*Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting Insert > Module.
*Copy the code from the code snippet box and paste it into the right-hand pane of Outlook's VB Editor window
*Click the diskette icon on the toolbar to save the changes
*Close the VB Editor
Here's how to add a button to the QAT for running the macro with a single click.
Outlook 2010. http://www.howto-outlook.com/howto/macrobutton.htm#qat
Sub ResizeAllPicsTo75Pct()
Const wdInlineShapePicture = 3
Dim olkMsg As Outlook.MailItem, wrdDoc As Object, wrdShp As Object
Set olkMsg = Application.ActiveInspector.CurrentItem
Set wrdDoc = olkMsg.GetInspector.WordEditor
For Each wrdShp In wrdDoc.InlineShapes
If wrdShp.Type = wdInlineShapePicture Then
wrdShp.ScaleHeight = 75
wrdShp.ScaleWidth = 75
End If
Next
Set olkMsg = Nothing
Set wrdDoc = Nothing
Set wrdShp = Nothing
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47269205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: setting up XmlConfigurator Common Logging with log4net I have been looking at creating a common logging library for the company I work for, based on a blog by Daniel Cazzulino. so we can switch one out for another without to much disruption.
The first library I looked to use is log4net, but I cannot work out how or where you would setup a call to the XmlConfigurator.
I have tried adding an assembly on the project being logged, which kind of defeats the object of the exercise I feel, but that doesn't appear to work any way.
I have tried adding it as an assembly of the log4net Logging library, but that doesn't appear to work.
I have also tried calling log4net.Config.XmlConfigurator.Configure(); from the TraceManager.Get method, but all the log options (IsDebugEnabled, IsWarnEnabled, ...) are disabled.
public partial class TracerManager : ITracerManager
{
/// <summary>
/// Gets a tracer instance with the specified name.
/// </summary>
public ITracer Get(string name)
{
log4net.Config.XmlConfigurator.Configure();
var logger = LogManager.GetLogger(name);
return new Log4NetAdapter(logger);
}
/// The rest
}
Do I need to do something else?
Does the app config need to be in in the logging library?
[Edit 1]
Feel very silly....
I'd added [assembly: XmlConfigurator(Watch = true)] to my Logging.Log4Net library, but I wasnt instantiating the TracerManager in my application on the tests I was performing... ID-10Tango issue
A: I'd added [assembly: XmlConfigurator(Watch = true)] to my Logging.Log4Net library, but I wasnt instantiating the TracerManager in my application on the tests I was performing...
ID-10Tango issue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14602488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mySQLdb import error I am following this guide: How do I connect to a MySQL Database in Python?
running jupyter notebook.
I am running windws 10 operating system and I have installed MySQLdb from this link https://sourceforge.net/projects/mysql-python/files/ "MySQL for python"
I have MySQL Workbench installed.
When running I get an error
ImportErrorTraceback (most recent call last)
<ipython-input-5-a07af86e2020> in <module>()
---> 12 import MySQLdb
ImportError: No module named MySQLdb
I am not sure what I am doing wrong.
I tried things such as
pip install mysqlclient
pip install mysql-python
Running mysqlclient gives me following:
Collecting mysqlclient
Using cached mysqlclient-1.3.10.tar.gz
Complete output from command python setup.py egg_info:
sh: 1: mysql_config: not found
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-TH5iAY/mysqlclient/setup.py", line 17, in <module>
metadata, options = get_config()
File "setup_posix.py", line 44, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 26, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
Running mysql-python gives me following:
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: 1: mysql_config: not found
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-anTaSr/mysql-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
When looking up the error on stack, it tells me to install MySQLdb, but I have that installed already.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43847868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to compare two columns in separate spreadsheets and if the columns match, output related data in from one spreadsheet to the other Had a search and sadly couldn't find a related question
Im trying to compare two columns in separate spreadsheets and if the columns match, output related data in from one spreadsheet to the other. In the Screenshot below, I am trying to compare the two "required functionality description" fields which are in separate spreadsheets. Then If the two fields match, output the Importance field from one to the other.
I really appreciate any help/guidance on this! Thanks!
A: Try:
=IFERROR(VLOOKUP(G6,[SO31165136a.xlsx]Sheet1!$G:$H,2,0),"")
adjusted for your sheet and workbook names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31165136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AWS S3 - How to stop images from force downloading instead of displaying. I am currently trying to load images from my website to AWS S3. I have the functionality working where it uploads the image to the server but when i try to view the images they download instead of displaying. I read there is a way to set the file type so this would not happen. I am not sure how to do that. Any help would be great.
router.post('/heroes/createNewHeroes', function(req,res) {
var formidable = require('formidable'),
http = require('http'),
util = require('util');
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(fields);
console.log(files);
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
var shortid = require('shortid');
var fs = require('fs');
var fileStream = fs.createReadStream(files.asset.path);
var newFilename = shortid.generate()+"_"+files.asset.name;
// Set your region for future requests.
AWS.config.region = 'us-west-2';
AWS.config.accessKeyId = 'access Key';
AWS.config.secretAccessKey = 'secret Key';
console.log(newFilename);
fileStream.on('error', function (err) {
if (err) { throw err; }
});
fileStream.on('open', function () {
var s3bucket = new AWS.S3({params: {Bucket: ' '}});
s3bucket.createBucket(function() {
var params = {Key: newFilename, Body: fileStream};
s3bucket.upload(params, function(err, data) {
if (err) {
console.log("Error uploading data: ", err);
} else {
console.log("Successfully uploaded data");
projectX.createHeroes(['plantTypes', 'asset', 'cost', 'energy', 'isSunProducer', 'isShooter', 'isExploding', 'sunFrequency', 'shootingFrequency', 'damage'], [fields.plantTypes, newFilename, fields.cost, fields.energy, fields.isSunProducer, fields.isShooter, fields.isExploding, fields.sunFrequency, fields.shootingFrequency, fields.damage], function(data){
res.redirect('/heroes')
});
}
});
});
});
});
});
A: var params = {Key: newFilename, ContentType: 'image/png', Body: fileStream};
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property
A: Just put "contentType: multerS3.AUTO_CONTENT_TYPE " . It will work .
Ex:
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'some-bucket',
contentType: multerS3.AUTO_CONTENT_TYPE,
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
})
Visit this link for more details https://github.com/badunk/multer-s3
A: This Helped me
storage: multerS3({
s3: s3,
bucket: "bucketname",
acl: "public-read",
contentType: multerS3.AUTO_CONTENT_TYPE,
key: function(req, file, cb) {
console.log("req.file", file);
cb(null, `${Date.now()}-${file.originalname}`);
}
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37903053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: WPF - When TextBox inside DateTemplate is focused change datatemplate child property I have a listview with a Border wrapping a textbox (and other elements not shown in sample code). I want when the textbox is keyboard focused to change a property of the border that wraps it.
<ListView ItemsSource="{Binding activeLists}">
<ListView.ItemTemplate>
<DataTemplate>
<Border x:Name="border">
<TextBox Text="something">
<TextBox.Style>
<Style>
<Style.Triggers>
<Trigger Property="TextBox.IsFocused" Value="True">
<Setter TargetName="border" Property="TextBox.Background" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
If using inside the trigger TargetName="border" the item is not found.
If possible to do this from XAML only.
A: When I tried running this, I also got the error "TargetName property cannot be set on a Style Setter". Which indicates that you can't set a property of the Border control inside a style setter for the TextBox control (which doesn't honestly surprise me.)
What you can do instead is set it in the style of the border control itself, using a DataTrigger to bind to the IsFocused property of the textbox:
<Border>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsFocused, ElementName=textBox}" Value="true">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBox Name="textBox" Text="something"/>
</Border>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41907274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hibernate str() function using Criteria API How can I use HQL str() function which is using for converting numeric value to readable string with Criteria API?
A: I think, you won't need str() function with Criteria API, since you can first convert numerics into Strings with API functions like: Integer.toString() then set as Parameter like;
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("age", Integer.toString(age) ) )
.list();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9195277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get the row values as column in SQL I have below table,and need to get row values as an output.
This is a part of a view in Oracle Database.
I need to get the output using SQL as below.name,address,regionare taking from another table by referringID .
Looking for much simple way since full query have more than 15 columns and below also need to be added as columns.
Thanks.
A:
"Looking for much simple way since full query have more than 15 columns"
Sorry, you can have a complex query or no query at all :)
The problem is the structure of the posted table mandates a complex query. That's because it uses a so-called "generic data model", which is actually a data anti-model. The time saved in not modelling the requirement and just smashing values into the table is time you will have to spend writing horrible queries to get those values out again.
I assume you need to drive off the other table you referred to, and the posted table contains attributes supplementary to the core record.
select ano.id
, ano.name
, ano.address
, ano.region
, t1.value as alt_id
, t2.value as birth_date
, t3.value as contact_no
from another_table ano
left outer join ( select id, value
from generic_table
where key = 'alt_id' ) t1
on ano.id = t1.id
left outer join ( select id, value
from generic_table
where key = 'birth_date' ) t2
on ano.id = t2.id
left outer join ( select id, value
from generic_table
where key = 'contact_no' ) t3
on ano.id = t3.id
Note the need to use outer joins: one of the problems with generic data models is the enforcement of integrity constraints. Weak data typing can also be an issue (say if you wanted to convert the birth_date string into an actual date).
A: PIVOT concept fits well for these types of problems :
SQL> create table person_info(id int, key varchar2(25), value varchar2(25));
SQL> create table person_info2(id int, name varchar2(25), address varchar2(125), region varchar2(25));
SQL> insert into person_info values(4150521,'contact_no',772289317);
SQL> insert into person_info values(4150522,'alt_id','98745612V');
SQL> insert into person_info values(4150522,'birth_date',date '1990-04-21');
SQL> insert into person_info values(4150522,'contact_no',777894561);
SQL> insert into person_info2 values(4150521,'ABC','AAAAAA','ASD');
SQL> insert into person_info2 values(4150522,'XYZ','BBBBB','WER');
SQL> select p1.id, name, address, region, alt_id, birth_date, contact_no
from person_info
pivot
(
max(value) for key in ('alt_id' as alt_id,'birth_date' as birth_date,'contact_no' as contact_no)
) p1 join person_info2 p2 on (p1.id = p2.id);
ID NAME ADDRESS REGION ALT_ID BIRTH_DATE CONTACT_NO
------- ------- ------- ------ --------- ---------- ----------
4150521 ABC AAAAAA ASD 12345678V 21-APR-89 772289317
4150522 XYZ BBBBB WER 98745612V 21-APR-90 777894561
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49747010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Creating Custom IconFactory in Gtkmm I have a small application, where I want to create some buttons, toolbars, etc. but I do not want to use a pre-existing GTK icon theme, I want to create my own. So I looked for tutorials and whatnot, but as it turned out, it was not very well discussed online. So I tried to do something on my own:
Header File:
#include <gtkmm.h>
#include <string>
#include <iostream>
#include <errno.h>
class IconFactoryBuilder
{
public:
IconFactoryBuilder();
~IconFactoryBuilder();
void RegisterNewIcons(std::string pPath);
private:
Glib::RefPtr<Gtk::IconFactory> mCustomFactory;
};
Cpp File:
#include <IconFactoryBuilder.h>
IconFactoryBuilder::IconFactoryBuilder() {
mCustomFactory = Gtk::IconFactory::create();
}
IconFactoryBuilder::~IconFactoryBuilder() {
}
void IconFactoryBuilder::RegisterNewIcons(std::string pPath) {
Glib::RefPtr<Gtk::IconSet> iconSet = Gtk::IconSet::create();
Gtk::IconSource someSource;
try{
Gtk::Image *someImage=Gtk::manage(new Gtk::Image(pPath+"appbar.at.png"));
someImage->set_pixel_size(Gtk::IconSize(48));
someSource.set_pixbuf(someImage->get_pixbuf());
someSource.set_size(Gtk::ICON_SIZE_DIALOG);
someSource.set_size_wildcarded();
}
catch(const Glib::Exception &ex) {
std::cerr << "An error occurred while opening the icon file!" << strerror(errno) << std::endl;
}
catch(...) {
std::cerr << "Unknown Error!" << std::endl;
}
iconSet->add_source(someSource);
const Gtk::StockID somestock("MyNewIcon");
Gtk::Stock::add(Gtk::StockItem(somestock, "somelabel"));
mCustomFactory->add(somestock, iconSet);
mCustomFactory->add_default();
}
But now I am quite stuck, because I do not really know how to call this new icon I have created. I also do not know if the above written code is enough to actually find the icon or not.
A: You created an icon factory... factory?
;-)
The serious answer to your question is that you don't need Gtk::IconFactory. Unfortunately the GTK 2 documentation doesn't tell you that it's unnecessary. What you do need is the freedesktop.org Standard Icon Naming Specification. Create your icons, give them simple names, organize according to the directory structure described there, install it to the appropriate place, and your icons will "just work" when you create a Pixbuf or Image using the ...from_icon_name() functions. (example: Gtk::Image::set_from_icon_name())
Here is a page from the Gnome developer wiki on how to provide your own icons:
http://developer.gnome.org/integration-guide/stable/icons.html.en
And here is a page from a tutorial I wrote about installing custom icons: http://ptomato.name/advanced-gtk-techniques/html/desktop-file.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12956081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Options to securely authenticate mobile access using OAuth2 We're currently in the process of implementing OAuth2 to secure our new API and not sure how to securely provide required functionality. We need to allow the following from a mobile device:
Immediately after downloading the app the user is able to take a picture and submit it without having to first log in.
While we want to allow anonymous user access, where a user does not need to log in or register to use certain functionality, we do not want to allow unauthenticated access to the API. This would normally be accomplished using the client credentials authorization flow to obtain and app access token, however this requires knowing the client secret. From what I've read, a mobile device is not considered a trusted client and should not contain the client secret, and hence should not be able to generate an app access token on its own.
We've come up with a few options to accomplish this requirement, but would like some input on them:
*
*Embed the client secret in the app. Doesn't seem ideal from a security standpoint, but maybe we're missing an obvious way to secure it? We're targeting at least iOS and Android.
*Generate an app access token offline and embed that in the app. Still not very secure, but at least the secret isn't exposed.
*Allow access to certain functionality using only the client ID instead of an access token. This may be the simplest, but it introduces an inconsistency and requires multiple ways of authenticating the client.
*Build and use a companion web app to generate app access tokens for the mobile app. On the surface seems like a winner, but now you have to secure access to the companion app!
How would you securely authenticate access to an API using OAuth2 from a mobile device without requiring the user to first log in?
A: Agree with the comments on the Q. Either:
1.) Use Client Credentials grant type in OAuth 2 - with an embedded secret in your App. Understand that this isn't super secure and someone will reverse engineer it eventually. Ideally each client would get a unique secret - so you could revoke a client if they're abusing its use.
2.) Live with that API being open - thereby not requiring an OAuth 2 access token at all. Maybe that API would be known only to your app - but again, it would only be a matter of time before someone reverse engineers it.
A: My group is having a similar discussion. Users can get the app and browse a catalog without having to sign-in. The catalog and other data is accessed via an API and we would like to force users to have an access_token for all calls.
Our current thinking is to
*
*Always force the App to exchange a common clientId/secret for an access_token. So the app would get an access_token even for anonymous users. This would be via the client_credentials oAuth flow.
*If the user signs in, use the oAuth password flow. They would pass in clientId, secret, username, and password. We would additionally allow them to pass in their anonymous token so that we could transfer any history from their anonymous session.
So for example...
access_token = api.oAuth.client_credentials(clientId, secret)
catalog = api.getCatalog(access_token)
authenticated_access_token = api.oAuth.password(clientId, secret, username, password, access_token)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8389134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to hide/unhide desktop icons in Python? Is it possible to hide/unhide icons on your desktop with Python? I know a way of doing it by editing registry but changes take place after you log off and log back on. If you have any suggestion, I'd appreciate your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68758276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Golang: what's the point of interfaces when you have multiple inheritence I'm a Java programmer, learning to program in Go. So far I really like the language. A LOT more than Java.
But there's one thing I'm a bit confused about. Java has interfaces because classes can inherit only from one class. Since Go allows multiple inheritance, what's the point of interfaces?
A: Interfaces in Go are very different from interfaces in Java.
In Java a class has to formally agree to implement an interface:
public class Foo implements iFoo
In Go a user type implements an interface by simply doing so.
A function or property can then define what is expected:
func DoSomething(r io.Reader) {
buf := make([]byte, 128)
n, err := r.Read(buf)
...
}
The DoSomething function can be passed anything that implements the Read function found in the io.Reader interface, without the thing knowing or caring about the interface. It is the responsibility of the caller to make sure it is passing in something that implements the interface. This is checked at compile time.
We can take this a step further. We can define our own interface:
type MyInterface interface {
io.Reader // Include Reader interface
Seek(int) error // Include my own function
}
func DoSomething(r MyInterface) {
buf := make([]byte, 128)
n, err := r.Read(buf)
...
}
Go is also different in that it doesn't have a class or object type. Any user declared type, whether it be based on an integer, string, struct, array, slice, channel, etc. can have methods attached to it.
Go also doesn't have typical class-like inheritance you're normally used to, but it does have a couple of things that are pretty close.
Redeclared type:
type Num int
func (n Num) Print() {
print(n)
}
type Number Num
func (n Number) Print() {
Num(n).Print()
}
Anonymous fields:
type Foo struct {
sync.Mutex
}
func main() {
f := Foo{}
f.Lock()
// ...
f.Unlock()
}
A: Polymorphism
Interfaces enable functions to have a 'placeholder' parameter which can take different structs as an argument. For example, if structs Man, Woman, Child implement interface Human, then a method with the parameter Human can take any of the structs Man, Woman, Child as an argument. Hence, the interface parameter can 'morph' into any struct passed as an argument as long as it implements all functions defined in the interface.
This is important because interfaces are the only way of achieving Polymorphism in Go, since it doesn't have inheritance. So if Man 'extended' Human (by having it as an anonymous field), any method that used Human as an argument, would not be able to take Man as an argument.
My confusion stemmed from the fact that inheritance is also a way of achieving Polymorphism in Java, and I assumed that was the case here as well. I stand corrected!
A: If supertype X is an interface, whoever is maintaining the code knows at once that it has no method implementations. If supertype Y is an abstract class, whoever is maintaining the code has to check whether there are method implementations. So it's a documentation/maintenance/readability thing.
A: Classes can inherit and implement from multiple class files.
Unless I misinterpreted:
public class MyClass extends MySuperClass implements MyInterface, MySecondInterface
The point of interfaces is to allow for a completely abstract class. So abstract that there isn't a single method defined.
I would use an interface when I need to create several abstract classes with the same basic structure. I would then be able to create instances of classes which extend the abstract class, which in turn would implement the interface.
This is done with the interface java.util.Collection and some classes like java.util.ArrayList and java.util.Stack implement that interface. This way you can store all kinds of lists' items in a Collection. This is why ArrayList has a method to addAll(Collection<? extends E> c).
You could say it is like being backwards compatible with simpler objects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18048541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to prevent JSX comment from adding a 'children' element, potentially breaking types? Let's say I have a third party library like this:
declare var SomeComponentFromLibrary: React.FC<{
children?: React.ReactElement
}>;
Where children is defined to be a React.ReactElement, and I can't change that fact.
Now, let's say I use it, with a component <MyComponent /> that happens to generate a type error, and I wish to suppress the error for the timebeing:
<SomeComponentFromLibrary>
{/* @ts-expect-error */}
<MyComponent />
</SomeComponentFromLibrary>
This creates 2 items in SomeComponentFromLibrary's children, (the comment {} and <MyComponent), while SomeComponentFromLibrary's type definition expects only one child, yielding this:
Type '{ children: any[]; }' is not assignable to type '{ children?: ReactElement.... }'.
Is it possible at all to use typescript @ts- comments (well, or any other comments) in ~~JSX without creating actual children?~~
EDIT:
Looks like when I add the comment, it doesn't change the resulting JavaScript ((React.createElement(SomeComponentFromLibrary, null, React.createElement(MyComponent, null)))) -- But for some reason, TypeScript still complains (things that children is any[]). I think this could be a bug in TS -- maybe it parses JSX differently?
A: Typescript comment directives are not very JSX friendly, sadly. But you can definitely make it work.
Give it one child, in braces, { }, with the comment in those braces.
<SomeComponentFromLibrary>
{/* @ts-expect-error */
<MyComponent />
}
</SomeComponentFromLibrary>
Playground
Also, side note: The typings of SomeComponentFromLibrary are probably just wrong. In nearly all cases I've ever seen, children should be typed as React.ReactNode. And when you type this function as such, it now works exactly like you expect.
So I'd probably create a pull request for whatever this library is to fix that.
A: Looks like this is a bug: https://github.com/microsoft/TypeScript/issues/41125
It's fixed here: https://github.com/microsoft/TypeScript/pull/41166 and should be released either in 4.1 or 4.2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64667775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PhpStorm make grouping like Xcode Can I make a grouping my php pages like Xcode group in PhpStorm ? Is there any suggestion ?
There are two types of folders in Xcode: groups and folder references.
You can use groups to organize files in your project without affecting
their structure on the actual file system. This is great for code,
because you’re only going to be working with your code in Xcode.
referance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38990260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Check Box makes Label Visible I have three Combo Boxes - When they are selected i would like it to check the tick box.
if the check box is ticked the Text box will then become Enabled, i currently have it set as disabled.
my question is how would i set the check box to be true when the three Combos are selected.
and how would i make it so that when the tick box is true it will enable the tex box
A: When all 3 combo boxes are set it will enable the checkbox. Once the value for any combo box is updated it calls a common function which checks whether all combo boxes have a value assigned and accordingly set the checkbox.
Private Sub cmbClientContact_AfterUpdate()
Call SetCheckBox
End Sub
Private Sub cmbClientName_AfterUpdate()
Call SetCheckBox
End Sub
Private Sub cmbProjectManager_AfterUpdate()
Call SetCheckBox
End Sub
Private Sub SetCheckBox()
If Nz(Me.cmbClientContact, "") <> "" And Nz(Me.cmbClientName, "") <> "" And Nz(Me.cmbProjectManager, "") <> "" Then
Me.Check25 = True
Me.Text27.Enabled = True
Else
Me.Check25 = False
End If
End Sub
Enable/disable textbox basis value of the checkbox
Private Sub Check25_AfterUpdate()
If Nz(Me.Check25, False) Then
Me.Text27.Enabled = True
Else
Me.Text27.Enabled = False
End If
End Sub
A: I would reccomend using the AfterUpdate event of all 3 combo boxes. Since the code is going to be the same (you're checking if all 3 combo boxes have a value), you can create one function to handle the check, and set that function to the AfterUpdate event of all 3 combo boxes when the form loads.
The function to update the controls (both the text box and check box) would be something like this:
Private Function UpdateControls()
Me.Text1.Enabled = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
Me.Check1.Value = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
End Function
You can call this function when the form initially loads, so the checkbox will be unchecked and the textbox will be disabled:
Private Sub Form_Load()
' update controls initially when the form loads
UpdateControls
End Sub
To make sure the same update happens whenever one of the combo box's values are updated, you can set each combobox's AfterUpdate event to the same function, like this:
Private Sub Form_Load()
' set each combo box's AfterUpdate event to run the check
Me.Combo1.AfterUpdate = "=UpdateControls()"
Me.Combo2.AfterUpdate = "=UpdateControls()"
Me.Combo3.AfterUpdate = "=UpdateControls()"
End Sub
So your final code might be something like this:
Private Sub Form_Load()
' set each combo box's AfterUpdate event to run the check
Me.Combo1.AfterUpdate = "=UpdateControls()"
Me.Combo2.AfterUpdate = "=UpdateControls()"
Me.Combo3.AfterUpdate = "=UpdateControls()"
' update controls initially when the form loads
UpdateControls
End Sub
Private Function UpdateControls()
Me.Text1.Enabled = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
Me.Check1.Value = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
End Function
A: Without knowing more specifics about the name schemas of your objects, this is my semi-vague answer:
One option (of many) is to use an On Click event procedure with the following:
If Not IsNull(Me.Combo1) _
And Not IsNull(Me.Combo2) _
And Not IsNull(Me.Combo3) Then
Me.Check1 = True
Me.Text1.Enabled = True
Else
Me.Check1 = False
Me.Text1.Enabled = False
End If
This assumes that the checkbox is named Check1 and the textbox is named Text1 and the comboboxes are Combo1, Combo2, and Combo3
It is a little confusing whether you meant Enabled or Visible, but if you meant Visible, just change the lines that say .Enabled to .Visible
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51635473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: put random image on uibutton I'm new to Objetive-C and need some help,
I have an Array with 22 UIImage's and 4 UIButtons on the view.
I want to take an image from the array with ObjectAtIndex:somecounter and place this image randomly in one of the 4 UIButton's, than I want to take another 3 UIImages from the Array (random images) and locate them randomly in the other 3 UIButtons that I have left.
so in each time that the counter is in a number, take the UIImage that stored in this index, locate it randomly in one of the UIButtons, than take other 3 random UIImages from the Array and locate them randomly on the 3 UIButton that I have left.
how can I do that?
after using basvk answer came up with this:
-(void)PlaceWordAndPictueOnScreen
{
NSArray *buttons = [NSArray arrayWithObjects:btnLetter1, btnLetter2, btnLetter3, btnLetter4, nil];
for (UIButton *btn in buttons) {
int randomIndex= random() % [LettersArray count];
UIImage *img = [LettersArray objectAtIndex:randomIndex];
[btn setImage:img forState:UIControlStateNormal];
[LettersArray removeObjectAtIndex:randomIndex];
}
}
so I did exactly as he said and it worked like charm, but, I do have a problem.
I have this counter called 'imgcounter', lets say he's value is '4', I want to take the image that located at index 4 and put it in one of the 'btnLetter' UIButton, but in a random button, than in the other 3 'btnLetter' buttons that left, to put another 3 random UIImage's, how can I do that?
Thanks..
A: Out the top of my head, something like this:
-(void)placeImages {
NSMutableArray *images = [NSMutableArray arrayWithObjects:@"image1.png", @"image2.png", @"image3.png", @"image4.png", @"image5.png", @"image6.png", @"image7.png", @"image8.png", nil]; // etc...
NSArray *buttons = [NSArray arrayWithObjects:btn1, btn2, btn3, btn4, nil];
for (UIButton *btn in buttons) {
int randomIndex= random() % images.length;
UIImage *img = [images objectAtIndex:randomIndex];
[btn setImage:img forState:UIControlStateNormal];
[images removeObjectAtIndex:randomIndex];
}
A: -(void)randomizeArray:(NSMutableArray *)array
{
int i, n = [array count];
for(i = 0; i < n; i++) {
int destinationIndex = random() % (n - i) + i;
[array exchangeObjectAtIndex:i withObjectAtIndex:destinationIndex];
}
}
this is a answer for your question
A: btnLetter1, btnLetter2, btnLetter3, btnLetter4 = UIButtons that should present an image.
LatterArray = the array that containes all of the images.
imgcounter = the current counter index
if the 'imgcounter' is on '2' so one of the 'btnLetters' buttons (random one between 1-4) should containe an image from 'LettersArray' that located in index number '2' equal to the 'imgcounter'. all the other remining 3 'btnLetter' should containe a random image from 'LettersArray'.
when the function called again the 'imgcounter' will be '3', now one of the 'btnLetters' (random one) should containe another image from 'LettersArray that is located at index number '3', again, equal to the 'imgcounter'. the other remining 3 'btnLetter' should containe again randome image from 'Letters Array' and so on..
-(void)PlaceWordAndPictueOnScreen2
{
NSMutableArray * ButtonArray = [[NSMutableArray alloc] initWithObjects:btnLetter1,btnLetter2,btnLetter3,btnLetter4, nil];
int CorrectImg = random() % [ButtonArray count];
UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgcounter]];
UIButton * btn = [ButtonArray objectAtIndex:CorrectImg];
[btn setImage:img forState:UIControlStateNormal];
[ButtonArray removeObjectAtIndex:CorrectImg];
NSLog(@"img correct: %i",CorrectImg);
while ([ButtonArray count] != 0)// how many times u want to run this
{
int imgRand = random() % [LettersArray count]; //number for random image
int btnRand = random() % [ButtonArray count]; //number for random button
//get that random image
UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgRand]];
//get that random button
UIButton * button = [ButtonArray objectAtIndex:btnRand];
//put image on that button
[button setImage:img forState:UIControlStateNormal];
[ButtonArray removeObjectAtIndex:btnRand];
NSLog(@"btnrnd: %i",btnRand);
NSLog(@"imgrnd: %i",imgRand);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9016422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Correct handling of exception: "getParameters failed (empty parameters)" I have a camera app in the Google Play store with Google Analytics installed. I keep getting the following crash report:
getParameters failed (empty parameters)
My question is: What is the correct way to handle this?
Looking into the Android source of where it happens didn't give me any extra details. The error is thrown in android_hardware_Camera.cpp:
String8 params8 = camera->getParameters();
if (params8.isEmpty()) {
jniThrowRuntimeException(env, "getParameters failed (empty parameters)");
return 0;
}
Looking into open source Android camera to see how it handles the situation was also not very helpful. That code doesn't appear to catch the RuntimeException when calling getParameters. (Except in one case where they catch it, close the camera, then rethrow it).
Is there a correct way to handle this?
If not, is there a reason this happens so often?
Note:
On any given day I have between 5k - 8k active users. With somewhere between 40-70 of these exceptions. That seems really high to me. I know there are legit instances where a camera may fail to initialize. But 1% of users seems unreasonable. Also, since the Android camera app doesn't handle the exception it really makes me wonder if there is some other root cause.
A: In my case I was getting this error :
getParameters failed (empty parameters)
when I called getParameters() after unlocking the camera. So, please call getParameters() before you call camera.unlock().
A: Is there a specific Android device that experiences this error? Or do you see it across many devices.
In general, you should not see this kind of an error. It's possible your application has some sort of race condition which results in this, but it'd have to involve trying to call getParameters on an uninitialized or already-released camera.
It could also be an error in the device-specific camera code, or a rare race condition somewhere in the camera code stack. Without more detail (logcat or Android bugreport from such a crash), it's impossible to tell - the error itself just says that the device-specific camera code returned an empty set of parameters.
But once you get this error, there's not a lot you can do - the camera subsystem is in some odd state. If you want to try to deal with it, all I can suggest is to close and reopen the camera device.
A: As +Eddy Talvala mentioned, this happens when the camera is in a bad state.
How does the camera get in a bad state?
1) Probably the most common reason would be closing/releasing the camera while still using it afterward. This can be especially problematic if you are using the Camera object on multiple threads without synchronizing access to the Camera. Make sure you only ever have a single thread accessing the Camera at a time.
2) In my case it was a bit more tricky. I use a SurfaceTexture so that I can use the camera output as an OpenGL texture. In Android 4.0 (ICS), there is a new method SurfaceTexture.release(). This method is important to use when using SurfaceTextures as it cleans up the memory quicker than it previously did.
The problem is that I was calling SurfaceTexture.release() while the camera preview was still active. This was crashing the Camera service, which was causing the issue explained in the question.
In my case I fixed it by delaying the call to SurfaceTexture.release() until after I had replaced it with a new SurfaceTexture. This way I was certain the SurfaceTexture could be cleaned up without any bad side-effects.
A: camera objects are always locked by default
so when you can unlock method then you allow to other procceses to use your parameters
so make sure that you re locked the camera before getting parameters
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14941625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
}
|
Q: Can't write data into Excel-Sheet using openpyxl Workbook I'm trying to write to specific cells in a Excel-Sheet using openpyxl Workbook. At first I couldn't write to cells that already had data in them and now I can't write at all (or I'm just going crazy).
Here's my code:
wb = load_workbook("..\\..\\Decision Tree Classifier TPS\\Decision Tree Classifier TPS\\TestData.xlsx")
ws1 = wb.get_sheet_by_name("Sheet1")
#this works
print(ws1.cell(row=1, column=1).value)
#these do not
ws1['D3'] = 5
ws1.cell(row=5, column=1).value = "SomeValue2"
ws1.cell(row=7, column=1,value='Hey')
ws1.cell(row=6, column=1).value = 'TEST'
wb.save("TestData.xlsx")
I get no errors, the print line works, the write lines do not.
Similar problem here Writing data into Excel-Sheet using openpyxl isn't working, except I have the save function.
What gives?
A: When you're saving workbook, provide full path, otherwise you will save it in a Python folder. I'm pretty sure that's where your Excel workbook with new data resides.
wb.save("..\\..\\Decision Tree Classifier TPS\\Decision Tree Classifier TPS\\TestData.xlsx")
Also, don't forget to close your workbook when you're done with it.
wb.close()
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56657204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How Scroll RecyclerView With MediaPlayer I have recyclerview in activity and mediaplayer. I want when play mediaplayer and when seekbar change position my recycleview scroll with him.befor i do for scrollbar and rigth work.but i can not do for recycler .
Please help me!?
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_matn);
public static void setAdapterLyric(List<Matn> matn) {
adapterLyrics = new AdapterLyrics(matn);
recyclerView.setAdapter(adapterLyrics);
}
and this my seekbar:
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
G.mediaPlayer.seekTo(i);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44150530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calculate position of projector I am projecting a rectangle on a table with a beamer and I want to calculate the absolute position of the beamer in the space from the destortion of this rectangle. I know the absolute position (in 3D) of all the corners of the rectangle that is projected on the table.
I dont know how to get started with this and cannot find much usefull info on the internet.
Can someone provide some tips please?
A: It depends on what you know. I'll choose the easiest:
If you know the position of the original rectangle, just find the intersection of the lines that go through the matching corners.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13961352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Animation/transition for Shiny conditionalPanel Shiny conditionalPanels just abruptly appear then disappear. Is there any way to make them slide or fade or otherwise gently transition?
A: Here is a way to fade the element when it is shown:
js <- "
$(document).ready(function(){
$('#plotContainer').on('show', function(event){
$(this).css('opacity', 0).animate({opacity: 1}, {duration: 1000});
});
});
"
ui <- fluidPage(
tags$head(tags$script(HTML(js))),
sidebarPanel(
actionButton("showplot", "Show")
),
mainPanel(
conditionalPanel(
condition = "input.showplot > 0",
id = "plotContainer",
plotOutput("plot")
)
)
)
server <- function(input, output) {
x <- rnorm(100)
y <- rnorm(100)
output$plot <- renderPlot({
plot(x, y)
})
}
shinyApp(ui, server)
EDIT
And also an effect on the hide event:
js <- "
$(document).ready(function(){
$('#plotContainer').on('show', function(){
$(this).css('opacity', 0).animate({opacity: 1}, {duration: 1000});
}).on('hide', function(){
var $this = $(this);
setTimeout(function(){
$this.show().hide(1000);
})
});
});
"
ui <- fluidPage(
tags$head(tags$script(HTML(js))),
sidebarPanel(
actionButton("showplot", "Show/Hide")
),
mainPanel(
conditionalPanel(
condition = "input.showplot % 2 == 1",
id = "plotContainer",
plotOutput("plot")
)
)
)
server <- function(input, output) {
x <- rnorm(100)
y <- rnorm(100)
output$plot <- renderPlot({
plot(x, y)
})
}
shinyApp(ui, server)
EDIT
Funny effects with the libraries Animate.css and jQuery-animateCSS:
js <- "
$(document).ready(function(){
$('#plotContainer').on('show', function(){
var $this = $(this);
$this.css('opacity', 0).
animate({opacity: 1}, 500, function(){
$this.animateCSS('jello', {
delay: 0,
duration: 2000
});
});
}).on('hide', function(){
var $this = $(this);
setTimeout(function(){
$this.show().animateCSS('heartBeat', {
delay: 0,
duration: 2000,
callback: function(){$this.hide(500);}
});
}, 0);
});
});
"
ui <- fluidPage(
tags$head(
tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.0/animate.compat.min.css"),
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/animateCSS/1.2.2/jquery.animatecss.min.js"),
tags$script(HTML(js))
),
sidebarPanel(
actionButton("showplot", "Show/Hide")
),
mainPanel(
conditionalPanel(
condition = "input.showplot % 2 == 1",
id = "plotContainer",
plotOutput("plot")
)
)
)
server <- function(input, output) {
x <- rnorm(100)
y <- rnorm(100)
output$plot <- renderPlot({
plot(x, y)
})
}
shinyApp(ui, server)
EDIT
I've done some convenient R functions to bind these animations in a Shiny app. Here is the code:
library(shiny)
animateCSS <- function(effect, delay = 0, duration = 500, then = NULL){
effect <- match.arg(effect, c(
"bounce",
"flash",
"pulse",
"rubberBand",
"shakeX",
"shakeY",
"headShake",
"swing",
"tada",
"wobble",
"jello",
"heartBeat",
"backInDown",
"backInLeft",
"backInRight",
"backInUp",
"backOutDown",
"backOutLeft",
"backOutRight",
"backOutUp",
"bounceIn",
"bounceInDown",
"bounceInLeft",
"bounceInRight",
"bounceInUp",
"bounceOut",
"bounceOutDown",
"bounceOutLeft",
"bounceOutRight",
"bounceOutUp",
"fadeIn",
"fadeInDown",
"fadeInDownBig",
"fadeInLeft",
"fadeInLeftBig",
"fadeInRight",
"fadeInRightBig",
"fadeInUp",
"fadeInUpBig",
"fadeInTopLeft",
"fadeInTopRight",
"fadeInBottomLeft",
"fadeInBottomRight",
"fadeOut",
"fadeOutDown",
"fadeOutDownBig",
"fadeOutLeft",
"fadeOutLeftBig",
"fadeOutRight",
"fadeOutRightBig",
"fadeOutUp",
"fadeOutUpBig",
"fadeOutTopLeft",
"fadeOutTopRight",
"fadeOutBottomRight",
"fadeOutBottomLeft",
"flip",
"flipInX",
"flipInY",
"flipOutX",
"flipOutY",
"lightSpeedInRight",
"lightSpeedInLeft",
"lightSpeedOutRight",
"lightSpeedOutLeft",
"rotateIn",
"rotateInDownLeft",
"rotateInDownRight",
"rotateInUpLeft",
"rotateInUpRight",
"rotateOut",
"rotateOutDownLeft",
"rotateOutDownRight",
"rotateOutUpLeft",
"rotateOutUpRight",
"hinge",
"jackInTheBox",
"rollIn",
"rollOut",
"zoomIn",
"zoomInDown",
"zoomInLeft",
"zoomInRight",
"zoomInUp",
"zoomOut",
"zoomOutDown",
"zoomOutLeft",
"zoomOutRight",
"zoomOutUp",
"slideInDown",
"slideInLeft",
"slideInRight",
"slideInUp",
"slideOutDown",
"slideOutLeft",
"slideOutRight",
"slideOutUp"
))
js <- paste(
" $this.animateCSS('%s', {",
" delay: %d,",
" duration: %d,",
" callback: function(){",
" %s",
" }",
" });",
sep = "\n"
)
sprintf(js, effect, delay, duration, ifelse(is.null(then), "", then))
}
onShowJS <- function(animation, fadeDuration){
sprintf(paste(
"$('#%%s>div').on('show', function(){",
" var $this = $(this);",
" $this.css('opacity', 0).animate({opacity: 1}, %d, function(){",
animation,
" });",
"});",
sep = "\n"
), fadeDuration)
}
onHideJS <- function(animation, fadeDuration){
paste(
"$('#%s>div').on('hide', function(){",
" var $this = $(this);",
" setTimeout(function(){",
sub(
"^(\\s.*?\\$this\\.animateCSS)",
"$this.show().animateCSS",
sub(
"\\{\n \n \\}",
sprintf("{$this.hide(%d);}", fadeDuration),
animation
)
),
" }, 0);",
"});",
sep = "\n"
)
}
animatedConditionalPanel <-
function(condition, ..., onShow = NULL, fadeIn = 600, onHide = NULL, fadeOut = 400){
id <- paste0("animateCSS-", stringi::stri_rand_strings(1, 15))
jsShow <- ifelse(!is.null(onShow), sprintf(onShowJS(onShow, fadeIn), id), "")
jsHide <- ifelse(!is.null(onHide), sprintf(onHideJS(onHide, fadeOut), id), "")
script <- tags$script(HTML(paste(jsShow,jsHide,sep="\n")))
condPanel <- conditionalPanel(condition, ...)
tags$div(id=id, tagList(condPanel, script))
}
You have to use animateCSS and animatedConditionalPanel only. The animateCSS function defines an animation. You can chain the animations with the then argument. The animatedConditionalPanel functions replaces conditionalPanel. Here is an example:
ui <- fluidPage(
tags$head(
tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.0/animate.compat.min.css"),
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/animateCSS/1.2.2/jquery.animatecss.min.js")
),
sidebarPanel(
actionButton("showplot", "Show/Hide")
),
mainPanel(
animatedConditionalPanel(
condition = "input.showplot % 2 == 0",
onShow = animateCSS("swing", duration = 1000, then = animateCSS("jello")),
fadeIn = 400,
onHide = animateCSS("pulse", then = animateCSS("bounce")),
plotOutput("plot")
)
)
)
server <- function(input, output) {
x <- rnorm(100)
y <- rnorm(100)
output$plot <- renderPlot({
plot(x, y)
})
}
shinyApp(ui, server)
UPDATE JUNE 2022
These animations will be available in the next version of the shinyGizmo package.
library(shiny)
library(shinyGizmo)
ui <- fluidPage(
sidebarPanel(
actionButton("showplot", "Show/Hide")
),
mainPanel(
fluidRow(
column(
10,
conditionalJS(
plotOutput("plot"),
condition = "input.showplot % 2 === 1",
jsCalls$animateVisibility("jello", "tada", duration = 1500)
)
),
column(2)
)
)
)
server <- function(input, output) {
x <- rnorm(100)
y <- rnorm(100)
output[["plot"]] <- renderPlot({
plot(x, y, pch = 19)
})
}
shinyApp(ui, server)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62972563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Java List I have the following method:
public static List<Integer> gradingStudents(List<Integer> grades) {
for(int i = 0; i < grades.size(); i++){
if(grades.get(i) < 40)
continue;
else if(grades.get(i) % 5 < 3)
grades.get(i) = grades.get(i) + (Math.abs(grades.get(i)%5-5));
else
continue;
}
return grades;
}
I get an unexpected type error at else if part. Why can't I change the element of grades, like I wrote in the code, above?
A: You cannot assign to grades.get(i).
I suggest you simplify your code as follows:
public static List<Integer> gradingStudents(List<Integer> grades) {
for(int i = 0; i < grades.size(); i++){
int grade = grades.get(i);
if (grade >= 40 && grade % 5 < 3) {
grades.set(i, grade + Math.abs(grade%5-5));
}
}
return grades;
}
A: It is because you are trying to modify the list like how you try to modify a list or dict in python as shown here. You have to use the inbuilt method .set() or .get(). set is used to add element by replacing it in the given index, add method adds the element to given index by pushing rest of the elements. You can understand more about the set and get method here
To this particular problem, as @Eran mentioned here, you can use the .set() method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65591638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: pandas str.replace is not working properly I want to replace specific Strings within another String in my .csv file.
While
import pandas
df = pandas.read_csv("file.csv", sep=";",encoding='iso-8859-1')
df['Column'] = df['Column'].str.replace('Corona', '')
is correctly removing the word Corona from Coronavirus,
df['Column'] = df['Column'].str.replace('\xc3\xa4', 'ä')
ist not working to replace the given String.
Where is the mistake?
A: Try this
data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65719102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When I store a bytearray with more than 100,000 index into the sqlite, I can only get 20 index of it while I select it from the table Here's what happen:
When I convert a bitmap into a bytearray, the bytearray stores more than 100,000 index, but when I use the SELECT function to get the bytearray, the bytearray have only 20 index left. What happen?
My field is using BLOB to store the bytearray, and the following code is what I'm trying to get the bytearray:
private void insertAttachmentRecord(int parentid) {
for(int k = 0; k < attachmentarray.size(); k++) {
byte[] claimAttachmentByteArray;
newAttachmentRecord = new ContentValues();
claimAttachmentByteArray = attachmentarray.get(k).getImageByteArray();
newAttachmentRecord.put("claimattachmentimage", claimAttachmentByteArray);
newAttachmentRecord.put("parent_id", parentid);
claiminfoDB.insert(DBATTACHMENT_TABLE, null, newAttachmentRecord);
}
}
And the query to get the bytearray:
private ArrayList<ClaimViewResult> GetClaimViewResult() {
ArrayList<ClaimViewResult> results = new ArrayList<>();
Cursor c2 = claiminfoDB.rawQuery("SELECT 'claimattachmentimage' FROM 'claimattachment' WHERE parent_id = "+bundletableId, null);
if (c2.getCount() != 0) {
c2.moveToFirst();
ClaimViewResult cvr = new ClaimViewResult();
byte[] imagebytearray = c2.getBlob(0);
Bitmap bitmap = BitmapFactory.decodeByteArray(imagebytearray, 0, imagebytearray.length);
cvr.setBitmap(bitmap);
cvr.setFilename(getFilename());
results.add(cvr);
while (c2.moveToNext()) {
cvr = new ClaimViewResult();
imagebytearray = c2.getBlob(0);
bitmap = BitmapFactory.decodeByteArray(imagebytearray, 0, imagebytearray.length);
cvr.setBitmap(bitmap);
cvr.setFilename(getFilename());
results.add(cvr);
}
}
return results;
}
Please help.
A: May be you need to change scheme for saving your bitmaps? For example, you can store bitmaps in inner app's directory and saving path to this image in database.
Also, you can try to change your select query like this:
SELECT * FROM your_table;
I think, you can receive only 20 bytes because you select word, not a column (I mean 'claimattachmentimage' in your query)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34260615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SL5 In Browser WebBrowser Control error "Trying to revoke a drop target that has not been registered" when re-navigating to another PDF Finally bit the bullet and replaced my hack for displaying PDF content inside a silverlight app with a proper SL5 Trusted In-Browser WebBrowser that navigates to a .pdf.
When i try to RE-navigate the WebBrowser to another PDF I am seeing the error "Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100)"
This only happens when I deploy to IIS (localhost IIS and another server IIS 7.5) ... NOT while running in VS2010.
Details:
UI is extremely simple. 1 Grid w/ 2 columns:
Column 1 Column2
======== ====================================================================
Treeview <WebBrowser x:Name="ContentWebBrowser" Grid.Column="1"></WebBrowser>
When user selects an item in the treeview, I simply call:
Uri serverUri = new Uri(string.Format("http://{0}:{1}/",
Application.Current.Host.Source.DnsSafeHost,
Application.Current.Host.Source.Port));
var relative= "/Content/x/y/z.pdf"; //This is dynamiclly pulled from Treeview, EDITED FOR SO
Uri relativeUri = new Uri(relative, UriKind.Relative);
ContentWebBrowser.Navigate(new Uri(serverUri, relativeUri));
With Cassini running silverlight both w/ and w/o debugger via VS2010 i can Select item after item in my list view and my WebBrowser will "re-navigate" calling this same code above.
BUT, once i deploy to my local iis, any time i end up calling Navigate for the 2nd time I am getting this error:
System.Exception: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100)
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.WebBrowser_Navigate(DependencyObject obj, Uri source)
at System.Windows.Controls.WebBrowser.Navigate(Uri source)
at SystemUtilities.Views.WebContentListView.TreeViewItem_Selected(Object sender, RoutedEventArgs e)
Other oddities: Sometimes i can "re-navigate" 3 or 4 times before i see this exception. Sometimes when i load another page in my SL application this error gets thrown. Happens whether PDF is cached or not cached when I load it into the WebBrowser. If i display standard html or an image instead of a PDF this does not happen.
Edit: I added logic to check to make sure LoadCompleted event fires before i try to re-navigate the WebBrowser but it does not seem to matter. (not 100% sure but i think that it ignores the fact that the PDF might still be loading and just signals that the DOM is ready). Although, even if I want a long time (30 seconds) after it looks like the 1st pdf is done loading, i still get the error.
Any suggestions?
New I posted my sample on skydrive.. check out the readme in order to repro!: http://sdrv.ms/JSn1KB
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10265104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using a delayed variable value to as a length value in a substring I am extracting note sets from a log file.
The line number of the header to a set in the file is found via FIND /V /N
The note set is delimited with a line containing only "@@@"
I use findstr to return this line which returns as 'xxx:@@@', e.g. '14:@@@' or '149:@@@' and so on.
in the snippet of code below, typical data for the variables on entry into the FOR/IN loop would be
*
*_ndelm = "@@@" ~ the delimiter marking the end of the note
*_infil = "notes.log" the file holding the dataset
*_atpos = the line position of the note header
During execution the local variables in the enabledelayedexpansion loop hold the following temporary values requiring !..! in the moment of processing:
*
*strel= the string delimiter line returned by findstr as above
*numel= the extracted line number from strel=='xxx', generally 1-4 chars long
*end = will become the (integer) line number of the delimiter line
In this code snippet the IF statements are needed to get around my problem: I can't find a way to use !end! in a single SET statement, so the workaround is 4 IFs.:
SET _ndelm=@@@
SET /a _atpos=1
FOR /f "usebackq tokens=1 delims=[]" %%i IN (`FINDSTR /b /l /n /c:%_ndelm% %_infil% `) DO (
SET strel=%%i
CALL stringlen %%i end & rem gets the character length of the delimiter line]
SET /a end-=4
IF [!end!] EQU [1] (SET numel=!strel:~0,1!)
IF [!end!] EQU [2] (SET numel=!strel:~0,2!)
IF [!end!] EQU [3] (SET numel=!strel:~0,3!)
IF [!end!] EQU [4] (SET numel=!strel:~0,4!)
SET /a end=!numel!
IF !end! GEQ %_atpos% GOTO fetchlines
)
Ideally, I would like to code something like this
(SET numel=!strel:~0,!end!!)
SET /a end=!numel!
I've hunted high and low to find a similar use case, but to no avail, and tried any number of combinations of %'s and !'s empirically.
If anyone has a syntax I could use ~ that would be great :-)
Thanks
file extract from the file:
11/01/2020 16:05:29.87 *** DONE *** All Batches [LEFiles needing /r]
find all batches that should not be run, apply the /r switch and amend
accordingly. Start at root and work down the main line before tackling the
side branches.
~ Main *** done ***
~ libs *** done ***
~ rest *** done ***
~
@@@
11/01/2020 15:18:47.02 >>> open >>> LEfiles runit [add a 'don't run!' switch]
some batches just can't be -or shouldn't be- run from the help system.
code a don't run switch [/r]=don't run
@@@
09/01/2020 10:12:52.83 *** DONE *** strcharrepl [bug] abend on "*" to " "
error message '= % was unexpected at this time.' after returning from a call to
nameFiledatetime which itself crashes on spaces - workaround for that needed
Suspect it's the same problem - returning a string with spaces is the generic
issue that needs a solution.
Maybe always return with quotes and then strip those?
~soln [strcharrepl] not much that can be done because redirection chars
always act in re-dir ways. Added notes to provide guidance in use.
~soln [zFN] surround filename with quotes and replace spaces with backslashes
before call, replace with spaces after.
@@@
A: For %%e in (!end!) Do set numel=!strel:~0,%%e!
The trick is to use a for loop parameter, because the parameter is expanded before the delayed expansion will be executed.
A: Thanks to the various contributors, the code snippet simplified to:
FOR /f "delims=:" %%i IN ('FINDSTR /b /l /n /c:%_ndelm% %_infil%') do (
set "end=%%i"
IF !end! GEQ %_atpos% GOTO fetchlines
)
which improved readability and performance.
The answer to the Question posed is the accepted answer from @Jeb.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59703305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Download multiple files with gevent I am trying to download a list of files in parallel, making use of [gevent][1]
My code is a slight modification of the code suggested here
monkey.patch_all()
def download_xbrl_files(download_folder, yq, list_of_xbrl_urls):
def download_and_save_file(url, yr, qtr):
if url is not None:
full_url = "http://edgar.sec.gov" + url
if not os.path.exists(full_url):
try:
content = urllib2.urlopen(full_url).read()
filename = download_folder + "/" + str(y) + "/" + q + "/" + url.split('/')[-1]
print "Saving: ", filename
f_raw = open(filename, "w")
f = FileObject(f_raw, "w")
try:
f.write(content)
finally:
f.close()
return 'Done'
except:
print "Warning: can't save or access for item:", url
return None
else:
return 'Exists'
else:
return None
(y, q) = yq
if utls.has_elements(list_of_xbrl_urls):
filter_for_none = filter(lambda x: x is not None, list_of_xbrl_urls)
no_duplicates = list(set(filter_for_none))
download_files = [gevent.spawn(lambda x: download_and_save_file(x, y, q), x) for x in no_duplicates]
gevent.joinall(download_files)
return 'completed'
else:
return 'empty'
What the code does is:
*
*after some cleaning
*gevent.spawn spawns download_and_save_file which:
*checks if the file has been already downloaded
*if not, downloads the content with urllib2.urlopen(full_url).read()
*saves the file with the help of gevent's FileObject
I have the impression that the download_and_save only works sequentially. Furthermore, my application gets in a stand-by. I could add a timeout but I wanted to handle failures gracefully within my code.
Wondering if I am doing something wrong - it's the first time I write code in python.
EDIT
Here is a version of the code using "Threads"
def download_xbrl_files(download_folder, yq_and_url):
(yq, url) = yq_and_url
(yr, qtr) = yq
if url is not None and url is not '':
full_url = "http://edgar.sec.gov" + url
filename = download_folder + "/" + str(yr) + "/" + qtr + "/" + url.split('/')[-1]
if not os.path.exists(filename):
try:
content = urllib2.urlopen(full_url).read()
print "Saving: ", filename
f = open(filename, "wb")
try:
f.write(content)
print "Writing done: ", filename
finally:
f.close()
return 'Done'
except:
print "Warning: can't save or access for item:", url
return None
else:
print "Exists: ", filename
return 'Exists'
else:
return None
def download_filings(download_folder, yq_and_filings):
threads = [threading.Thread(target=download_xbrl_files, args=(download_folder, x,)) for x in yq_and_filings]
[thread.start() for thread in threads]
[thread.join() for thread in threads]
A: I looked into this a little deeper the basic problem is that gevent.spawn() creates greenlets not processes (all greenlets run in a single OS thread).
Try a simple:
import gevent
from time import sleep
g = [gevent.spawn(sleep, 1) for x in range(100)]
gevent.joinall(g)
You'll see the time this takes is 100s. Which proves the point above.
You are really looking for multithreading which can be found in the threading module.
Have a look at the the question at: How to use threading in Python?. For a little how to.
---update---
Here is a quick example of how you might do this:
threads = [threading.Thread(target=sleep, args=(1,)) for x in range(10)]
[thread.start() for thread in threads]
[thread.join() for thread in threads]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23823257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there an alternative to .toggle() that will let me control on/off? I am developing a portfolio website and I want to be able to tag items in the page that displays work so you can toggle visibility. I have it set up with .toggle() right now, which works, except that if I want to use multiple tags, it throws off other tags. You an see this is action on my site - http://nu-creative.com/ourwork.html
On the left, you can toggle both branding and case studies, but the third image is tagged as both, so when you click one after the other it hides it when it should show it and vice versa.
The code is all in the bottom of the page but a snippet of the relevant jQuery is here:
$("#branding").click(function () {
$(this).toggleClass("showItem");
$(".brandingHide").toggle("slow", function () {
});
});
$("#case").click(function () {
$(this).toggleClass("showItem");
$(".caseHide").toggle("slow", function () {
});
});
Then the <-li> has the appropriate ID and the class is on the div in the grid that hides. I could make it work if I had two buttons - a hide and a show, but that would be weird. I could also hack it by making the grey a seperate layer so that when you click again you are actually clicking a different item which then disappears and exposes the show button again. There must be a better way, though!
Thanks in advance!
Solution
http://jsfiddle.net/ngau3xjL/5/
A: You just have to complete your animation logic. The advantage of this approach is its more verbose but still only one DOM lookup.
$("#branding").click(function () {
var $element = $(this);
var isVisible = $element.hasClass('showItem');
if(isVisible)
$element.removeClass("showItem");
} else {
$element.addClass("showItem");
}
});
http://jsfiddle.net/ngau3xjL/4/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27260947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AS3 safe downloaded file directly to specified folder May be some body have FLA file which download file to folder (without dialog of save file).
Just Click to - DOWNLOAD -> file save to folder /update on swf located. (without any confirmation of filename or filder location)
var fileName:String = "upgrade.zip";
var request:URLRequest = new URLRequest();
request.url = DOWNLOAD_URL;
var params:URLVariables = new URLVariables();
fr.download(request,fileName);
This change filename in dialog only, but dialog must to be auto-agreed.
And more one. When I try to make AS3 script, for download via URLRequest, this work only in Flash editor. FLA file (when I comp[ile to SWF -> not work).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29263001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Accordion and Dialog components for Material Design Lite Are there any accordion and modal dialog components available and actually work that are compatible with my environment of:
Google's Material Design Lite version 1.06
Facebook's ReactJS 0.14.2
Microsoft's TypeScript and Visual Studio 2015 (for typescript bundling)
I am trying to avoid JavaScript library bloat and Material Design Lite is missing these essential widgets. I'm not using Node.js since I'm on a Windows platform so Material-UI is not an option. MaterializeCSS bloats my Visual Studio project and makes it really slow and unusable.
A: Update Sep 28,2016
It looks like there is now an open-source library for doing just this: https://github.com/fiffty/react-treeview-mui
Self Implementation
This answer serves as an example for an Accordion dropdown built using React, though not styled as Material Design. You would need to do that yourself.
This setup requires a hierarchy object of parent > child objects/arrays. This base class should be able to handle very deep depths just fine. It uses recursion for its structure setup. I'll also be using ES6 syntax for preference, as it helps setup the recursion easier for me.
Accordion Class:
// Accordian Class
// Dynamic/Recursive
// a parent>child>child... relationship is required
// the whole object can be named however you like,
// but each child object needs to be identified as "children"
class Accordian extends React.Component {
constructor(props) {
super(props);
this.state = {
openLevelRow: "", // this is the current open level row in an accordian (starts out with none being open)
selfLevelObject: props.newLevel // the current level object containing all rows and their data/children
};
}
// This is our toggle open/close method
// if row is already open, close it
// uniqueSelector is unique per row, and also a key
// in the selfLevelObject (could be a name, id)
toggleOpenClose(uniqueSelector) {
// simple ternary assignment
this.setState({
openLevelRow: this.state.openLevelRow != uniqueSelector ? uniqueSelector : ""
});
}
render () {
// deconstruct assignment from state
const { selfLevelObject, openLevelRow } = this.state
return (
<div>
{selfLevelObject.map((row, i) =>
{/* Collectively where all children of the same hierchy level are listed*/}
<div className="accordian-hold-self-level" key={i} >
{/* This is an individual collapsable Row */}
<div onClick={this.toggleOpenClose.bind(this, row.uniqueSelector)} className="accordian-title-row">
<p className='accordian-title'> {row.title}</p>
</div>
{/*
When iterating the list, find out if a row has been opened
*/}
{this.state.openLevelRow != row.uniqueSelector ? <span></span> :
/*
This code block is called if the current row is opened
now we to need to find out if there are children,
if not, then we are at the bottom, do what ever
you'd like with the bottom row
*/
selfLevelObject[uniqueSelector].children != undefined ?
<Accordian newLevel={selfLevelObject[uniqueSelector].children} />
: // else
// TODO - whatever you want with bottom row
}
</div>
)}
</div>
);
}
}
Accordian.propTypes = {
newLevel: React.PropTypes.object
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34998630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: visual studio backward compatibility Hi there I have build a project with visual studio 2010 but I now need to open it using an older version vs2008. Is this possible by just changing the target framework to .net 3.5?
A: In my experience, VS2008 can open VS2010 project files if there aren't VS2010-specific bits in it - so simple class libraries or console apps are fine, for example. There will be a warning that the tools version is unknown, but it will basically work. (You'll still need to target .NET 3.5, I believe - I haven't tried opening a .NET 4 project in VS2008, but I wouldn't really expect it to work, at least not if it uses new language features.)
Where I've used this approach, I've had two different solution files - one for VS2008 and one for VS2010, both including the same projects. That way both can open without any problems, and without any conversion prompts. So far it's worked fine.
As I say, that's my experience - YMMV.
A: I was able to open a project file created in VS2010 by simply opening it in VS2008. I was then able to go into Project Properties and set the target framework - just be sure to check the Build settings too, as 2010 is version 4, which isn't supported in 2008.
In my particular case, I targeted Framework v2.0, which involved removing unused LINQ references. The project compiled happily, and I was able to run the app.
A: No, the project file format has been extended.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2780464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Doctype for html email Which DOCTYPE is the right one for HTML email?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
A: There is only minor differences these days in DOCTYPE declarations in html email. Although only minor, it is still recommended to test your emails via Email on Acid or Litmus or any other testing software prior to a send to ensure cross client compatibility and to find any unforeseen quirks.
The larger issues comes with if you do not declare a doctype or body tag, it can really screw up different parts of the email on certain clients.
The most popular DOCTYPE nowadays is the HTML 5 doctype (<!DOCTYPE HTML>) which is used with very little hiccups. The most popular/safest doctype used to be the <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> doctype. This can still be used, but may limit different capabilities of your email, as it is referencing an older version of HTML.
See this forum post in litmus for more in-depth information on this: https://litmus.com/community/discussions/39-explanation-of-doctype-html-attributes-and-meta-tags-in-email-head
A: This is what I use.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
I code emails daily and this came as the header that exact target (salesforce) provided us. Our company has sister brands and this what they all use as well so I'm assuming this is standard.
A: More primitive email readers cannot handle DOCTYPE at all, and instead either strip it completely out of the email, or just remove the string "!DOCTYPE" and leave the rest of the HTML intact. You wind up seeing weird things like this at the beginning of the emails:
< HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
...because the word !DOCTYPE was removed, but not the rest, and since it did not remove the space, it displayed the broken code to the reader.
The rest of the email will usually display just fine.
While this obviously is a programming error by the writer of the script, I have seen a lot of scripts with this same exact error. It's usually because they are simply stripping out HTML tags and not allowing !DOCTYPE.
Email clients seem to be able to process your email without it unless you are using a different character set than the user, and sometimes stumble when you declare it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34319889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How does the method know what array need to be checked? If I have 2 classes that extend from this container class, one that can only alter the list container and the other that can only alter the set container. How would the isEmpty() method be able to know which container to check? This is a lab for class so I'm not allowed to change any of the code already given to me.
public class Container {
// Do not change the value of the following constants.
protected final int ORIGINAL_SIZE = 10;
protected Object[] list; // is a container that stores the element of MyList
protected Object[] set; // is a container that stores the element of MySet
protected int size; // this variable holds the actual number of elements that are stored in either of the containers (i.e. MyList or MySet).
/**
* This method returns true if the container is empty.
* @return It returns true if the container is empty, otherwise false.
*/
boolean isEmpty() {
return true;
}
}
class MyList extends Container{
public MyList () {
list= new Object[ORIGINAL_SIZE];
size = 0;
}
}
class MySet extends Container{
public MySet() {
set = new Object[ORIGINAL_SIZE];
size = 0;
}
}
A: You need to override the isEmpty method on the respective sub classes, and then it's clear to which collection they refer:
class MyList extends Container {
public MyList() {
list = new Object[ORIGINAL_SIZE];
size = 0;
}
@Override
public boolean isEmpty() {
return size > 0;
}
}
Here you need to maintain the size variable each time you modify (add to or remove from) the list.
(Same for the set implementation, just using set instead of list.)
The whole thing is a bit of a weird class design. The Container base class should not have list and set, these should be in the respective child classes MyList and MySet, so that everything is defined where it's used (only).
A: You don't need to check either container. Override the isEmpty() method in both classes to check the size field. As elements are added or removed to either array, increment or decrement the size accordingly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71355631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: simple Tkinter program - window vanishes after clicking button - maintop problem? Coders,
I guess I have a newbie question: my windows disappears when I click on a button. If I put in root.mainloop() as last line in the buttonClicked-function, then the program is fine - but it looks not right...what is wrong here?
import tkinter as tk
def buttonClicked(event):
print(tf1.get())
tf1Content.set("button clicked")
# root.mainloop() ... would work
root = tk.Tk()
frame = tk.Frame(root, relief="ridge", borderwidth=2)
frame.pack(fill="both",expand=1)
label = tk.Label(frame, text="Input:")
label.pack(expand=1)
tf1Content = tk.StringVar()
tf1 = tk.Entry(frame, text="input here", textvariable=tf1Content)
tf1.pack(expand=1)
bOk = tk.Button(frame,text="OK",command=root.destroy)
bOk.bind("<Button-1>", buttonClicked)
bOk.widget = "bOK"
bOk.pack(side="bottom")
tf1.focus()
root.mainloop()
A: It turns out that you just copied this line:
bOk = tk.Button(frame,text="OK",command=root.destroy)
which binds a call to root.destroy() to the button press.
The fix is to just remove the command parameter:
bOk = tk.Button(frame,text="OK")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71056814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Capistrano: Override shared_dir variable First off, very new to Capistrano, so excuse my newbness.
I am deploying a CodeIgniter application of which I have a data folder that lives outside the current web directory that I am trying to symlink to. This is what I have used to create the symlink
set :shared_dir, %w(/var/www/website/)
set :linked_dirs, %w{43b621acdfc9523443f27b7767e}
This is the result of the deployed application
43b621acdfc9523443f27b7767e -> /var/www/website/shared/43b621acdfc9523443f27b7767e
My goal is to override the shared_dir variable to generate a symlink of
/var/www/website/43b621acdfc9523443f27b7767e
I am using Capistrano 3. Any insight greatly appreciated.
Thanks
A: You can create an specific task to take care of creating and updating the symlink from anywhere in your application to anywhere in your system on each deploy. For example:
namespace :terminal do
task :link_external_dir, :except => { :no_release => true } do
capifony_pretty_print '--> Generating soft link with external_example_dir'
run "sharedWebDir=#{shared_path}/web; cd $sharedWebDir; if [ -d $sharedWebDir/internal_example_dir -o -f $sharedWebDir/internal_example_dir ]; then rm -rf $sharedWebDir/internal_example_dir; fi; if [ ! -L $sharedWebDir/internal_example_dir ]; then ln -s /srv/example/vhost/external_example_dir $sharedWebDir/internal_example_dir; fi;"
capifony_puts_ok
end
task :rm_shared_example_dir, :except => { :no_release => true } do
capifony_pretty_print '--> Removing sharedDir/internal_example_dir symlink'
run "sharedWebDir=#{shared_path}/internal_example_dir; if [ -L $sharedWebDir/internal_example_dir ]; then rm $sharedWebDir/internal_example_dir; fi;"
capifony_puts_ok
end
end
Now call each function on each deploy:
before "deploy", "terminal:rm_shared_example_dir"
after "deploy", "deploy:cleanup"
after "deploy", "terminal:link_external_dir"
What we are trying to accomplish is:
1.Before Deploy, remove the file from your main sharedDir that links to your external dir.
REMOVE
/var/www/website/shared/externalDir -> /srv/example/vhost/external_example_dir
2.Deploy your app.
3.Generate the custom symlink again.
ln -s /srv/example/vhost/external_example_dir $sharedWebDir/internal_example_dir
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29710825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Swift convert string to date output wrong date I want to convert dateStartString = “28/02/2018” in to Date and compare that converted date with today date. when i convert dateStartString the converted date is "2018-02-27 18:30:00 UTC".why its output is wrong date?
here is my code
var dateStartString = "28/02/2018"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
guard let dateStartDate = dateFormatter.date(from: dateStartString) else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
let dateToday = Date()
if(dateStartDate>=dateToday){
print("Yes")
}
else{
print("Today date is 28/02/2018. Why it print No?")
}
Hope you understand my problem.
Thanks in advance.
A: You need to understand that Date does not only represent a date, but also a time.
>= compares both date and time components of a Date object. Since you didn't specified any time in your date string, the API assumed it to be 00:00:00 in your local time, which is 18:30:00 of the previous day in UTC. Why UTC, you ask? That's what the description of the date always is. When you print a date, it always prints it in UTC time. To print it in your time zone, set the timeZone property of your date formatter and format it.
One way to only compare the date components is by removing the time components. From this answer, this is how you remove time components:
public func removeTimeStamp(fromDate: Date) -> Date {
guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: fromDate)) else {
fatalError("Failed to strip time from Date object")
}
return date
}
Now this should be true:
dateStartDate >= removeTimeStamp(fromDate: dateToday)
A: As Sweeper explained, dateStartDate is at 00:00 of 28/02/2018,
whereas dateToday is the current point in time, which is
on the same day, but after midnight. Therefore dateStartDate >= dateToday evaluates to false.
To compare the timestamps only to day granularity and ignore the
time components you can use
if Calendar.current.compare(dateStartDate, to: dateToday, toGranularity: .day) != .orderedAscending {
print("Yes")
}
This will print "Yes" if dateStartDate is on the same or a later
day than dateToday.
The compare method returns .orderedAscending, .orderedSame,
or .orderedDescending, depending on wether the first date is on
a previous day, the same day, or a later day, than the second date.
A: try to set your current date Formatter while comapring date.
Below your sample code update:
var dateStartString = "28/02/2018"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.locale = NSLocale.current
guard let dateStartDate = dateFormatter.date(from: dateStartString) else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
var dateToday = Date()
print(dateToday)
let dateTodaystr = dateFormatter.string(from: dateToday)
dateToday = dateFormatter.date(from: dateTodaystr)!
print(dateToday)
if(dateStartDate>=dateToday){
print("Yes")
}
else{
print("Today date is 28/02/2018. Why it print No?")
}
A: You need to timeZone for your dateFormatter:
dateFormatter.timeZone = TimeZone(secondsFromGMT:0)!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49023814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to bypass onCompleted I use BehaviorSubject to make a stream of events from different sources.
Being simplified, It look like that:
BehaviorSubject subject = BehaviorSubject.create();
Observable<Integer> src1 = Observable.just(1, 2, 3);
Observable<Integer> src2 = Observable.just(4, 5, 6);
Observable<Integer> src3 = Observable.just(7, 8, 9);
src1.subscribe(subject);
src2.subscribe(subject);
src3.subscribe(subject);
subject.subscribe(this::log);
In this example values from src1 only will be logged, because no more subject subscription will exists after src1 completion.
How could I bypass completion events from all the sources? Is there an operator like ignoreCompleted()?
A: Use this, it ignores onComplete() and onError(): https://github.com/JakeWharton/RxRelay
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43427288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC4 403 forbidden error with siteminder We have a MVC4 application running on a windows server 2008 with iis 7.5. everything was running fine until out SSO team installed siteminder for single sign on.
Now the application after the SSO redirect is giving a 403 forbidden error. Any Suggestions?
Here's what is happening.
1. access the site.
2. Site redirects to SSO page
3. after entering the credentials (everything is validated as the siteminder trace and logs is showing no errors)
4. application redirects the original entered url and we see a 403.
we currently have no implementation that uses the SSO user coz we were waiting for the SSO to be setup and our current authentication in web config is set to "None"
application was all good before the siteminder and the url was accessible.
Verified everything but not sure what is the issue.
1. Application pool is set to 4.0
2. TestConnection is ok for authorization and authentication
3. No errors in siteminder logs (the SM cookie is set correctly)
4. We do not have SSL
5. this is the only site running on the server
6. IIS_IUSRS is given access to the sites root folder
Not sure if there is anything we can do in the sites web config. though as i have mentioned before it was all ok before site minder. Now Even if we disable the siteminder the application just return 403 forbidden.
please help!!
A: well we finally reached out to some people with extensive siteminder experience and they suggested to use the "classic" app pool instead of "Integrated" which solved our issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32960063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.