id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23528600
|
I'm adding manually conditions for this operation
exports.saveuser = async (req, res) => {
const { first_name, email } = req.body;
if (!first_name || !email)
return res.status(401).json({ error: 'All the data require' });
const user = User.findOne({ email });
if (user) {
return res.status(401).json({ error: 'Email already exist' });
}
const user = new User({
first_name,
email,
});
await user.save();
};
in the above code, I add conditions manually, but I don't want to add all the conditions every time.
A: You can follow express Validator. It pretty industry standard. https://express-validator.github.io/docs/
Below is the example:
router.PUT(
`/api/user`,
auth,
validate(UserValidator.saveUser),
UserController.saveUser,
);
| |
doc_23528601
|
Using "-monitor" command-line argument i can get only input filenames.
A: Updated Answer
The simplest, and most direct, way of doing this is to use the -verbose option as follows:
convert rose: rose: rose: -verbose image_%04d.png
rose:=>image_0000.png[0] PPM 70x46 70x46+0+0 8-bit sRGB 6.97KB 0.000u 0:00.000
rose:=>image_0001.png[1] PPM 70x46 70x46+0+0 8-bit sRGB 6.97KB 0.000u 0:00.000
rose:=>image_0002.png[2] PPM 70x46 70x46+0+0 8-bit sRGB 6.97KB 0.000u 0:00.000
It took several iterations and far too much dinking around for me to get there, but I'll leave my earlier ideas below in case anyone wants to try out some "off the wall" and, let's say, "contrived", ways of doing similar things...
Option 1
You can use the %p escape sequence and -format and +identify like this:
convert rose: rose: rose: -format "image_%p.png\n" -identify image_%04d.png
image_0.png
image_1.png
image_2.png
Yes, I know it's not quite perfect, but it may be good enough to get you started.
Option 2
This might be another option:
convert rose: rose: rose: -verbose +identify 'rose-%04d.png' | grep png
rose:=>rose-0000.png[0] PPM 70x46 70x46+0+0 8-bit sRGB 7.06KB 0.000u 0:00.000
rose:=>rose-0001.png[1] PPM 70x46 70x46+0+0 8-bit sRGB 7.06KB 0.000u 0:00.000
rose:=>rose-0002.png[2] PPM 70x46 70x46+0+0 8-bit sRGB 7.06KB 0.000u 0:00.000
Option 3
convert -debug "Trace" rose: rose: rose: image_%04d.png 2>&1 | grep "\.png" | sort -u
image_%04d.png
image_0000.png
image_0001.png
image_0002.png
Option 4
Yet another option might be to create a file to mark the current time, and then run your command and find any newer files than the one you created before you started:
touch b4; sleep 1; convert rose: rose: rose: image_%04d.png
find . -newer b4
./image_0000.png
./image_0001.png
./image_0002.png
Option 5
Yet another option using the %o (output filename) escape you suggest - along with -verbose
convert rose: rose: rose: -format "%o" -verbose -identify image_%04d.png
rose:=>image_0000.png[0] PPM 70x46 70x46+0+0 8-bit sRGB 6.97KB 0.000u 0:00.000
rose:=>image_0001.png[1] PPM 70x46 70x46+0+0 8-bit sRGB 6.97KB 0.000u 0:00.000
rose:=>image_0002.png[2] PPM 70x46 70x46+0+0 8-bit sRGB 6.97KB 0.000u 0:00.000
A: Expanding on Mark Setchel answer, I did this to get the file names:
FILES=( $(
convert <arguments> \
-format "%o\n" -verbose -identify \
<output> \
2>&1 > /dev/null | sed -nEe 's/.*=>(.*)\[.*/\1/p'
) )
For example:
$ FILES=( $(
convert rose: \
\( -clone 0 -modulate 100,100,33.3 \) \
\( -clone 0 -modulate 100,100,66.6 \) \
-format "%o\n" -verbose -identify \
rose.png \
2>&1 > /dev/null | sed -nEe 's/.*=>(.*)\[.*/\1/p'
) )
$ echo ${FILES[0]}
rose-0.png
$ echo ${FILES[1]}
rose-1.png
$ echo ${FILES[2]}
rose-2.png
$ echo ${#FILES[@]}
3
A: This is more of a workaround... If you use a variable to specify the output ahead of time, you can get the output from the variable. Here's an example using a shell script:
#!/bin/bash
export fn="fuzzy-magick"
export inp="$fn.png"
export outp="$fn.gif"
convert $inp $outp
echo "Output was "$outp
| |
doc_23528602
|
A: The following snippet creates a 100x100 masking item and then a loader that uses that item for it's mask. After the loader is created, a URL is called to populate the loader, then the loader is added to the stage.
import flash.display.*;
import flash.net.URLRequest;
var rect:Shape = new Shape();
rect.graphics.beginFill(0xFFFFFF);
rect.graphics.drawRect(0, 0, 100, 100);
rect.graphics.endFill();
addChild(rect);
var ldr:Loader = new Loader();
ldr.mask = rect;
var url:String = "http://www.unknown.example.com/content.jpg";
var urlReq:URLRequest = new URLRequest(url);
ldr.load(urlReq);
addChild(ldr);
This example came straight from the Adobe docs. http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/display/Loader.html
A: Alternatively you can use the image tag.
<mx:image id="img" source="http://foo.com/bar.png"/>
| |
doc_23528603
|
<div class="footer-btm">
Thanks for watching
<div class="loading">
<span></span>
<span></span>
<span></span>
</div>
</div>
<style>
.loading span{
width: 15px;
height: 15px;
margin: 0 5px;
background-color: #ffd957;
border-radius: 50%;
display: inline-block;
animation-name: dots;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
.loading span:nth-child(2){
background-color: #57ffa0;
animation-delay: 0.4s;
}
.loading span:nth-child(3){
background-color: #ff8b57;
animation-delay: 0.8s;
}
@keyframes dots{
50%{
opacity: 0;
transform: scale(0.7) translateY(10px);
}
}
</style>
i am following this https://youtu.be/aglMDLGeXnc tutorial to develop this thing
A: You've forgotten the animation-duration attribute:
animation-name: dots;
animation-duration: 2s;
animation-iteration-count: infinite;
Add this, and the dots will appear/disappear properly.
| |
doc_23528604
|
my intention to keep the data based on the sheet name, i have tried with loop but it take long time for processing.
wb.Activate
wb.Sheets("PMCC 1").Select
For Each ws In wb.Worksheets
ws.Activate
index = index + 1
If index <= 10 Then
irow = ws.Cells(Rows.Count, 1).End(xlUp).Row
newtemp = Replace(ws.Name, " ", "#0")
For J = irow To 2 Step -1
If ws.Cells(J, 1) <> newtemp Then
ws.Cells(J, 1).EntireRow.Delete
End If
Next J
Else
irow = ws.Cells(Rows.Count, 1).End(xlUp).Row
newtemp = Replace(ws.Name, " ", "#")
For J = irow To 2 Step -1
If ws.Cells(J, 1) <> newtemp Then
ws.Cells(J, 1).EntireRow.Delete
End If
Next J
End If
Next ws
MsgBox ("Deleted")
A: You can modify & try this solution:
Option Explicit
Sub test()
Dim ws As Worksheet
Dim LastRow As Long, Index As Long, j As Long
Dim newtemp As String
For Each ws In ThisWorkbook.Worksheets
Index = Index + 1
With ws
If Index <= 10 Then
newtemp = Replace(.Name, " ", "#0")
Else
newtemp = Replace(.Name, " ", "#")
End If
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For j = LastRow To 2 Step -1
If .Cells(j, 1) <> newtemp Then
.Rows(j).EntireRow.Delete
End If
Next j
End With
Next ws
MsgBox ("Deleted")
End Sub
| |
doc_23528605
|
I am having trouble with the protractor tests. I'm not clear on what changes I should make to the old AngularJS test to make it compatible with Angular 5.
If anyone has experience of this and could point me in the right direction it would be appreciated.
Existing AngularJS code...
**// card.template.html**
<article class="rt-card">
<header class="rt-card__header">
<h1 data-ng-transclude="title"
class="rt-card__title"
data-rt-id="{{::$ctrl.rtId}}Title"></h1>
</header>
<section data-ng-transclude="content"
class="rt-card__content"
data-rt-id="{{::$ctrl.rtId}}Content"></section>
<footer data-ng-transclude="link"
class="rt-card__footer"
data-rt-id="{{::$ctrl.rtId}}Footer"></footer>
</article>
**// card.component.ts**
import * as main from "../../common/main";
main.module.component('rtCard', {
template: require('./card.template.html'),
bindings: {
rtId: '@'
},
transclude: {
'title': 'rtCardTitle',
'content': 'rtCardContent',
'link': 'rtCardLink'
}
});
// Test Files
**// card.page.ts *Test File***
import {browser} from 'protractor';
import {CardComponent} from './card.component';
export default class CardPage {
public readonly defaultCard: CardComponent = new CardComponent(`[data-rt-id='default-card']`);
constructor() {
browser.get('#/components/card');
}
}
**// card.component.ts *Test File***
import {element, by, ElementFinder} from 'protractor';
import {promise} from "selenium-webdriver";
export interface ICard {
isPresent(): promise.Promise<boolean>;
getTitleText(): promise.Promise<string>;
}
export class CardComponent implements ICard {
private readonly titleElementSelector: string = '.rt-card__title';
private readonly contentElementSelector: string = '.rt-card__content > rt-card-content';
private readonly linkElementSelector: string = '.rt-card__footer > rt-card-link > a';
private component: ElementFinder;
constructor(selector: string) {
this.component = element(by.css(`rt-card${selector}`));
}
isPresent(): promise.Promise<boolean> {
return this.component.isPresent();
}
getTitleText(): promise.Promise<string> {
return this.component.element(by.css(this.titleElementSelector)).getText().then((text) => {
return text ? text.trim() : '';
});
}
getContentHtml(): promise.Promise<string> {
return this.component.element(by.css(this.contentElementSelector)).getAttribute('innerHTML').then((html: string) => {
return html.trim();
});
}
getLinkText(): promise.Promise<string> {
return this.component.element(by.css(this.linkElementSelector)).getText();
}
getLinkUrl(): promise.Promise<string> {
return this.component.element(by.css(this.linkElementSelector)).getAttribute('href');
}
}
**// card.spec.functional.ts**
import CardPage from './card.page';
let page;
describe('Card', () => {
beforeAll(() => {
page = new CardPage();
});
it('should be available on the page', () => {
expect(page.defaultCard.isPresent()).toBe(true, `Can't find the default card`);
});
it('should contain the correct title text', () => {
expect(page.defaultCard.getTitleText()).toEqual('Time off', `Title text is not correct`);
});
it('should contain the correct content', () => {
expect(page.defaultCard.getContentHtml()).toEqual(`<span>0 hours available</span>`, `Content HTML is not correct`);
});
it('should contain the correct link', () => {
expect(page.defaultCard.getLinkText()).toEqual(`Go to time off`, `Link text is not correct`);
expect(page.defaultCard.getLinkUrl()).toEqual(`http://www.google.com/`, `Link URL is not correct`);
});
});
Angular 5 code...
**// card.component.html**
<article class="rt-card">
<header class="rt-card__header">
<h1 class="rt-card__title"
[attr.data-rt-id]="rtId + 'Title'">
<ng-content select="rt-card-title"></ng-content>
</h1>
</header>
<section class="rt-card__content"
[attr.data-rt-id]="rtId + 'Content'">
<ng-content select="rt-card-content"></ng-content>
</section>
<footer class="rt-card__footer"
[attr.data-rt-id]="rtId + 'Footer'">
<ng-content select="rt-card-footer"></ng-content>
</footer>
</article>
**// card.component.ts**
import { Component, Input, OnInit } from '@angular/core';
// import './card.component.scss';
@Component({
selector: 'rt-card',
templateUrl: './card.component.html'
})
export class CardComponent implements OnInit {
@Input() rtId: string;
constructor() { }
ngOnInit() {
if (!this.rtId) {
console.error(`The attribute 'rtId' is mandatory for rt-card`);
}
}
}
**// card.page.ts *Test File***
import {browser} from 'protractor';
import {CardComponent} from './card.component';
export default class CardPage {
public readonly defaultCard: CardComponent = new CardComponent(`[data-rt-id='default-card']`);
constructor() {
browser.get('card');
}
}
**// card.component.ts *Test File***
import {element, by, ElementFinder} from 'protractor';
import {promise} from 'selenium-webdriver';
export interface ICard {
isPresent(): promise.Promise<boolean>;
getTitleText(): promise.Promise<string>;
}
export class CardComponent implements ICard {
private readonly titleElementSelector: string = '.rt-card__title > rt-card-title';
private readonly contentElementSelector: string = '.rt-card__content > rt-card-content';
private readonly footerElementSelector: string = '.rt-card__footer > rt-card-footer > a';
private component: ElementFinder;
constructor(selector: string) {
this.component = element(by.css(`rt-card${selector}`));
}
isPresent(): promise.Promise<boolean> {
return this.component.isPresent();
}
getTitleText(): promise.Promise<string> {
return this.component.element(by.css(this.titleElementSelector)).getText().then((text) => {
return text ? text.trim() : '';
});
}
getContentHtml(): promise.Promise<string> {
return this.component.element(by.css(this.contentElementSelector)).getAttribute('innerHTML').then((html: string) => {
return html.trim();
});
}
getLinkText(): promise.Promise<string> {
return this.component.element(by.css(this.footerElementSelector)).getText();
}
getLinkUrl(): promise.Promise<string> {
return this.component.element(by.css(this.footerElementSelector)).getAttribute('href');
}
}
**// card.e2e-spec-protractor.ts *Test File***
import CardPage from './card.page';
let page;
fdescribe('Card', () => {
beforeAll(() => {
page = new CardPage();
});
it('should be available on the page', () => {
expect(page.defaultCard.isPresent()).toBe(true, `Can't find the default card`);
});
it('should contain the correct title text', () => {
expect(page.defaultCard.getTitleText()).toEqual('Time off', `Title text is not correct`);
});
it('should contain the correct content', () => {
expect(page.defaultCard.getContentHtml()).toEqual(`<span>16 hours available</span>`, `Content HTML is not correct`);
});
it('should contain the correct link in the footer', () => {
expect(page.defaultCard.getLinkText()).toEqual(`Go to time off`, `Link text is not correct`);
expect(page.defaultCard.getLinkUrl()).toEqual(`http://www.rt.com/`, `Link URL is not correct`);
});
});
Test Failures - Terminal
**************************************************
* Failures *
**************************************************
1) Card should be available on the page
- Failed: invalid selector: An invalid or illegal selector was specified
(Session info: chrome=67.0.3396.62)
(Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.15063 x86_64)
2) Card should contain the correct title text
- Failed: invalid selector: An invalid or illegal selector was specified
(Session info: chrome=67.0.3396.62)
(Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.15063 x86_64)
3) Card should contain the correct content
- Failed: invalid selector: An invalid or illegal selector was specified
(Session info: chrome=67.0.3396.62)
(Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.15063 x86_64)
4) Card should contain the correct link in the footer
- Failed: invalid selector: An invalid or illegal selector was specified
(Session info: chrome=67.0.3396.62)
(Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.15063 x86_64)
Executed 4 of 29 specs (4 FAILED) (25 SKIPPED) in 2 secs.
[09:34:33] I/launcher - 0 instance(s) of WebDriver still running
[09:34:33] I/launcher - chrome #01 failed 4 test(s)
[09:34:33] I/launcher - overall: 4 failed spec(s)
[09:34:33] E/launcher - Process exited with error code 1
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! angular-library-demo@0.0.0 protractor: `protractor protractor.conf.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the angular-library-demo@0.0.0 protractor script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\R\AppData\Roaming\npm-cache\_logs\2018-05-30T07_34_34_050Z-debug.log
A: The only changes that your protractor tests would require is that if you've used any locator using by.repeater or by.binding or by.model, then they would not work. You would need to replace them with other locators, most preferably by using by.css locators.
Rest other things should be working fine as expected.
| |
doc_23528606
|
A: I resolved this with JSON variable substitution in release pipeline's Azure App Service Deploy task.
[
Then put appropriate variables to put wanted values to function.json, for example topic for Azure Service Bus trigger: bindings.0.topicName = MyTopic
| |
doc_23528607
|
In other words, let the extension do the key-checking; if it does exist, then add the element to the array enclosed in that key, if it doesn't exist, then create the key by storing a new array with that element.
The code that I use now goes like this:
dictionary[key] == nil ? dictionary[key] = [element] : dictionary[key]?.append(element)
But I would love to write something like:
dictionary.add(element, toArrayOn: key)
The extension would look something like this:
extension Dictionary {
mutating func add(element: SomeElement, toArrayOn key: Key) {
// Check if self[key] exisists:
// If self[key] != nil, check if the value is Array<SomeElement>, if so append the element to the Array, if not throw an error.
// If self[key] == nil, make an empty Array<SomeElement> and insert the element.
}
}
}
I recognize this might be a bit of a stretch but I find it fun to write these sort of extensions that help clean up code. I'm also starting to catch up with the idea of deciding a specific code syntax and then figuring out how can it be accomplished.
Any thoughts on this would be very welcome!
A: Here is possible solution. Tested with Xcode 11.4
extension Dictionary {
mutating func add<T>(_ element: T, toArrayOn key: Key) where Value == [T] {
self[key] == nil ? self[key] = [element] : self[key]?.append(element)
}
}
| |
doc_23528608
|
My testing code is below. Could someone let me know what I'm missing? I'd appreciate it!
import Cocoa
import SceneKit
class ViewController: NSViewController {
@IBOutlet weak var sceneView: SCNView!
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "Sounds/Test.mp3",
ofType: nil)
let url = URL(fileURLWithPath: path!)
let source = SCNAudioSource(url:url)!
source.loops = true
source.shouldStream = false
source.isPositional = true
source.load()
let player = SCNAudioPlayer(source: source)
let box = SCNBox(width: 100.0,
height: 100.0,
length: 100.0,
chamferRadius: 100.0)
let boxNode = SCNNode(geometry: box)
let audioNode = SCNNode()
boxNode.addChildNode(audioNode)
let scene = SCNScene()
scene.rootNode.addChildNode(boxNode)
sceneView.scene = scene
audioNode.addAudioPlayer(player)
let avm = player.audioNode as! AVAudioMixing
avm.volume = 1.0
let up = SCNAction.moveBy(x: 0, y: 100, z: 0, duration: 5)
let down = SCNAction.moveBy(x: 0, y: -100, z: 0, duration: 5)
let sequence = SCNAction.sequence([up, down])
let loop = SCNAction.repeatForever(sequence)
boxNode.runAction(loop)
// Do any additional setup after loading the view.
}
}
A: Updated.
You're casting the player.audioNode to AVAudioMixing protocol:
let avm = player.audioNode as! AVAudioMixing
But instead of it, you have to cast it to a class. A code looks like this:
let avm = player.audioNode as? AVAudioEnvironmentNode
Any node that conforms to the AVAudioMixing protocol (for example, AVAudioPlayerNode) can act as a source in this environment. The environment has an implicit listener. By controlling the listener’s position and orientation, the application controls the way the user experiences the virtual world. This node also defines properties for distance attenuation and reverberation that help characterize the environment.
And take into account !
Only inputs with a mono channel connection format to the environment node are spatialized. If the input is stereo, the audio is passed through without being spatialized. Inputs with connection formats of more than two channels aren't supported.
And, of course, you need to implement AVAudio3DMixing protocol.
Here's a working code:
import SceneKit
import AVFoundation
class ViewController: NSViewController, AVAudio3DMixing {
// YOU NEED MONO AUDIO !!!
var renderingAlgorithm = AVAudio3DMixingRenderingAlgorithm.sphericalHead
var rate: Float = 0.0
var reverbBlend: Float = 0.5
var obstruction: Float = -100.0
var occlusion: Float = -100.0
var position: AVAudio3DPoint = AVAudio3DPoint(x: 0, y: 0, z: -100)
override func viewDidLoad() {
super.viewDidLoad()
let scene = SCNScene()
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.camera?.zFar = 200
cameraNode.position = SCNVector3(x: 0, y: 0, z: 40)
scene.rootNode.addChildNode(cameraNode)
let sceneView = self.view as! SCNView
sceneView.scene = scene
sceneView.backgroundColor = NSColor.black
sceneView.autoenablesDefaultLighting = true
let path = Bundle.main.path(forResource: "Test_Mono", ofType: "mp3")
let url = URL(fileURLWithPath: path!)
let source = SCNAudioSource(url: url)!
source.loops = true
source.shouldStream = false // MUST BE FALSE
source.isPositional = true
source.load()
let player = SCNAudioPlayer(source: source)
let audioNode = SCNNode()
let box = SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0.2)
let boxNode = SCNNode(geometry: box)
boxNode.addChildNode(audioNode)
scene.rootNode.addChildNode(boxNode)
audioNode.addAudioPlayer(player)
let avm = player.audioNode as? AVAudioEnvironmentNode
avm?.reverbBlend = reverbBlend
avm?.renderingAlgorithm = renderingAlgorithm
avm?.occlusion = occlusion
avm?.obstruction = obstruction
let up = SCNAction.moveBy(x: 0, y: 0, z: 70, duration: 5)
let down = SCNAction.moveBy(x: 0, y: 0, z: -70 , duration: 5)
let sequence = SCNAction.sequence([up, down])
let loop = SCNAction.repeatForever(sequence)
boxNode.runAction(loop)
avm?.position = AVAudio3DPoint(
x: Float(boxNode.position.x),
y: Float(boxNode.position.y),
z: Float(boxNode.position.z))
}
}
A: After researching and experimenting for a hwile, I finally figured it out. There were two things that I needed to fix.
*
*I had to change the default renderingAlgorithm for SCNAudioPlayer.AVAudioNode from equalPowerPanning to either HRTF or HRTFHQ. However, AVAudioNode does not have renderingAlgorithm property. However, I was able to cast SCNAudioPlayer.AVAudioNode as AVAudioPlayerNode, and AVAudioPlayerNode does have renderingAlgorithm property. Here's the relevant code.
if let apn = player.audioNode as? AVAudioPlayerNode {
apn.renderingAlgorithm = .HRTFHQ
}
*I had to assign a node with SCNCamera to pointOfView for SCNView. Also I had to change the position of the camera node further away from the audioNode. Otherwise, I heard the drastic movement in the beginning. Here's the relevant code.
let cameraNode = SCNNode(geometry: SCNBox(width:1, height:1, length:1, chamferRadius: 0.1))
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(x: 0, y: 0, z: -10)
sceneView.pointOfView = cameraNode
My scene.rootNode is a box geometry with 100x100x100 dimension. Inside scene.rootNode, I have a boxNode with 50x5050 dimension. Then inside the boxNode, I have audioNode generating sound with 1x1x1 dimension as well as cameraNode with 1x1x1 dimension. AudioNode's start position is 0,0,0, and the position for the cameraNode is 0,0,-20.
Finally here's the entire working code.
import Cocoa
import AVFoundation
import SceneKit
class ViewController: NSViewController {
@IBOutlet weak var sceneView: SCNView!
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "Sounds/Test_mono.mp3", ofType: nil)
let url = URL(fileURLWithPath: path!)
let source = SCNAudioSource(url: url)!
source.loops = true
source.shouldStream = false
source.isPositional = true
source.load()
let player = SCNAudioPlayer(source: source)
if let apn = player.audioNode as? AVAudioPlayerNode {
apn.renderingAlgorithm = .HRTFHQ
}
let audioNode = SCNNode(geometry: SCNBox(width:1, height:1, length:1, chamferRadius: 0.1))
let cameraNode = SCNNode(geometry: SCNBox(width:1, height:1, length:1, chamferRadius: 0.1))
cameraNode.camera = SCNCamera()
let boxNode = SCNNode(geometry: SCNBox(width:50, height:50, length:50, chamferRadius: 1))
boxNode.addChildNode(audioNode)
audioNode.position = SCNVector3(x: 0, y: 0, z: 0)
boxNode.addChildNode(cameraNode)
cameraNode.position = SCNVector3(x: 0, y: 0, z: -10)
let scene = SCNScene()
scene.rootNode.geometry = SCNBox(width:100, height:100, length:100, chamferRadius: 0.1)
scene.rootNode.addChildNode(boxNode)
boxNode.position = SCNVector3(x: 0, y: 0, z: 0)
sceneView.scene = scene
sceneView.pointOfView = cameraNode
sceneView.audioListener = cameraNode
audioNode.addAudioPlayer(player)
let move = SCNAction.moveBy(x:1, y:0, z:0, duration: 1)
let sequence = SCNAction.sequence([move])
let loop = SCNAction.repeatForever(sequence)
audioNode.runAction(loop)
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| |
doc_23528609
|
How can i find x0, x1, y0 and y1 by using case number, height and width in a maze ?
Are there a formule for that ?
float distance(Maze* maze, int start, int end)
{
float x0 = ..??..
float x1 = ..??..
float y0 = ..??..
float y1 = ..??..
float dx = x0 - x1;
float dy = y0 - y1;
return sqrtf(dx*dx+dy*dy);
}
Example of a maze :
<----------- width ------------->
case0 | case1 | case2 | case3 |
case4 | case5 | case6 | case7 | height
case8 | case9 | case10 | case11 |
A: First calculate the indexes:
int x0 = m % width; // % = modulo operation
int y0 = m / width;
int x1 = n % width;
int y1 = n / width;
int dx = x1 - x0;
int dy = y1 - y0;
return sqrtf(dx*dx + dy*dy);
Make sure to perform the index calculations with int. The int-division truncates the decimals. The modulo operation returns the remainder of the division. x % width yields a value in the range 0 .. width-1.
A: From your example, you can get the row and the column of the element, like this:
//for case(n)
int row_of_n = n / number_of_columns;
int column_of_n = n % number_of_columns;
Do the same to find the coordinates of case(m) and then apply the Pythagorean theorem.
A: Assuming you want:
1:(0,0) | 2:(1,0) | 3:(2,0) | 4:(3,0) |
5:(0,1) | 6:(1,1) | 7:(2,1) | 8:(3,1) |
9:(0,2) | 10:(1,2) | 11:(2,2) | 12:(3,2) |
You can find the x and y of a given case by
void find_coordinates(int case_number, &x, &y) {
*x = case_number % 4 - 1;
*y = case_number / 4;
if(*x==-1) *x=3;
if(*x==0) *y=*y-1;
}
A: float x0 = (start % width);
float x1 = ( end % width);
float y0 = (start / width);
float y1 = ( end / width);
As start/end in effect wraps around at width to the next row, the y is just the number of widths which fits into the start/end. The x is what's left over when you subtract the y.
| |
doc_23528610
|
My goal here is to extract clean texts while keeping the wikilinks and discarding complicated templates such as info-boxes. Do you have any idea how to tackle this template expansion problem ?
A: I made a solution that uses Kiwix to get clean texts from Wikipedia. The HTML produced by Kiwix seems easy to parse for my purpose. I don't make the code available anymore (didn't have time to make something shareable). But it turned out to be effective and fast to implement.
A: I believe that https://github.com/tatuylonen/wikitextprocessor/ does what you want:
This is a Python package for processing WikiMedia dump files for
Wiktionary, Wikipedia, etc., for data extraction, error checking,
offline conversion into HTML or other formats, and other uses. Key
features include:
*
*Parsing dump files, including built-in support for processing pages in parallel
*Wikitext syntax parser that converts the whole page into a parse tree
*Extracting template definitions and Scribunto Lua module definitions from dump files
*Expanding selected templates or all templates, and heuristically identifying templates that need to be expanded before parsing is
reasonably possible (e.g., templates that emit table start and end
tags)
*Processing and expanding wikitext parser functions
*Processing, executing, and expanding Scribunto Lua modules (they are very widely used in, e.g., Wiktionary, for example for generating
IPA strings for many languages)
*Controlled expansion of parts of pages for applications that parse overall page structure before parsing but then expand templates on
certain sections of the page
*Capturing information from template arguments while expanding them, as template arguments often contain useful information not
available in the expanded content.
| |
doc_23528611
|
And this is the source code
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
A: When you use glyphicons, you must always add single class "glyphicon". You can see, the example on bootstrap3 components page
Wrong usage
<i class="glyphicon-search"></i>
Correct usage
<i class="glyphicon glyphicon-search"></i>
| |
doc_23528612
|
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((288, 512))
clock = pygame.time.Clock()
spaceship = pygame.image.load(r'C:\Users\Anonymous\Downloads\New folder\spaceship.png')
x = 150
y = 495
spaceship_rect = spaceship.get_rect(center=(x, y))
velocity = 10
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > 0:
x -= velocity
spaceship_rect = spaceship.get_rect(center=(x, y))
screen.blit(spaceship, spaceship_rect)
pygame.display.update()
clock.tick(120)
A: Any object drawn on a surface stays there permanently. Drawing an object only persistently changes the color of some pixels in the surface.
You have to clear the display in ever frame, by pygame.Surface.fill, before you draw the scene and update the display:
screen.fill(0)
screen.blit(spaceship, spaceship_rect)
pygame.display.update()
Complete example:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((288, 512))
clock = pygame.time.Clock()
spaceship = pygame.image.load(r'C:\Users\Anonymous\Downloads\New folder\spaceship.png')
x = 150
y = 495
spaceship_rect = spaceship.get_rect(center=(x, y))
velocity = 10
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > 0:
x -= velocity
spaceship_rect = spaceship.get_rect(center=(x, y))
screen.fill(0)
screen.blit(spaceship, spaceship_rect)
pygame.display.update()
clock.tick(120)
| |
doc_23528613
|
I tried instead $comment->comment_post_ID to $comment->comment_ID but it does not work.
Thank everyone!
<?php $comments = get_comments($param);?>
<?php foreach ($comments as $comment): ?>
<?php if ($comment->comment_approved != '0'): ?>
<?php
$attachments = get_posts(array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'any',
'post_parent' => $comment->comment_post_ID,
));
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_url($attachment->ID);
}
}
?>
<?php endif;?>
<?php endforeach;?>
A: After self-study, I know how to get the url image in the comment with the following code, this code put in the functions.php file.
function get_attachment_url_image_comment($comment_id) {
$meta_key = 'attachment_id';
$attachment_id = get_comment_meta( $comment_id, $meta_key, true );
$full_img_url = wp_get_attachment_image_url( $attachment_id, 'full' );
return $full_img_url;
}
All that's left to do is pass the desired comment ID into the function and get the attached image
<?php $comments = get_comments($param);?>
<?php foreach ($comments as $comment): ?>
<?php if ($comment->comment_approved != '0'): ?>
<?php if(get_attachment_url_image_comment($comment->comment_ID)): ?>
<?php echo get_attachment_url_image_comment($comment->comment_ID) ?>
<?php endif; ?>
<?php endif;?>
<?php endforeach;?>
Result: "http://localhost/wp-content/uploads/2020/07/11439468-3x4-xlarge-2.jpg"
It works fine!
| |
doc_23528614
|
Which ORY solution should I be using for that part, and how would I use it together with Kratos?
A: Please let me elaborate Matt Mc's answer:
As per the official documentation here:
https://www.ory.sh/hydra/docs/
Hydra implements the OAuth and OpenID Connect standard without forcing you to use a "Hydra User Management" (login, logout, profile management, registration), a particular template engine, or a predefined front-end. This allows you to implement user management and login your way, in your technology stack, with authentication mechanisms required by your use case (token-based 2FA, SMS 2FA, etc).
This means that we can use any user management system and Kratos is one choice for it.
Hydra becomes in charge of issuing Access tokens, Refresh tokens etc.
The third-party apps can register themselves with Hydra and they will be issued a client ID and client secret.
Hydra provides an API for this, however, you have to design the UI by yourself.
More details regarding the API for creating clients can be found here:
https://www.ory.sh/hydra/docs/reference/api/#operation/createOAuth2Client
The quickest way to get acquainted with Hydra is their 5 minute tutorial over here:
https://www.ory.sh/hydra/docs/5min-tutorial
Kratos becomes in charge of actually storing the user credentials and checking the user credentials when they login.
I have created a reference implementation in Go, that integrates Kratos (v0.8.0-alpha.3) and Hydra (v1.10.6).
https://github.com/atreya2011/go-kratos-test/tree/hydra
There is also an official Node.js reference implementation that uses an older version of Kratos/Hydra over here.
https://github.com/ory/kratos-selfservice-ui-node/tree/hydra-integration-2021
You can use both as a starting point to implement an integration in any other language of your choice :)
You can also find other useful community implementations over here:
https://www.ory.sh/docs/ecosystem/community/
A: Seems like you would use ORY Hydra.
| |
doc_23528615
|
$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql
This command will overwrite the existing table data.
Looking at appending to existing instead of overwrite.
Any command for this ?
A: Have a look in the sql file that you want to add to existing data. It is likely a dump that includes the lines starting like this: DROP TABLE IF EXISTS and/or it contains DROP DATABASE IF EXISTS db_name
You need to remove these lines from the sql file that you feed into mysql, either by modifying the dump command with which you created the file (see --skip-add-drop-table option and --no-create-db options) or by removing those lines from the sql file with an editor or awk or something.
see https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html
other relevant SO-links: mysqldump with create database line and MySQL import - How to ignore Drop table if exists line?
| |
doc_23528616
|
const src = "base 64 of the image";
window.open(src,'Image','width=largeImage.stylewidth,height=largeImage.style.height,resizable=1');
this is now working (at least on the latest stable Chrome version).. am I missing something?
A: Try this:
var image = new Image();
image.src = "data:image/jpg;base64, " + "base 64 of the image";
var w = window.open("");
w.document.write(image.outerHTML);
w.document.close();
Also, make sure to specify the correct content type, in my answer I'm using jpg
| |
doc_23528617
|
Base Input List:
data=[
["10000025",710],
["1000138833",1065],
["100274005",820],
["1353180",3160],
["481584",3670],
["4851845845",1690],
["485584",1310],
["48848448",1000],
["49849948",1050],
["585598",4620],
["84154858584",620],
["841584584",2050],
["8451184584",2860],
["845188956",1800],
["845845184",1300],
["8458484",2300],
["8954884",1780],
["9416481584",2720],
["9448155584",1000],
["94949494",1000],
["959494158",1590],
["98558858",1550]
]
Expected Output:
List of Combos from the list having the sum of 10000, and if no sum of a specific value is possible, then a list of leftover elements with a max of 6 elements at each combo.
I tried following some threads:
Find all combinations of a list of numbers with a given sum
How to get all combination for a given sum with a given number of elements
My code:
data = [
["10000025", 710], ["1000138833", 1065], ["100274005", 820], ["1353180", 3160], ["481584", 3670],
["4851845845", 1690], ["485584", 1310], ["48848448", 1000],
["49849948", 1050], ["585598", 4620], ["84154858584", 620], ["841584584", 2050], ["8451184584", 2860],
["845188956", 1800], ["845845184", 1300], ["8458484", 2300], ["8954884", 1780], ["9416481584", 2720],
["9448155584", 1000],
["94949494", 1000],
["959494158", 1590], ["98558858", 1550]
]
valueList = [x[1] for x in data]
def GetNumbers(number):
result = []
for i in sorted(valueList, reverse=True):
sum_list = sum(result)
if sum_list + i == number:
result.append(i)
return result
elif sum_list + i < number:
result.append(i)
return result
for i in range(0, len(data)):
print(GetNumbers(10000))
Output in code could be in the list of the list or dict, whichever is achievable.
A: Here is a code, that solve this problem however there is a high complexity, so it will quickly become too long to compute if you have more element in your dataset.
data=[
["10000025",710],
["1000138833",1065],
["100274005",820],
["1353180",3160],
["481584",3670],
["4851845845",1690],
["485584",1310],
["48848448",1000],
["49849948",1050],
["585598",4620],
["84154858584",620],
["841584584",2050],
["8451184584",2860],
["845188956",1800],
["845845184",1300],
["8458484",2300],
["8954884",1780],
["9416481584",2720],
["9448155584",1000],
["94949494",1000],
["959494158",1590],
["98558858",1550]
]
targetAmmount = 10000
groupMaxSize = 6
def createGroup(current, remaining_data):
currentAmmount = sum(e[1] for e in current)
missingAmmount = targetAmmount - currentAmmount
if len(current) >= groupMaxSize:
if currentAmmount == targetAmmount:
yield current
else:
yield None
possibilities = sorted(filter(lambda e: e[1] <= missingAmmount, remaining_data), key=lambda e: e[1], reverse=True)
for possibility in possibilities:
next_current = [*current, possibility]
next_remaining = list(filter(lambda e: e!=possibility, possibilities))
if sum(e[1] for e in next_current) == targetAmmount:
yield next_current
else:
for res in createGroup(next_current, next_remaining):
yield res
res = []
ungrouped = []
while len(data) != 0:
first = [data.pop(0)]
groupeCreated = False
for group in createGroup(first, data):
if group != None:
groupeCreated = True
res.append(group)
for elem in group:
if elem in data:
data.remove(elem)
break
if not groupeCreated:
ungrouped.append(first[0])
print("Res : \n", res)
print("Ungrouped : \n", ungrouped)
A: The below code works for me. In jupyter lab on a 10 year old laptop it executes in 0.4 seconds.
from itertools import combinations, chain, islice
data=[["10000025",710],["1000138833",1065],["100274005",820],["1353180",3160],["481584",3670],["4851845845",1690],["485584",1310],["48848448",1000],["49849948",1050],["585598",4620],["84154858584",620],["841584584",2050],["8451184584",2860],["845188956",1800],["845845184",1300],["8458484",2300],["8954884",1780],["9416481584",2720],["9448155584",1000],["94949494",1000],["959494158",1590],["98558858",1550]]
limit = 10000
def data_sum(xs):
global limit # using global to avoid having to do multiple argument passing in filter
return (sum(x[1] for x in xs)) == limit
def data_uptil(xs):
global limit
return (sum(x[1] for x in xs)) < limit
match_limit = chain.from_iterable([(filter(data_sum,combinations(data,k))) for k in range(2,len(data)+1)])
uptil_limit = (filter(data_uptil,combinations(data,6)))
print("Exact matchest that sum to limit")
for m in match_limit:
print(list(m))
print("Samples with 6 elements that sum to less than limit")
for u in uptil_limit:
print(list(u))
A few notes:
*
*If you run with pypy it might be faster, although the itertools are pretty fast on their own.
*You said all possible combinations, so I included combinations of size 2 up to the size of the input list
*I believe your code will not produce correct results as it is summing up from a sorted list as it goes. This would not work if limit = 10 and the list is (2,4,7,8) because it would not find (2,8).
*match_limit and uptil_limit generators are created almost
instantaneous using len consumes the list and will take processing
time, for example print(len(list(match_limit))) which gives 278
possible combinations in 4.2 seconds on my 10 year old laptop
*you can use islice if you want just a few answers, for example for m in islice(match_limit,5):
*your choice if you want a dict or a list. this also works:
print(dict(m))
*as noted, it is the calling of list that will consume the generator
this means results start be produced immediately as they are found.
A: Here's another version. It forces full evaluation of the lists to allow for the conditions from OP, I believe.
from itertools import combinations, chain
# data = [["10000025",710],["1000138833",1065],["100274005",820],["1353180",3160],["481584",3670],["4851845845",1690],["485584",1310],["48848448",1000],["49849948",1050],["585598",4620],["84154858584",620],["841584584",2050],["8451184584",2860],["845188956",1800],["845845184",1300],["8458484",2300],["8954884",1780],["9416481584",2720],["9448155584",1000],["94949494",1000],["959494158",1590],["98558858",1550]]
data = [["10000025",71],["1000138833",165],["100274005",820],["1353180",160]]
limit = 10000
def data_sum(xs):
global limit # using global to avoid having to do multiple argument passing in filter
return (sum(x[1] for x in xs)) == limit
def my_sum(xs):
return (sum(x[1] for x in xs))
match_limit = chain.from_iterable([filter(data_sum,combinations(data2,k)) for k in range(2,len(data)+1)])
match_limit_list = list(match_limit)
if len(match_limit_list) > 0:
[print(m) for m in match_limit_list]
else:
uptil_limit_list = list(chain.from_iterable([list(combinations(data2,k)) for k in range(2,7)]))
uptil_limit_max = sorted(uptil_limit_list, key=my_sum, reverse=True)
[print(u) for u in uptil_limit_max]
For the test data that does not sum to limit, the output is:
(['10000025', 71], ['1000138833', 165], ['100274005', 820], ['1353180', 160])
(['1000138833', 165], ['100274005', 820], ['1353180', 160])
(['10000025', 71], ['1000138833', 165], ['100274005', 820])
(['10000025', 71], ['100274005', 820], ['1353180', 160])
(['1000138833', 165], ['100274005', 820])
(['100274005', 820], ['1353180', 160])
(['10000025', 71], ['100274005', 820])
(['10000025', 71], ['1000138833', 165], ['1353180', 160])
(['1000138833', 165], ['1353180', 160])
(['10000025', 71], ['1000138833', 165])
(['10000025', 71], ['1353180', 160])
| |
doc_23528618
|
I've cleaned my project.
public static final class id {
public static final int =0x7f07005b;
public static final int button1=0x7f070004;
public static final int button2=0x7f070005;
public static final int frameLayout1hardMatchup=0x7f070009;
There is no error in String.xml, here is my String.xml.
<string name="hello">Hello World, MemoryCardsActivity!</string>
<string name="app_name">Princess Memory Cards</string>
<string name="text_name">Congrates</string>
<string name="text_help">Turn over pairs of matching cards, tap to flip two cards, as the match happens, they get removed from the screen.Try to get all cards match in minimum moves and proceed to next level</string>
And also there is not any @+id kind of error.
What else could be the reason of this.
Any positive response would be really appreciated.. :(
A: You are missing a variable name
public static final int = 0x7f07005b;
instead
public static final int variableName = 0x7f07005b;
A: I produced a similar error by changing one of my layout XML files. I changed
android:id="@+id/image_frame"
to
android:id="@+id/ "
The error I see with this change is
public static final int =0x7f080010;
// Syntax error on token "int", VariableDeclaratorId expected after this token
This seems to be what @codeMagic was describing.
| |
doc_23528619
|
Possible Duplicate:
Why are interfaces preferred to abstract classes?
Abstract class and Interface class?
Please give a real world example for the use of Interfaces. Also, what are the differences between an Abstract Class and an Interface. I mean, what are the benefits of Interfaces over abstract class, because Abstract Classes can also be used for the same purpose as the Interfaces. Then why Interfaces are so important?
Thanks for your comments guys, but still I didn't get answer for my question. I have asked for a "REAL WORLD EXAMPLE" of java interfaces. In real world, like in our daily life, where we use java interfaces. I think i am clear this time.
A: Interfaces simply define the contract (API) of the class. In other words, it simply states which methods you MUST implement if your class implements the interface.
With Abstract classes, you can implement functionality. This is usually done when multiple classes have similar functionality, so the implementation only needs to be done once.
Another differnce between the two is that a class my implement many interfaces, but can extend only one abstract class (multiple inheritance). This is because interfaces don't define implementation. If you could extend multiple abstract classes, the JVM would not know which implementation from which abstract class to use.
Example of using an interface:
public interface Bouncable {
public void bounce(); // no implementation
}
public class Ball implements Bouncable {
// now you must provide the implementation
public void bounce() {
System.out.println("I can bounce!");
}
}
But let's say you have more than one object that can bounce, and you don't want to write the implementation more than once.
Example of using abstract class:
public abstract class BouncableObject {
// you can provide implementation
public void bounce() {
System.out.println("I can bouce too!");
}
// or not if you define it abstract
public abstract void sayMyName();
}
// you don't need to implement bounce()
public class Ball extends BouncableObject {
// but you have to give this implementation
public void sayMyName() {
System.out.println("I am a ball");
}
}
public class RubberChicken extends BouncableObject {
public void sayMyName() {
System.out.println("I am a rubber chicken");
}
}
And now both Ball and RubberChicken can call bounce()
A: "A Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface, thereby agreeing to certain behavior. "
Take a look at these JAVA Interface tutorials:
*
*http://download.oracle.com/javase/tutorial/java/concepts/interface.html
*http://www.iam.ubc.ca/guides/javatut99/java/more/interfaceDef.html
A: Abstract class : Abstract classes permit declaration of classes that define only part of an
implementation, leaving the subclasses to provide the details.
In the class: Implementation of common state and behaviour that will be inherited by subclasses. Declaration of generic behaviours that subclasses must implement
An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it or that does not provide an implementation. for any abstract methods declared in its superclasses must be declared as an abstract class. An abstract class cannot be instantiated, however references to an abstract class can
be declared.
Interface:
An interface is like a class that defines only abstract methods. Unlike a class, an interface cannot include implementation (variables and method bodies). An interface is typically intended to be implemented by several classes
A class that claims to implement an interface must provide an implementation of every method defined within the interface. A class can implement many interfaces. An Interface can extend an existing interface.
Have a look at the lectures here: http://www.cs.auckland.ac.nz/courses/compsci230s2c/lectures/
A: In java, the two concepts abstract class and interface sounds similar.
But,
(1)
In interface you can only declare the members, you can't define anything inside the interface
In abstract class can have both definition and declaration.
(2)
Remember "A class can extend only one class where as it can implement more than one interface"
You can't extend more than one class in java where as you can implement any number of interfaces. This is one of the advantage of Interfaces over the Abstract Classes.
(3)
A class which extends the abstract class should define all the members from the abstract class. If you don't want to define all of them you need to declare the sub class also as abstract class.
Where as in Interfaces, if you implement an interface you can use what ever members you want from that interface, so need of declaring the class as abstract or any thing else. This is another advantage of using Interfaces rather than abstract class.
| |
doc_23528620
|
Python 3.7.0
IDLE 3.6. (64-bit)
Sublime Text 3.1.1.(3176)
#firstly I created classes for items and items_in_body_parts.
#for example, one of them:
class item_for_put_on:
def __init__(self):
self.name = ''
self.body_part = '' #for what body part? like in Diablo, for example, you can take a weapon in your hand and put on a helmet on your head
#there is a lot of other staff, i deleted it to make it simple, here are the main things:
right_hand_item_1 = right_hand_item()
on_head_item_1 = on_head_item()
item_for_put_on_1 = item_for_put_on()
item_check_on = item_check_on_class()
right_hand_item_1.name = ''
right_hand_item_1.body_part = ''
on_head_item_1.name = ''
on_head_item_1.body_part = ''
item_for_put_on_1.name = ''
item_check_on.name = ''
i_stick = ['Stick', 'in_hands']
i_helmet = ['Helmet', 'on_head']
all_item_names = {'Stick' : i_stick, 'Helmet' : i_helmet}
def item_put_on():
global item_for_put_on_1, right_hand_item_1, on_head_item_1
if item_for_put_on_1.body_part == 'on_head' and on_head_item_1.name == '':
on_head_item_1.name = item_for_put_on_1.name
#go back to function inventory_menu
if item_for_put_on_1.body_part == 'in_hands'and right_hand_item_1.name == '':
right_hand_item_1.name = item_for_put_on_1.name
#go back to function inventory_menu
#def inventory_menu(): --- this and a lot of other functions i don't decribe you, it's not necessary
def inventory_bag():
#we come here from inventory menu to see what we have in the bag
#global item_check_on, item_for_put_on_1 ---- should be globals here?
#here was some code - to describe to player all content of the bag - it works good
#NOW PLAYER DECIDES WHAT ITEM TO CHOOSE TO READ INFO ABOUT IT AND AFTER THAT HE CAN PUT IT ON HIS HERO
#command4 - it is the list of items.names in bag - it works good; player should type full name or to choose item's number
com4 = input ("> ")
while com4 not in commands4 and com4.lower() != 'back':
print ("Unknown command, try again.\n")
com4 = input ("> ")
if com4 in commands4:
ppp = com4
for i in all_item_names: #i - str!!!
if ppp == all_item_names[i][0]:
item_check_on.name = all_item_names[i][0]
item_check_on.body_part = all_item_names[i][1]
# remember ---- i_stick = ['Stick', 'in_hands']
# remember ---- i_helmet = ['Helmet', 'on_head']
# remember ---- all_item_names = {'Stick' : i_stick, 'Helmet' : i_helmet}
print("You are looking to the item " + item_check_on.name) #this is just info to display for player
print("item body part: " + item_check_on.body_part) #this is just info to display for player
ppp = ''
com4=''
print ("Would you like to 'equip'('eq') it or 'back'?\n")
com5 = input ("> ")
commands5 = ['back', 'equip', 'eq']
while com5.lower() not in commands5:
print ("Unknown command, try again.\n")
com5 = input ("> ")
if com5.lower() == 'back':
inventory_bag()
break
elif com5.lower() in ['equip', 'eq']:
item_for_put_on_1.name = all_item_names[i][0]
item_for_put_on_1.body_part = all_item_names[i][1]
item_put_on()
break
break
else:
print('test looping') #loop while going to this again and again, searching for the correct name of item in dictionary all_item_names
if ppp == '' and action4 == '':
break
elif action4.lower() == 'back':
#inventory_menu()
def inventory_eq():
#we come here from inventory menu to see what is equipped on our hero
#global right_hand_item_1, on_head_item_1 ---- should be globals here?
print("right arm - " + str(right_hand_item_1.name) + "\n")
print("head - " + str(on_head_item_1.name) + "\n")
#SO HERE WE CAN SEE WRONG INFO --- if you put on only one thing, everything is right, but if you put on the second thing - there will be two sticks (one on head, one in hand) or two helmets (one on head, one in hand)
SO HERE WE CAN SEE WRONG INFO: if you put on only one thing, everything is right, but if you put on the second thing - there will be two sticks (one on head, one in hand) or two helmets (one on head, one in hand); because of problems with names of items. And if I add more items and body-slots for them, and the last one will be for example Shield - there will be many shields on the hero's body instead of right items. And there are no previous items in inventory, of course.
In my opinion, the problem is somewhere with global variebles or maybe while-loop somewhere is not working good (maybe assigning every second forever, i don't know).
It seems that when we change item_for_put_on_1 it changes everything, that was assigned it - on_head_item_1 and right_hand_item_1 in function item_put_on().
And if i use clearing function for item_for_put_on_1 (to make it ='') in item_put_on() after item was equipped - it somehow deletes items' names from equipment
So the main problem is connected with item_for_put_on_1, but i need help to find a way to fix it.
A: I solved the problem, deleting objects and object.names. Now I use simple variables - I made them global everywhere.
Now it is works! But I don't understand what was the problem, even if we replace stupid unnecessary "item_for_put_on_1" by direct name from dictionary "all_item_names[i][0]". The problem wasn't solved with this method. The below code still didn't worked (the same problem with changing names)
# item_left_hand, item_on_head - these are objects, they got .name firstly
# below code is in item_put_on(): #I also saved global i from inventory_bag() for that
if all_item_names[i][1] == 'in hands':
item_left_hand.name = all_item_names[i][0]
elif all_item_names[i][1] == 'on head':
item_on_head.name = all_item_names[i][0]
But usual global variables (not objects) work very good:
global item_left_hand, item_on_head #in all functions
# below code is in item_put_on(): #I also saved global i from inventory_bag() for that
if all_item_names[i][1] == 'in hands':
item_left_hand = all_item_names[i][0]
elif all_item_names[i][1] == 'on head':
item_on_head = all_item_names[i][0]
| |
doc_23528621
|
I have a Kubernetes deployment.yaml file and I need my Python program to add the text from the dictionary to a particular line number (line 29, in between cpu: "500m" and volumeMounts:) in the deployment.yaml file.
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
volumeMounts:
- name: ephemeral
mountPath: "/tmp"
volumes:
- name: ephemeral
emptyDir: {}
test.py
yaml_change={
"change": '''
tolerations:
- key: "example-key"
operator: "Exists"
effect: "NoSchedule"
'''
}
line_number = 29
yaml_modification = yaml_change['change']
with open('values.yaml', 'r') as FileRead:
yaml_data = FileRead.readlines()
yaml_data = yaml_data[line_number-2]+yaml_modification
print(yaml_data)
with open('values.yaml', 'w') as FileWrite:
FileWrite.writelines(yaml_data)
When I run the python file, the text file in the dictionary gets added to the .yaml file. However, all the other contents are lost.
Before
After
Does anyone know how to get this requirement done?
A: Try changing the line yaml_data = yaml_data[line_number-2]+yaml_modification to
yaml_data.insert(line_number - 1, yaml_modification)
yaml_data is a list of all lines in the file. The list.insert(idx, obj) function inserts the object at a given position.
Your solution doesn't work because you are adding the content you want to add and the line before (yaml_data[line_number-2]).
| |
doc_23528622
|
- name: ${{ matrix.users }}-${{ matrix.comment-type }}
id: ${{ matrix.users }}-${{ matrix.comment-type }}
shell: bash
run: |
COMMENT_DATE=(something that depends on matrix users)
echo "::set-output name=${{ matrix.users }}-${{ matrix.comment-type }}::$COMMENT_DATE"
- name: echo issue and pr comment dates
shell: bash
run: |
echo "Last ISSUE comment date: ${{ steps.${{ matrix.users }}-${{ matrix.comment-type }}.outputs.${{ matrix.users }}-${{ matrix.comment-type }} }}"
In the second step of the job I am trying to access these outputs but the following syntax is not working
${{ steps.${{ matrix.users }}-${{ matrix.comment-type }}.outputs.${{ matrix.users }}-${{ matrix.comment-type }} }}"
Is there a way around this?
| |
doc_23528623
|
colorList1 = ['red', 'orange', 'pink', 'brown', 'green', 'yellow']
colorList2 = ['purple', 'blue', 'violet', 'black, 'cyan', 'white']
How do I generate and print 1 color from each list (per row), starting from beginning of list, based on the number entered by the user. And, how do I generate only a maximum of 2 pairs of colors each time until user hits Enter key.
Example:
userinput = int(input("Enter a limit: ")) # user enters 5
Output:
red purple
orange blue
press Enter key for next 2 pairs of colors # user presses Enter key to generate the next pair
pink violet
brown black
press Enter key for next 2 pairs of colors # user presses Enter key to generate the next pair
green cyan # last pair since user entered 5
End of list of colors
A: You could try something like this.
colorList1 = ['red', 'orange', 'pink', 'brown', 'green', 'yellow']
colorList2 = ['purple', 'blue', 'violet', 'black', 'cyan', 'white']
def print_color():
userInput = input("Enter amount to print: ")
try:
userInput = int(userInput)
except ValueError:
print("User Input must be a positive integer")
return
if userInput < 0:
print("User Input must be a positive integer")
return
for i in range(0, int(userInput)):
if i >= len(colorList1) or i >= len(colorList2):
print("End of list of colors")
return
if i % 2 == 0 and i != 0:
input("press Enter key for next 2 pairs of colors")
print(colorList1[i], colorList2[i])
print_color()
EDIT: I have updated the code to include basic error checking
A: You can do this:
colorList1 = ['red', 'orange', 'pink', 'brown', 'green', 'yellow']
colorList2 = ['purple', 'blue', 'violet', 'black', 'cyan', 'white']
color_pairs = iter(zip(colorList1,colorList2))
userinput = int(input("Enter a limit: ")) # user enters 5
i = 0
while i<userinput:
if i%2 == 0: input(f"press Enter key for next 2 pairs of colors")
print(*next(color_pairs))
if i+1 == len(colorList1):
break
i += 1
print("\nEnd of list of colors")
Output:
Enter a limit: 5
press Enter key for next 2 pairs of colors
red purple
orange blue
press Enter key for next 2 pairs of colors
pink violet
brown black
press Enter key for next 2 pairs of colors
green cyan
End of list of colors
limit = 7:
Enter a limit: 7
press Enter key for next 2 pairs of colors
red purple
orange blue
press Enter key for next 2 pairs of colors
pink violet
brown black
press Enter key for next 2 pairs of colors
green cyan
yellow white
End of list of colors
| |
doc_23528624
|
I have searched on here, youtube ect and even reserched about modals, but I am unable to find a solution to the problem.
HTML
<!-- Trigger/Open The Modal -->
<button class="subscribe" id="subscribe">Subscribe</button>
<!-- The Modal -->
<div id="subscription" class="subscribe-modal">
<!-- Modal content -->
<div class="subscribe-content">
<div class="subscribe-header">
<span class="close"></span>
</div>
<div class="subscribe-body">
<h2>Subscribe to the Galaxy Mailing List</h2>
<p>Welcome to the Galaxy Games Subscription Management page. Galaxy mailing lists are the best way to get the early word on all our game announcements, official launches, contests, special events, and more. Make sure you're enlisted to receive all
the updates.</p>
<a href="https://socialclub.galaxy-games.co.uk/settings/email" class="manage" target="_blank" click="closeSection()" data-gtm-category="Footer" data-gtm-action="Social Club" data-gtm-label="Manage Subscription Account">Manage Your Account</a>
</div>
</div>
</div>
<li><a href="http://support.galaxy-games.co.uk/" target="_blank" data-gtm-category="Footer" data-gtm-action="Link Click" data-gtm-label="Support">Support</a></li>
<li><a href="/careers" target="_blank" data-gtm-category="Footer" data-gtm-action="Link Click" data-gtm-label="Careers">Careers</a></li>
<!-- Trigger/Open The Modal -->
<button class="mouthoff" id="mouthoff">mouthoff</button>
<!-- The Modal -->
<div id="shout" class="mouthoff-modal">
<!-- Modal content -->
<div class="mouthoff-content">
<div class="mouthoff-header">
<span class="close"></span>
</div>
<div class="mouthoff-body">
<h2>Mouthoff - Tell Us What's On Your Mind</h2>
<p>Have something you want to tell us, ask us or bring to our attention? Feel free to Mouthoff and let us know here. Please bear in mind that we may not be able to answer absolutely everything and we won’t reveal to you any game info that hasn't yet been announced, but we’re always happy to have a look at what you have to say.</p><p>If you have a technical issue that you’d like to report, please <a href="http://www.galaxy-games.co.uk/support" target="_blank">contact our Support Team</a>.</p>
<form method="post" accept-charset="utf-8" class="row common-form pristine valid" action="https://www.galaxy-games.co.uk/mouthoff/mouthoff/submit.json">
<div style="display:none;">
<input type="hidden" name="_method" value="POST" autocomplete="off"></div>
<div class="form-group col-md-5 col-xxs-12">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" maxlength="100" placeholder="Name" oninvalid="setCustomValidity('You need to provide your name')" oninput="setCustomValidity('')" required="required" id="name">
</div>
<div class="form-group col-md-5 col-xxs-12">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" maxlength="100" placeholder="Email Address" oninvalid="setCustomValidity('You need to provide your email address')" oninput="setCustomValidity('')" required="required" id="email" value="">
</div>
<div class="form-group col-md-2 col-xxs-12">
<label for="age">Age</label>
<input type="number" name="age" class="form-control" min="13" max="100" pattern="[0-9]{2}" placeholder="Age" oninvalid="setCustomValidity('You need to provide your age')" oninput="setCustomValidity('')" required="required" id="age">
</div>
<div class="form-group col-md-8 col-xxs-12">
<label for="subject">Subject</label>
<input type="text" name="subject" class="form-control" maxlength="100" placeholder="Subject" oninvalid="setCustomValidity('You need to provide a subject')" oninput="setCustomValidity('')" required="required" id="subject">
</div>
<div class="form-group col-md-4 col-xxs-12">
<select name="category_id" required="required" id="category-id">
<option value="">Select Category</option>
<option value="1">General Suggestions</option>
<option value="2">GTA Online Suggestions</option>
<option value="3">Crews</option>
<option value="4">Other Social Club Features</option>
<option value="5">Galaxy Warehouse</option>
<option value="6">Customer Support</option>
<option value="7">Other Feedback</option>
<option value="8">Check out my Job</option>
<option value="9">Check out my Fan Video</option>
</select>
</div>
<div class="form-group col-xxs-12">
<textarea name="body" class="form-control" rows="4" placeholder="Talk To Us" templates="<div class="form-group col-xxs-12"></div>" oninvalid="setCustomValidity('You need to provide content')" oninput="setCustomValidity('')" maxlength="5000" required="required"></textarea>
</div>
<div id="captcha">
<div style="width: 304px; height: 78px;">
<div>
<iframe src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LejXR0TAAAAAOmd4Ya4FwOMyQar9uGCYU3Qm6P9&co=aHR0cHM6Ly93d3cucm9ja3N0YXJnYW1lcy5jb206NDQz&hl=en&v=v1563777128698&size=normal&cb=7eh5s8ewvd10" width="304" height="78" role="presentation" name="a-yc8avbksowkq" frameborder="0" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox"></iframe>
</div>
<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea>
</div>
</div>
<input type="hidden" name="g-response" autocomplete="off">
<button class="btn btn-yellow" type="submit">SUBMIT</button>
<!-- ngIf: message -->
</form>
</div>
</div>
</div>
<!-- Trigger/Open The Modal -->
<button class="press" id="press">Press</button>
<!-- The Modal -->
<div id="release" class="press-modal">
<!-- Modal content -->
<div class="press-content">
<div class="press-header">
<span class="close"></span>
</div>
<div class="press-body">
<h2>Press</h2>
<p>Have something you want to tell us, ask us or bring to our attention? Feel free to Mouthoff and let us know here. Please bear in mind that we may not be able to answer absolutely everything and we won’t reveal to you any game info that hasn't yet been announced, but we’re always happy to have a look at what you have to say.</p><p>If you have a technical issue that you’d like to report, please <a href="http://www.galaxy-games.co.uk/support" target="_blank">contact our Support Team</a>.</p>
<form method="post" accept-charset="utf-8" class="row common-form pristine valid" action="https://www.galaxy-games.co.uk/mouthoff/mouthoff/submit.json">
<div style="display:none;">
<input type="hidden" name="_method" value="POST" autocomplete="off"></div>
<div class="form-group col-md-5 col-xxs-12">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" maxlength="100" placeholder="Name" oninvalid="setCustomValidity('You need to provide your name')" oninput="setCustomValidity('')" required="required" id="name">
</div>
<div class="form-group col-md-5 col-xxs-12">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" maxlength="100" placeholder="Email Address" oninvalid="setCustomValidity('You need to provide your email address')" oninput="setCustomValidity('')" required="required" id="email" value="">
</div>
<div class="form-group col-md-2 col-xxs-12">
<label for="age">Age</label>
<input type="number" name="age" class="form-control" min="13" max="100" pattern="[0-9]{2}" placeholder="Age" oninvalid="setCustomValidity('You need to provide your age')" oninput="setCustomValidity('')" required="required" id="age">
</div>
<div class="form-group col-md-8 col-xxs-12">
<label for="subject">Subject</label>
<input type="text" name="subject" class="form-control" maxlength="100" placeholder="Subject" oninvalid="setCustomValidity('You need to provide a subject')" oninput="setCustomValidity('')" required="required" id="subject">
</div>
<div class="form-group col-md-4 col-xxs-12">
<select name="category_id" required="required" id="category-id">
<option value="">Select Category</option>
<option value="1">General Suggestions</option>
<option value="2">GTA Online Suggestions</option>
<option value="3">Crews</option>
<option value="4">Other Social Club Features</option>
<option value="5">Galaxy Warehouse</option>
<option value="6">Customer Support</option>
<option value="7">Other Feedback</option>
<option value="8">Check out my Job</option>
<option value="9">Check out my Fan Video</option>
</select>
</div>
<div class="form-group col-xxs-12">
<textarea name="body" class="form-control" rows="4" placeholder="Talk To Us" templates="<div class="form-group col-xxs-12"></div>" oninvalid="setCustomValidity('You need to provide content')" oninput="setCustomValidity('')" maxlength="5000" required="required"></textarea>
</div>
<div id="captcha">
<div style="width: 304px; height: 78px;">
<div>
<iframe src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LejXR0TAAAAAOmd4Ya4FwOMyQar9uGCYU3Qm6P9&co=aHR0cHM6Ly93d3cucm9ja3N0YXJnYW1lcy5jb206NDQz&hl=en&v=v1563777128698&size=normal&cb=7eh5s8ewvd10" width="304" height="78" role="presentation" name="a-yc8avbksowkq" frameborder="0" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox"></iframe>
</div>
<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea>
</div>
</div>
<input type="hidden" name="g-response" autocomplete="off">
<button class="btn btn-yellow" type="submit">SUBMIT</button>
<!-- ngIf: message -->
</form>
</div>
</div>
</div>
CSS
button.subscribe{
background:transparent !important;
border:none;
display:inline-block;
zoom:1;
*display:inline;
vertical-align:top;
float:none !important;
margin-top:7px;
text-transform:uppercase;
}
button.subscribe:focus{
outline:none;
}
/* The Modal (background) */
.subscribe-modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
-webkit-animation-name: fadeIn; /* Fade in the background */
-webkit-animation-duration: 0.4s;
animation-name: fadeIn;
animation-duration: 0.4s
}
/* Modal Content */
.subscribe-content {
position: fixed;
bottom: 0;
background-color: #fefefe;
width: 100%;
-webkit-animation-name: slideIn;
-webkit-animation-duration: 0.4s;
animation-name: slideIn;
animation-duration: 0.4s
}
/* The Close Button */
.close {
color: #000;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #ff0000;
text-decoration: none;
cursor: pointer;
}
.subscribe-header {
padding: 2px 16px;
background-color: #000;
color: white;
}
.subscribe-body {
padding: 2px 16px;
}
.subscribe-body h2{
margin-top: 15px;
text-transform: uppercase;
font-size: 15px;
font-weight: 400;
padding-bottom: 2px;
font-family: DINNext-Bld,sans-serif;
margin: 20px 20px 20px;
line-height: 90%;
text-align: center;
letter-spacing: -.03em;
}
.subscribe-body p{
margin-left:550px;
margin-right:550px;
font-size: 15px;
padding-bottom: 2px;
font-family: DINNext-Bld,sans-serif;
text-align: justify;
}
.subscribe-body a.manage{
margin-right: 1700px;
padding:6px 20px 3px;
text-decoration:none;
border:1px solid #000;
position:relative;
left:50%;
transform:translateX(-50%);
text-transform:uppercase;
font-size:1em;
display:inline-block;
zoom:1;
*display:inline;
vertical-align:top;
float:none !important;
color:#000;
font-family:DINNext-Med,sans-serif;
margin-bottom:25px;
}
.subscribe-body a.manage:hover{
background:#000;
color:#fff
}
.subscribe-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
/* Add Animation */
@-webkit-keyframes slideIn {
from {bottom: -300px; opacity: 0}
to {bottom: 0; opacity: 1}
}
@keyframes slideIn {
from {bottom: -300px; opacity: 0}
to {bottom: 0; opacity: 1}
}
@-webkit-keyframes fadeIn {
from {opacity: 0}
to {opacity: 1}
}
@keyframes fadeIn {
from {opacity: 0}
to {opacity: 1}
}
button.mouthoff{
background:transparent !important;
border:none;
display:inline-block;
zoom:1;
*display:inline;
vertical-align:top;
float:none !important;
margin-top:7px;
text-transform:uppercase;
}
button.mouthoff:focus{
outline:none;
}
/* The Modal (background) */
.mouthoff-modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
-webkit-animation-name: fadeIn; /* Fade in the background */
-webkit-animation-duration: 0.4s;
animation-name: fadeIn;
animation-duration: 0.4s
}
/* Modal Content */
.mouthoff-content {
position: fixed;
bottom: 0;
background-color: #fefefe;
width: 100%;
-webkit-animation-name: slideIn;
-webkit-animation-duration: 0.4s;
animation-name: slideIn;
animation-duration: 0.4s
}
.mouthoff-header {
padding: 2px 16px;
background-color: #000;
color: white;
}
.mouthoff-body {
padding: 2px 16px;
}
.mouthoff-body h2{
margin-top: 15px;
text-transform: uppercase;
font-size: 15px;
font-weight: 400;
padding-bottom: 2px;
font-family: DINNext-Bld,sans-serif;
margin: 20px 20px 20px;
line-height: 90%;
text-align: center;
letter-spacing: -.03em;
}
.mouthoff-body p{
margin-left:550px;
margin-right:550px;
font-size: 15px;
padding-bottom: 2px;
font-family: DINNext-Bld,sans-serif;
text-align: justify;
}
.mouthoff-body .row{
margin-left: 550px;
margin-right:550px;
}
.mouthoff-body .btn-yellow{
margin-bottom:100px;
padding: 9px 20px 6px
}
.mouthoff-body a.manage{
margin-right: 1700px;
padding:6px 20px 3px;
text-decoration:none;
border:1px solid #000;
position:relative;
left:50%;
transform:translateX(-50%);
text-transform:uppercase;
font-size:1em;
display:inline-block;
zoom:1;
*display:inline;
vertical-align:top;
float:none !important;
color:#000;
font-family:DINNext-Med,sans-serif;
margin-bottom:25px;
}
.mouthoff-body a.manage:hover{
background:#000;
color:#fff
}
.mouthoff-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
/* Add Animation */
@-webkit-keyframes slideIn {
from {bottom: -300px; opacity: 0}
to {bottom: 0; opacity: 1}
}
@keyframes slideIn {
from {bottom: -300px; opacity: 0}
to {bottom: 0; opacity: 1}
}
@-webkit-keyframes fadeIn {
from {opacity: 0}
to {opacity: 1}
}
@keyframes fadeIn {
from {opacity: 0}
to {opacity: 1}
}
button.press{
background:transparent !important;
border:none;
display:inline-block;
zoom:1;
*display:inline;
vertical-align:top;
float:none !important;
margin-top:7px;
text-transform:uppercase;
}
button.press:focus{
outline:none;
}
/* The Modal (background) */
.press-modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
-webkit-animation-name: fadeIn; /* Fade in the background */
-webkit-animation-duration: 0.4s;
animation-name: fadeIn;
animation-duration: 0.4s
}
/* Modal Content */
.press-content {
position: fixed;
bottom: 0;
background-color: #fefefe;
width: 100%;
-webkit-animation-name: slideIn;
-webkit-animation-duration: 0.4s;
animation-name: slideIn;
animation-duration: 0.4s
}
.press-header {
padding: 2px 16px;
background-color: #000;
color: white;
}
.press-body {
padding: 2px 16px;
}
.press-body h2{
margin-top: 15px;
text-transform: uppercase;
font-size: 15px;
font-weight: 400;
padding-bottom: 2px;
font-family: DINNext-Bld,sans-serif;
margin: 20px 20px 20px;
line-height: 90%;
text-align: center;
letter-spacing: -.03em;
}
.press-body p{
margin-left:550px;
margin-right:550px;
font-size: 15px;
padding-bottom: 2px;
font-family: DINNext-Bld,sans-serif;
text-align: justify;
}
.press-body .row{
margin-left: 550px;
margin-right:550px;
}
.press-body .btn-yellow{
margin-bottom:100px;
padding: 9px 20px 6px
}
.press-body a.manage{
margin-right: 1700px;
padding:6px 20px 3px;
text-decoration:none;
border:1px solid #000;
position:relative;
left:50%;
transform:translateX(-50%);
text-transform:uppercase;
font-size:1em;
display:inline-block;
zoom:1;
*display:inline;
vertical-align:top;
float:none !important;
color:#000;
font-family:DINNext-Med,sans-serif;
margin-bottom:25px;
}
.press-body a.manage:hover{
background:#000;
color:#fff
}
.press-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
/* Add Animation */
@-webkit-keyframes slideIn {
from {bottom: -300px; opacity: 0}
to {bottom: 0; opacity: 1}
}
@keyframes slideIn {
from {bottom: -300px; opacity: 0}
to {bottom: 0; opacity: 1}
}
@-webkit-keyframes fadeIn {
from {opacity: 0}
to {opacity: 1}
}
@keyframes fadeIn {
from {opacity: 0}
to {opacity: 1}
}
Javascript
// Get the modal
var modal = document.getElementById("subscription");
// Get the button that opens the modal
var btn = document.getElementById("subscribe");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// Get the modal
var shoutModal = document.getElementById("shout");
// Get the button that opens the modal
var mouthoffButton = document.getElementById("mouthoff");
// Get the <span> element that closes the modal
var spanClose = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks the button, open the modal
mouthoffButton.onclick = function() {
shoutModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
spanClose.onclick = function() {
shoutModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal || event.target == shoutModal) {
shoutModal.style.display = "none";
modal.style.display = "none";
}
}
// Get the modal
var releaseModal = document.getElementById("release");
// Get the button that opens the modal
var pressButton = document.getElementById("press");
// Get the <span> element that closes the modal
var spanClose = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks the button, open the modal
pressButton.onclick = function() {
releaseModal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
spanClose.onclick = function() {
releaseModal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal || event.target == releaseModal) {
releaseModal.style.display = "none";
modal.style.display = "none";
}
}
Any help appreciated and thanks in advance.
A: document.getElementsByClassName("close")[0]; will always get you the first instance of the close button in the dom. In this case it is always the close button for the first modal. Try providing different ids for each of the modal close button and get the references using the getElementById method or provide different classes for each close button.
| |
doc_23528625
|
However nothing after the first page responds entirely correctly to being clicked in the way that the first page's worth does. (They actually do open as they should (Collapse plugin), but currently as soon as the collapsible comment toggle is selected the website scrolls down so that the toggle button clicked is barely in sight at the top.)
So how do I use a callback function [or something] so that elements loaded by Infinite Scroll behave the same as the original page's elements??????
Current Script:
$(function(){
var $container = $('#ISCONTAINER');
$container.isotope({
itemSelector : '.shifty-item'
});
$container.infinitescroll({
navSelector : '#page_nav', // selector for the paged navigation
nextSelector : '#page_nav a', // selector for the NEXT link (to page 2)',
bufferPx:900,
itemSelector : '.shifty-item', // selector for all items you'll retrieve
loading: {msgText:"Patience is a virtue.",
finishedMsg: 'Out of new things to show you today.',
img: 'http://i.imgur.com/qkKy8.gif'
}
},
// call Isotope as a callback
function( newElements ) {
$container.isotope( 'appended', $( newElements ) );
}//SOMEWHERE HERE IS WHERE I NEED TO ADD IN WHATEVER FUNCTION ISN'T FIRING YET TO MAKE BEHAVIOR AWESOME
);
});
| |
doc_23528626
|
I have tried everything really but I am at a dead end here.
if(isset($_POST['submit'])){
$names=$_POST['names'];
$check=$_SESSION['user'];
$queryselect="SELECT `id` FROM `meeting` WHERE `chairman` = '.$check.'";
if($resultselect=mysqli_query($db,$queryselect)){
$row=mysqli_fetch_array($resultselect);
foreach($names as $user){
$queryinsert="INSERT INTO `usermeet` (`id`, `username`) VALUES
('".$row['id']."','".mysqli_real_escape_string($db, $user)."')";
if($resultinsert=mysqli_query($db,$queryinsert)){
echo "<script type='text/javascript'>alert('Meeting have been created')</script>";
header('Location: home.php');
}
else{
echo "bad";
}
}
}
}
A:
i am retreiving a garbage value when print it
How do you actually print it? With echo or var_dump/print_r. Also did you checked your SELECT-Query, for example in phpMyAdmin? And I might be wrong, but the query doesn't look right:
$queryselect="SELECT id FROM meeting WHERE chairman = '".$check."'";
You haven't to enclose column names with quotes. Also you combined the variable and the string not correctly.
Just a tip for debugging: Check every step in your code and its returned values. And use var_dump/print_r for it, not echo. Be aware of all values you have in your code and check if they are exactly what you want them to be.
A: First please check your id is set to auto increment then
Try by Removing " Quotations "
$queryinsert="INSERT INTO `usermeet` (`id`, `username`)
VALUES ('.$row['id'].','.mysqli_real_escape_string($db, $user).')";
A: You haven't to enclose column names with quotes. Also you combined the variable and the string not correctly.
$queryselect="SELECT id FROM meeting WHERE chairman = '".$check."'";
As per you have written a code you have to used mysqli_fetch_array with MYSQLI_ASSOC constant.
mysqli_fetch_array($result,MYSQLI_ASSOC);
| |
doc_23528627
|
@XmlType(name = "V4NetworkCIDRType")
@XmlEnum
public enum V4NetworkCIDRType {
@XmlEnumValue("Y")
Y("Y"),
@XmlEnumValue("N")
N("N");
private final String value;
V4NetworkCIDRType(String v) {
value = v;
}
public String value() {
return name();
}
public static V4NetworkCIDRType fromValue(String v) {
for (V4NetworkCIDRType c: V4NetworkCIDRType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
I have a field with name cird and type is V4NetworkCIDRType.
If I set value for cird is Y or N, it working correctly. But when I send a request JSON format with wrong cidr value:
{
"cidr": "@"
}
It will return 400 Bad request
But when I send request with XML format:
<cidr>@</cidr>
It's OK.
How I can do that with JSON format?
| |
doc_23528628
|
If I update values in the HMI then the values are updated in the spreadsheet of Excel and vice versa. Which is exactly what I want. However, I created a VBA code that will also update values in the spreadsheet when values are changed in the HMI. This VBA code does not run though if I change the values through the HMI but will run if I manually change them in Excel.
Is there something that I am not considering?
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("K1:K3"), Range(Target.Address)) Is Nothing Then
Call UpdateDateandTime
End If
End Sub
Sub UpdateDateandTime()
MsgBox "yes"
End Sub
A: as a crude workaround, If only three cells are involved, may create some simple formula in other cells involving the target cells (if not already exists) and use Worksheet_Calculate() event do the processing. Something like,
Public VarK1, VarK2, Vark3
Private Sub Worksheet_Calculate()
If VarK1 <> Range("K1").Value Or VarK2 <> Range("K2").Value Or Vark3 <> Range("K3").Value Then
VarK1 = Range("K1").Value
VarK2 = Range("K2").Value
Vark3 = Range("K3").Value
'Call the required process
End If
End Sub
though other direct methods involving DDE may be also be available to do the same and may please research/wait further for more appropriate the commands. Another workaround way is to use Application.OnTime method.
| |
doc_23528629
|
Edit: Some additional research, it appears the problem for one of these fields is that Pandas can't handle null integers very well. It looks like I am getting some sort of overflow when it tries to cast a null float to int; when I do explicit cast I get these same values. Is there any way to use the executemany function with null integers?
Edit2: I've tried playing around with the Int64 extension as some answers reference, but still had no luck since it still puts the type as float:
| |
doc_23528630
|
Before it is suggested that I use a list, my next step is to randomize the array to output something different each time its called. That part i have figured out but I keep stumbling on this read to array nonsense.
Here is what I currently have:
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Ashleysaurus\Documents\test.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Dim Str As String
Dim dr As OleDbDataReader
Dim myArray(2, 5) As String
myConnection.Open()
Str = "SELECT Question, Answer1, Answer2, Answer3, Answer4, CorrectAnswer FROM Critters;"
Dim cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
Dim i As Integer = 0
myArray(i, 0) = CType(dr("Question"), String)
myArray(i, 1) = CType(dr("Answer1"), String)
myArray(i, 2) = CType(dr("Answer2"), String)
myArray(i, 3) = CType(dr("Answer3"), String)
myArray(i, 4) = CType(dr("Answer4"), String)
myArray(i, 5) = CType(dr("CorrectAnswer"), String)
i = i + 1
End While
myConnection.Close()
A: You have a simple error. The declaration and the initialization of the variable i should go outside the loop
Dim i As Integer = 0
While dr.Read()
....
But I prefer a lot to use a DataTable with code like this
Dim dt = new DataTable()
dt.Load(cmd.ExecuteReader)
Now you can use the DataTable more or less like a two dimensional array
Dim question as string = dt.Rows(0)(0)
for each row as DataRow in dt.Rows
Console.WriteLine("Question = " & row(0).ToString())
Next
| |
doc_23528631
|
Whenever the user edits a ".txt" File the MDI application should launch and a editor window should be populated with the contents of the chosen ".txt" file .
Is there a way I can do that please.
Thanks
A: In my application, I do this at launch:
[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
private void GetDefaultsFromRegistry()
{
if (Registry.GetValue("HKEY_CLASSES_ROOT\\MyApp", String.Empty, String.Empty) == null)
{
Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\MyApp", "", "My File Type");
Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\MyApp", "FriendlyTypeName", "My Friendly Type Name");
Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\MyApp\\shell\\open\\command", "",
"path\\to\\my\\app \"%1\"");
Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\.ext", "", "MyApp");
//this call notifies Windows that it needs to redo the file associations and icons
SHChangeNotify(0x08000000, 0x2000, IntPtr.Zero, IntPtr.Zero);
}
}
With all paths, names, and extensions changed to your application, of course.
Do be careful with messing with the user's .txt file association, though. I check the assignment on every launch because my application is using a custom type and is only deployed on in-house imaged systems. I don't know where your application is being deployed, but I would be very annoyed if some random utility I downloaded from the internet was constantly changing my .txt file association, and I'm sure a lot of other people would be too.
A: You need to change this reg key:
HKCR\txtfile\shell\open\command
Change the default value to your program with %1 at the end for parameters. Then in your program handle the command line args to do what you want with it.
A: File assocition can programmatically be done like this or it can be done by through registry key like this
| |
doc_23528632
|
The problem here is that the Registration of the Aspose.PDF.dll does not work because of those "ghost" assemblies that are created or atleast that is what I think that the problem is.
So basically: Why are there those "ghost" assemblies?
First off, I got the following components:
-Console application (Main)
-Class library (MyDll)
-3rd party dll in this case Aspose.PDF.dll
Main has no reference to MyDll aswell as no reference to the 3rd party dll.
MyDll has a reference to a specific version of the 3rd party dll.
I want to load the correct version of the Aspose.PDF.dll from a remote location into the AppDomain corresponding of which version MyDll asks for.
To achieve this I subscribe to the AppDomain.AssemblyResolve event.
If MyDll is called and asks for an assembly that the clr can't find I load the corresponding dll with LoadFrom.
This works well so far but while overwatching the loaded assemblies, that I get when I call AppDomain.CurrentDomain.GetAssemblies(), I noticed that there are some assemblies that have a weird name but seeme to be Aspose.PDF assemblies (the public key is the same). Those only appear after certain methods in MyDll are called. All these methods contain Aspose.PDF method calls.
I created an Example to demonstrate this Issue. First the Main console application.
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
Assembly myAssembly = Assembly.LoadFile(@"FullPathToMyDll\MyDll.dll");
Type myType = myAssembly.GetType("myDll.Class1");
var myTypeInstance = Activator.CreateInstance(myType);
myType.InvokeMember("DoAction", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, myTypeInstance, null);
Console.ReadLine();
}
private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
StringBuilder stb = new StringBuilder();
stb.AppendLine(new string('-', 20));
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
stb.AppendLine(assembly.FullName);
}
stb.AppendLine(new string('-', 20));
Console.WriteLine(stb.ToString());
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var nameSplitted = args.Name.Split(',');
Assembly assemblyToReturn = null;
if(args.Name.Contains("19.2.0.0"))
assemblyToReturn = Assembly.LoadFrom(@"FullPathToDll\Apsose_19.2\Aspose.PDF.dll");
if (args.Name.Contains("19.6.0.0"))
assemblyToReturn = Assembly.LoadFrom(@"FullPathToDll\Apsose_19.6\Aspose.PDF.dll");
return assemblyToReturn;
}
}
MyDll.dll:
public class Class1
{
public Class1()
{
Console.WriteLine(Aspose.Pdf.BuildVersionInfo.FileVersion);
Console.WriteLine(Aspose.Pdf.BuildVersionInfo.Product);
Console.WriteLine(Aspose.Pdf.BuildVersionInfo.AssemblyVersion);
}
public void DoAction()
{
// Part of the 3rd party dll
Document doc = new Document();
// After the following line the "ghost assemblies appear"
bool licensed = Document.IsLicensed;
Console.WriteLine(doc.GetType().Assembly.FullName);
}
}
Image of loaded "ghost assemblies"
I wouldn't suppose there should be those "ghost" assemblies and I think they lead to a problem with the registration of the 3rd party dll (which is not included in this example).
This is my first question on stackoverflow so please give me any feedback regarding how I asked my questrion and what I could do better.
A: I hard coded the "weird assembly name" when loading, for examle I used
string fullName = "Aspose.PDF, Version=21.2.0.0, Culture=neutral, PublicKeyToken=f0262d67fe233d63";
| |
doc_23528633
|
I have been trying to find a way to fit a triangle over this image and finding the vertices. I have tried finding corners but the values it returns are not always correct.
Is there any way I can sharpen the edges so that the corner function can return better results?
I appreciate any input! Thanks!
What strategy seems easier and more efficient? What existing MatLab functions could I use?
A: Instead of image processing approach, let's try a more algebraic approach.
You have white pixels - 2D points on a plane, and you wish to find three half-planes (straight lines) that best separate these points from the rest of the plane.
So, let's start
img=imread('http://i.stack.imgur.com/DL2Cq.png'); %// read the image
bw = img(:,:,1) > 128; %// convert to binary mask
[y x] = find(bw); %// get the x-y coordinates of white pixels
n=numel(x); %// how many do we have
For stability we subtract the mean of all points - centering the white pixels around the origin:
mm = mean([x y],1);
mA = bsxfun(@minus, [x y], mm);
Now, a line can be described by two parameters, all the points (x, y) that satisfy L(1)*x + L(2)*y = 1. In order to find a line that all the points are strictly to one side of it, this inequality must hold for all points (x,y) of the set: L(1)*x + L(2)*y <= 1. We can force these inequalities and search for the most tight half plane L that fulfill this constraint using quadprog:
L1 = quadprog(eye(2), -ones(2,1), mA, ones(n,1));
L2 = quadprog(eye(2), ones(2,1), mA, ones(n,1));
L3 = quadprog(eye(2), [1; -1], mA, ones(n,1));
Note how by changing the quadratic optimization target f, we are able to get different half planes separating the white pixels.
Once we have the three lines, we can get the intersection points (shifting them back from the origin by mm):
x12=inv([L1';L2'])*ones(2,1)+mm';
x23=inv([L3';L2'])*ones(2,1)+mm';
x13=inv([L3';L1'])*ones(2,1)+mm';
You can use see the results
imshow(bw,'border','tight');
hold all;
%// plot the lines
ezplot(gca, @(x,y) L1(1)*(x-mm(1))+L1(2)*(y-mm(2))-1, [1 340 1 352]);
ezplot(gca, @(x,y) L2(1)*(x-mm(1))+L2(2)*(y-mm(2))-1, [1 340 1 352]);
ezplot(gca, @(x,y) L3(1)*(x-mm(1))+L3(2)*(y-mm(2))-1, [1 340 1 352]);
%// plot the intersection points
scatter([x12(1) x23(1) x13(1)],[x12(2) x23(2) x13(2)],50,'+r');
A: You can find the minimum area circumscribed triangle.
First compute the convex hull of the blob.
Then try all distinct choices of three sides of the hull, extend the sides by computing the pairwise intersections and keep the triangle with the smallest positive area.
| |
doc_23528634
|
function authenticate(req,res){
username = req.body.username;
password = req.body.password;
db.users.find({$and :[{username:username},{password:password}]},function(err,doc){
if(( Object.keys(doc).length === 0 && doc.constructor === Object) === false){
res.send("Invalid login")
} else {
doc.forEach(function(doc){
console.log(doc.firstname)
})
}
})
}
Im checking if the doc contanis an empty object (which means the username and password didnt match) and telling the page to show that the login is invalid. If the doc does contain a matching username and password, Im console.log()ging the firstname of the user...
The code above is not working...What is it that I am doing wrong?
Thanks in advance...
A: I think that instead of doing what you're doing it would make much more sense if you were to instead to simply run a query for the username with a limit of one result and see if the returned doc contains a result. From there we will check if the posted password matches the one queried from the database and if so we will console.log the username. Furthermore instead of querying for the password you should be first hashing it. read more about that HERE
function authenticate(req,res){
username = req.body.username;
password = req.body.password;
db.users.findOne({"username":username}, function(err, doc) {
if (err) throw err;
if(doc && doc._id){
if(password==doc["password"]){
console.log("Your first name is: "+doc.firstname)
}else{
res.send("Invalid login")
}
}else{
res.send("Invalid login")
}
});
}
| |
doc_23528635
|
However I've discovered today that there's a problem with multi-dimension $_REQUEST arrays, and I'm wondering if there's a way around it.
To test, I used a form with the fields:
<input name="one[one]" />
<input name="one[two]" />
<input name="three[four[five]]" />
<input name="three[four[six]]" />
Once this was submitted, I used var_dump to see the array structure:
array(3) {
["one"]=>
array(2) {
["one"]=>
string(0) ""
["two"]=>
string(0) ""
}
["three"]=>
array(2) {
["four[five"]=>
string(0) ""
["four[six"]=>
string(0) ""
}
}
The one element is array-ified as expected. But the three element is not. Now I wouldn't mind if it just wasn't supported, but what's got me confused is the reason why. Look at the names of the sub-elements of three - four[five and four[six. It's not being interpreted as an array because for some reason the trailing ] which would help to identify these elements as array values has been lost!
Does anyone have an explanation for this? Is there any way around it, other than to only use a maximum of one level in $_REQUEST arrays?
A: Try three[four][five] and three[four][six] instead.
A: The input names correspond completely to variable "names".
You'd write in PHP:
$three['four']['five'] = 'trees';
Likewise in your HTML:
<input name="three[four][five]" value="trees" />
| |
doc_23528636
|
So VK_W = 87 and it saves 87 in a config file. So i want to have a Choice or button that can pick what VK/number that will be pick to be KeyPressed.
Here is my code
public class Twitchbot extends PircBot {
int VK_W = 87;
int VK_S = 83;
int[] saveInformation = {VK_W, VK_S};
int VK_WLoc = 0;
int VK_SLoc = 1;
public Twitchbot() {
configRead("Config.cfg");
updateConfig();
configSave("Config.cfg");
this.setName("Rex__Bot");
}
private void updateConfig(){
System.out.println(VK_W);
System.out.println(VK_S);
VK_W = saveInformation[VK_WLoc];
VK_S = saveInformation[VK_SLoc];
System.out.println(VK_W);
System.out.println(VK_S);
}
private void configRead(String filePath) {
File inputFile;
BufferedReader inputReader;
try {
inputFile = new File(filePath);
inputReader = new BufferedReader(new FileReader(inputFile));
for(int i = 0; i < saveInformation.length; i++){
saveInformation[i] = Integer.parseInt(inputReader.readLine());
}
System.out.println(filePath);
inputReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void configSave(String filePath) {
File outputFile;
BufferedWriter outputWriter;
try {
outputFile = new File(filePath);
outputWriter = new BufferedWriter(new FileWriter(outputFile));
for(int i = 0; i < saveInformation.length; i++){
outputWriter.write(Integer.toString(saveInformation[i]) + "\n");
}
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onMessage(String channel, String sender, String login, String hostname, String message) {
if(message.equals("up")) {
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_W);
r.delay(300);
r.keyRelease(KeyEvent.VK_W);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
| |
doc_23528637
|
In excel (2010) I have a section of data referring to test results. The data looks roughly like this:
Each run inserts a new line at the top (row 2) with the latest results. From this I am trying to produce a chart that shows only the results from the last 7 runs, so the data in B1:E8. I can do by either direct reference, named range or converting to a table. The problem with the first two methods are that when I insert a new line under the headers the range then splits so that I have B1:E1 and B3:E9. The table method is slightly better in that it includes the newly inserted row but keeps the range set to the same bottom row (so it ends up referencing 8 rows of data).
Am i missing something obvious here? I'd prefer the data to be listed like this with the newest on the top, but I'm sure I can change it so the newest is at the bottom if anyone has a good idea!
Thanks in advance!
A: You can use INDIRECT formula on another worksheet to capture part of your table from Sheet1, like this:
=INDIRECT("Sheet1!B1:E8")
And then specify that as your chart data range.
Just remember to use INDIRECT as array formula:
*
*Enter =INDIRECT("Sheet1!B1:E8") in Sheet2!B1 cell.
*Select B1:E8 range.
*Press F2 and then Ctrl-Shift-Enter to make it an array formula.
A: I would use a Pivot Chart.
You can apply a filter on these charts to only look at the Top X results. So if you filter to show Top 7 by Date, then this should do the trick.
You might need to lookup a quick tutorial on Pivots and Pivot Charts if you don;t have any experience though.
They are incredibly valuable though, so I would recommend it regardless.
| |
doc_23528638
|
I am using MahApps.Metro v1.6.5 and MahApps.Metro.IconPacks v2.3.0.
I have tried to set Padding, HorizontalAlignment and VerticalAlignment for the button, but it didn't solve the problem.
<controls:DropDownButton ArrowVisibility="Hidden" ItemsSource="{Binding MenuItems}" BorderThickness="0" Focusable="False">
<controls:DropDownButton.Icon>
<iconPacks:PackIconEntypo Kind="Menu" VerticalAlignment="Center" HorizontalAlignment="Center" />
</controls:DropDownButton.Icon>
</controls:DropDownButton>
Screenshot: https://i.ibb.co/4NhXZ8S/Untitled.png
I am trying to align the icon inside DropDownButton, but can't remove the padding (you can see it on the screenshot).
A: Okay, I found the problem. It was arrow, which is visible by default:
https://i.ibb.co/CQmZn3p/Screenshot-22.png
It occupies the space for itself even if it is hidden (ArrowVisibility="Hidden"). In this case ArrowVisibility="Collapsed" should be used instead, it solves the problem.
| |
doc_23528639
|
http://www.srigranth.org/servlet/gurbani.gurbani?Action=Page&Param=1&g=1&h=0&r=0&t=0&p=0&k=0&fb=0
A: JSoup allows you to read a web page and iterate over its content elements.
Sting yourURL = "servlet/gurbani.gurbani?Action=Page&Param=1&g=1&h=0&r=0&t=0&p=0&k=0&fb=0";
Document doc = Jsoup.connect(yourURL).get();
I don't understand what's on that page, but it looks like the text you're after might be the inner html of a links with class dict. If that's the case,
Elements links = doc.select("a.dict");
will give you an iterable collection of Element of which you can easily extract the text content:
for (Element word : links) {
String theTextyoureafter = word.html();
}
That's the basic idea, you'll probably need to experiment a bit to get it "just right", but there are also a lot of examples on the Jsoup website.
| |
doc_23528640
|
http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false
in this url betwn source and destination we can pass waypoints
but how i can pass waypoints for kml url
http://maps.google.com/maps?f=d&hl=en&saddr=9.036597,77.536&daddr=8.919942,77.669208&ie=UTF8&0&om=0&output=kml
i have tried like this
http://maps.google.com/maps?f=d&hl=en&saddr=9.157283,77.544239&daddr=9.035239,77.784564&waypoints=9.036597,77.536|8.919942,77.669208&sensor=false&ie=UTF8&0&om=0&output=kml
but it is not worked so how i can pass waypoints multiple lat and long between source and destination?
A: There's no documented way to do that. The KML interface om maps.google.com isn't really an "API" like the Directions API with formal documentation and specs... it's just a commonly used service for simple requests.
Your best bet is to work with the JSON/XML from the directions service and transform it into KML (if you can't consume it directly).
| |
doc_23528641
|
In this example, we'd select Yellow for any times before noon. Being the row for 7:00AM, we would like the Timeslot label saying "7am" to have a yellow background color based on the hour of the day being before noon.
<tr data-time="07:00:00">
<td class="fc-axis fc-time fc-widget-content" style="width: 36px;">
<span>7am</span>
</td>
<td class="fc-widget-content">
</td>
</tr>
A: Just an idea. You can do something like this:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
eventAfterAllRender: function(view) {
$('.fc-axis.fc-time').each(function() {
$(this).addClass(getClass($(this).parent().data('time')));
})
}
});
function getClass(timePart) {
var hour = parseInt(moment("2016-12-20T" + timePart).format("H"));
if (hour >= 6 && hour < 9) {
return "morning";
} else if (hour >= 9 && hour < 20) {
return "day";
} else {
return "evening";
}
}
Fiddle
| |
doc_23528642
|
GOAL: The application is full of input elements that are styled up to look like custom buttons. They are of various types e.g. 'submit', 'reset' and 'button'. When the user hits the button (i.e. clicks it with their mouse on PC or touches the screen on the right place on a touch-screen device e.g. BlackBerry) the button text and background should change to indicate the button has been pushed. The text and background should revert before the action associated with the button is executed - to indicate the button has been released.
Here is the snippet of the code that I have for my solution - can anyone see ways to improve/slim/refactor?
<script type="text/javascript">
$(document).ready(function () {
RegisterJQueryFunctions();
});
</script>
In an external file:
function RegisterJQueryFunctions() {
$('input[type=submit], input[type=button], input[type=reset]').mousedown(function () {
// Record the original font and BG colors so we can revert back to them in 'delight'
var originalFont = $(this).css("color");
var originalBG = $(this).css("background-color");
$(this).data("originalFont", originalFont);
$(this).data("originalBG", originalBG);
$(this).highlightBG();
$(this).highlightFont();
});
$('input[type=submit], input[type=button], input[type=reset]').mouseup(function () {
$(this).revertFont();
$(this).revertBG();
});
$.fn.highlightFont = function (highlightFontColor) {
var highlightFont = highlightFontColor || "#FFFFFF"; // Defaults to white
$(this).css("color", highlightFont);
};
$.fn.highlightBG = function (highlightBGColor) {
var highlightBg = highlightBGColor || "#FF7F00"; // Defaults to orange
$(this).css("background-color", highlightBg);
};
$.fn.revertFont = function () {
var originalFont = $(this).data("originalFont");
if (!originalFont.length)
originalFont = "#000000"; // Defaults to black in case data attribute wasn't set properly in highlightFont
$(this)
.css("color", originalFont);
};
$.fn.revertBG = function () {
var originalBG = $(this).data("originalBG");
if (!originalBG.length)
originalBG = "#FEC800"; // Defaults to orange in case data attribute wasn't set properly in highlightFont
$(this)
.css("background-color", originalBG);
};
}
A: Using CSS (class), you can reduce the size of your code drastically. Secondly CSS will give the option of changing colors without altering your javascript (Themes). The sole purpose of CSS is to give look and feel to the site & for javascript, add dynamic behavior to the site.
Hope this helps.
A: This is how you would do it with CSS. If you want the pressed look to be the following CSS
.pressed { color : #ffffff; background-color : #FEC800; }
Then your functions are simple:
function RegisterJQueryFunctions() {
$('input[type=submit], input[type=button], input[type=reset]')
.mousedown(function () { $(this).toggleClass("pressed",true); })
.mouseup(function () { $(this).toggleClass("pressed",false); });
}
You can have different pressed looks for different input types (using standard CSS selectors).
You are separating the styling from the code (always a good thing.)
A: *
*If you're using the same jQuery selector several times you should cache the
first jQuery object returned and reuse it
*If you're calling several jQuery methods on the same jQuery object you can chain them
*I dislike single-use variables: if a variable is only assigned a value in one
place and that value is only used in one (other) place then you don't need it
*If setting more than one value with .data() (or .attr() or in several other jQuery methods) you can do all with a single call by putting the properties in a map
So:
function RegisterJQueryFunctions() {
$('input[type=submit], input[type=button], input[type=reset]').mouseup(function () {
$(this).revertFont().revertBG();
})
.mousedown(function () {
// Record the original font and BG colors so we can revert back to them in 'delight'
var $this = $(this);
$this.data({"originalFont" : $this.css("color"),
"originalBG" :, $this.css("background-color")
})
.highlightBG()
.highlightFont();
});
$.fn.highlightFont = function (highlightFontColor) {
$(this).css("color", highlightFontColor || "#FFFFFF");// Defaults to white
};
$.fn.highlightBG = function (highlightBGColor) {
$(this).css("background-color", highlightBGColor || "#FF7F00";);
};
$.fn.revertFont = function () {
var $this = $(this);
// Defaults to black in case data attribute wasn't set properly in highlightFont
$this.css("color", $this.data("originalFont") || "#000000");
};
$.fn.revertBG = function () {
var $this = $(this);
// Defaults to orange in case data attribute wasn't set properly in highlightFont
$this.css("background-color", $this.data("originalBG") || "#FEC800");
};
}
A: Using a combination of the above advice, this is the solution is ended up with:
$('input[type=submit], input[type=button], input[type=reset]')
.mousedown(function () { $(this).toggleClass("pressed", true); })
.mouseup(function () { $(this).toggleClass("pressed", false); })
.focusout(function () { $(this).toggleClass("pressed",false); });
$('a,a>*')
.mousedown(function () { $(this).toggleClass("pressed",true); })
.mouseup(function () { $(this).toggleClass("pressed", false); })
.focusout(function () {
$(this).toggleClass("pressed", false);
$(this).children().toggleClass("pressed", false); // call explictily because some elements don't raise the 'focusout' event
});
| |
doc_23528643
|
main.py:
import pygame as pg
from classes import *
from settings import *
pg.font.init()
HEALTH_FONT = pg.font.SysFont('comicsans', 20)
pg.display.set_caption("Testa Game")
ground_surface = pg.image.load('graphics/ground.png').convert()
BG_COLOR = (0, 255, 255)
BLACK = (0, 0, 0)
run = True
while run == True:
clock = pg.time.Clock()
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
exit()
clock.tick(FPS)
keys_pressed = pg.key.get_pressed()
health_text = HEALTH_FONT.render("Health: " + str(class_type.health), 1, BLACK)
WIN.fill(BG_COLOR)
WIN.blit(class_type.karakter_surface, (class_type.karakter.x, class_type.karakter.y))
WIN.blit(ground_surface, (0, 350))
WIN.blit(health_text, (10, 10))
karakter_moving(keys_pressed, class_type.karakter)
pg.display.flip()
settings.py:
import pygame as pg
from classes import *
WIDTH, HEIGHT = 900, 500
WIN = pg.display.set_mode((WIDTH, HEIGHT))
class_type = death_mage
FPS = 60
def karakter_moving(keys_pressed, karakter):
if keys_pressed[pg.K_w] and karakter.y - class_type.speed > 0:
karakter.y -= class_type.speed
if keys_pressed[pg.K_s] and karakter.y + class_type.speed + karakter.height < HEIGHT - 5:
karakter.y += class_type.speed
if keys_pressed[pg.K_a] and karakter.x - class_type.speed > 0: #LEFT
karakter.x -= class_type.speed
if keys_pressed[pg.K_d] and karakter.x + class_type.speed + karakter.width < WIDTH:
karakter.x += class_type.speed
classes.py:
import pygame as pg
from settings import WIN
pg.init()
def fire_ball():
fireball = []
maxFireBall = 3
manacost = 1
color = 'ORANGE'
for event in pg.event.get():
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE and len(fireball) < maxFireBall:
dmFireBall = pg.Rect(
death_mage.karakter.x + death_mage.karakter.width, death_mage.karakter.y + death_mage.karakter.height//2 - 2, 10, 5)
fireball.append(dmFireBall)
death_mage.mana -= manacost
pg.draw.rect(WIN, color, fireball)
class death_mage:
KARAKTER_WIDTH, KARAKTER_HEIGHT = 60, 85
karakter = pg.Rect(400, 200, KARAKTER_WIDTH, KARAKTER_HEIGHT)
karakter_surface = pg.transform.scale(pg.image.load('Assets/death_mage.png'), (KARAKTER_WIDTH, KARAKTER_HEIGHT))
health = 10
mana = 5
attack = 1
speed = 2
attack_speed = 1
crit_rate = 0
crit_damage = 0
Error message:
"settings.py", line 12, in <module>
class_type = death_mage
NameError: name 'death_mage' is not defined
or if settings.py: from classes import death_mage
"settings.py", line 3, in <module>
from classes import death_mage
ImportError: cannot import name 'death_mage' from partially initialized module 'classes' (most likely due to a circular import)
How can I remedy this?
Thanks to helping me
A: One of your modules has got no urls.py
| |
doc_23528644
| ||
doc_23528645
|
$CopyFromUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyToUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyFromUser.MemberOf | Where{$CopyToUser.MemberOf -notcontains $_} | Add-ADGroupMember -Members $CopyToUser
pause
This is the error that I'm getting.
| A positional parameter cannot be found that accepts argument
| 'Microsoft.ActiveDirectory.Management.ADPropertyValueCollection'.
A: Add the group memberships one at a time, explicitly pass the target DN to the -Identity parameter:
$CopyFromUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyToUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyFromUser.MemberOf |Where-Object {$CopyToUser.MemberOf -notcontains $_} |ForEach-Object {
Add-ADGroupMember -Identity $_ -Members $CopyToUser
}
| |
doc_23528646
|
<input
id="googleLink"
onclick="window.open('https://www.google.com', '_blank');"
style="display: none"
>
And I tried to click it with Typescript
this.googleLink = document.getElementById("googleLink") as HTMLElement;
this.googleLink.click();
And read this
window.open(url, '_blank'); not working on iMac/Safari
But none of it helps. I am not running my code in an async function. What can I do? I have an iPhone 11 and 7 and on both, it does not work. It works just fine on android and pc. I need the URL to be opened in a new window.
I need to do this with the onClick since I am using pixi js and it is a pixi container that is being clicked.
Setting the href won't help either because I want the page to open in a new tab.
A: This should work on safari as well, but you can add a target to the link by adding target="_blank". This opens the link in a new tab and should also open in a new window on safari. Here is an example:
<a href="https://example.com" target="_blank">Link text.</a>
In your case wrap the input in a link:
<input
id="googleLink"
style="display: none"
>
If you dont want to do this with html and instead an onclick function, you could also use the onclick="location.href='https://example.com'"
A: You can try the below
<canvas id="myCanvas" width="200" height="100" style="border: 1px solid #000;" onclick="myFunction('thisURL')"></canvas>
<script>
function myFunction(url) {
window.open(url, '_blank').focus();
}
</script>
A: Have you checked if you have Block pop-up windows disabled in Safari Security settings? The same thing applies to mobile versions of Safari.
A: Try to replace async with a defer attribute in your script.
| |
doc_23528647
|
http://testserver.glow-berlin.de/kurzfilmwettbewerb
this is the website we're talking about.
At the bottom (right above the footer) you find an image that is supposed to stick to the bottom of the pink box.
Whenever I check it on mobile, the image offsets outside of the box. I built the section using the grid system but struggled with it, so I removed it for mobile... I just couldn't figure out the problem. Now – without the grid system – the same problem appears. On Android it seems to work fine but on iOS the image jumps out of the box again. When I fix it for iOS the problem appears on Android.
Any help with this?
A: The background-attachment: fixed; style on your div with the ID #gutfilmer is the problem on iOS.
'background-attachment: fixed has been disabled on iOs since it costs a lot on mobile browsers.
If you remove it the filmflap stays on the pink background.
A: try
#gutfilmer {
overflow:hidden;
}
| |
doc_23528648
|
0 3 6
1 4 7
2 5 8
using a reverse iterator I get the following output:
8 5 2
7 4 1
6 3 0
The output I need is:
6 3 0
7 4 1
8 5 2
how would i go about getting that required ordering, at first it seems like i would be able to get a reverse iterator position - vertical size but that gets tricky when my vector is something like this:
0 6 12
1 7 13
2 8 14
3 9 15
4 10 16
5 11 17...
| |
doc_23528649
|
I have a dataframe:
A B C
0 1.438161 -0.210454 -1.983704
1 -0.283780 -0.371773 0.017580
2 0.552564 -0.610548 0.257276
3 1.931332 0.649179 -1.349062
4 1.656010 -1.373263 1.333079
5 0.944862 -0.657849 1.526811
which I can easily plot as a boxplot for each column using seaborn:
sns.boxplot(df)
However swarmplots, stripplots dont work, I guess because categorical data is needed?
value indx
1.438161 A
-0.283780 A
...
0.552564 B
1.931332 B
...
1.656010 C
0.944862 C
Is there a very easy quick way to do this, that Im not aware of?
https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.swarmplot.html
A: I think you need parameter data:
sns.boxplot(data=df)
Docs:
data : DataFrame, array, or list of arrays, optional
Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.
A: IIUC, you can use melt to convert one of the variables into categorical format to aid in the plotting of swarmplots and stripplots.
In [3]: df_sns = pd.melt(df, value_vars=['A', 'B', 'C'])
In [4]: df_sns
Out[4]:
variable value
0 A 1.438161
1 A -0.283780
2 A 0.552564
3 A 1.931332
4 A 1.656010
5 A 0.944862
6 B -0.210454
7 B -0.371773
8 B -0.610548
9 B 0.649179
10 B -1.373263
11 B -0.657849
12 C -1.983704
13 C 0.017580
14 C 0.257276
15 C -1.349062
16 C 1.333079
17 C 1.526811
In [5]: sns.swarmplot(x='variable', y='value', data=df_sns)
Out[5]: <matplotlib.axes._subplots.AxesSubplot at 0x268db2a6e10>
| |
doc_23528650
|
Is there a way to do this operation with Pandas in Python?
Thanks!
A: Unfortunately no build-in method exist, as you'll need to build cartesian product of those DataFrame check that fancy explanation of merge DataFrames in pandas
But for your specific problem, try this:
import pandas as pd
import numpy as np
df1 = pd.DataFrame(columns=['Entity', 'Account'])
df1.Entity = ['Entity1', 'Entity1']
df1.Account = ['Sales', 'Cost']
df2 = pd.DataFrame(columns=['Region'])
df2.Region = ['North America', 'Europa', 'Asia']
def cartesian_product_simplified(left, right):
la, lb = len(left), len(right)
ia2, ib2 = np.broadcast_arrays(*np.ogrid[:la,:lb])
return pd.DataFrame(
np.column_stack([left.values[ia2.ravel()], right.values[ib2.ravel()]]))
resultdf = cartesian_product_simplified(df1, df2)
print(resultdf)
output:
0 1 2
0 Entity1 Sales North America
1 Entity1 Sales Europa
2 Entity1 Sales Asia
3 Entity1 Cost North America
4 Entity1 Cost Europa
5 Entity1 Cost Asia
as expected.
Btw, please provide the Data Frame the next time as code, not as a screenshot or even as link. It helps up saving time (please check how to ask)
| |
doc_23528651
|
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^xxx\.xx\.xxx\.xx/domain\.com [NC]
RewriteRule (.*) http://xxx.xx.xxx.xx/domain.com/$1 [R=301,L]
Website isn't available, this is error I get:
The page isn't redirecting properly
How to create this redirect?
A: The %{HTTP_HOST} variable does not contain any URI path elements in it, it is only the hostname that is given as the Host: request header. This is usually what appears in the hostname part of a URL:
*
*http://www.google.com/blahblahblah = www.google.com
*http://localhost/foo/bar/zzzzz = localhost
*http://123.45.67.89/something/something/ = 123.45.67.89
Just get rid of all of the URI from your condition:
RewriteCond %{HTTP_HOST} !^xxx\.xx\.xxx\.xx$ [NC]
A: Try replacing
RewriteCond %{HTTP_HOST} !^xxx\.xx\.xxx\.xx/domain\.com [NC]
with this
RewriteCond %{SERVER_ADDR} !xxx\.xx\.xxx\.xx
| |
doc_23528652
|
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class ResizableRubberBand(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ResizableRubberBand, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.SubWindow)
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(
QtWidgets.QSizeGrip(self), 0,
QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
layout.addWidget(
QtWidgets.QSizeGrip(self), 0,
QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)
self._band = QtWidgets.QRubberBand(
QtWidgets.QRubberBand.Rectangle, self)
self._band.show()
self.show()
def resizeEvent(self, event):
size = QtCore.QSize(3, 4)
size.scale(self.size(), QtCore.Qt.KeepAspectRatio)
self.resize(size)
self._band.resize(self.size())
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.button = QtWidgets.QPushButton('Show Rubber Band')
self.button.clicked.connect(self.handleButton)
self.label = QtWidgets.QLabel()
self.label.setScaledContents(True)
self.label.setPixmap(QtGui.QPixmap('image.JPG'))
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.button)
def handleButton(self):
self.band = ResizableRubberBand(self.label)
self.band.setGeometry(50, 50, 150, 300)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(800, 100, 600, 500)
window.show()
sys.exit(app.exec_())
A: You're on the right track. PyQt uses event handlers to control mouse interaction and resize events. For your application, resizing grips will call resizeEvent and repainting the changed window involves paintEvent. Similarly, mouse interaction utilizes mousePressEvent, mouseMoveEvent, and mouseReleaseEvent as event handlers are called when these actions are triggered. Essentially, for each interaction that you want, you must implement the handler for that particular event. I used PyQt4 to test but it should be the same for PyQt5.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
# from PyQt4 import QtCore, QtWidgets
class ResizableRubberBand(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ResizableRubberBand, self).__init__(parent)
self.draggable = True
self.dragging_threshold = 5
self.mousePressPos = None
self.mouseMovePos = None
self.borderRadius = 5
self.setWindowFlags(QtCore.Qt.SubWindow)
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(
QtWidgets.QSizeGrip(self), 0,
QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
layout.addWidget(
QtWidgets.QSizeGrip(self), 0,
QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)
self._band = QtWidgets.QRubberBand(
QtWidgets.QRubberBand.Rectangle, self)
self._band.show()
self.show()
def resizeEvent(self, event):
self._band.resize(self.size())
def paintEvent(self, event):
# Get current window size
window_size = self.size()
qp = QtWidgets.QPainter()
qp.begin(self)
qp.setRenderHint(QtWidgets.QPainter.Antialiasing, True)
qp.drawRoundedRect(0, 0, window_size.width(), window_size.height(),
self.borderRadius, self.borderRadius)
qp.end()
def mousePressEvent(self, event):
if self.draggable and event.button() == QtCore.Qt.RightButton:
self.mousePressPos = event.globalPos() # global
self.mouseMovePos = event.globalPos() - self.pos() # local
super(ResizableRubberBand, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.draggable and event.buttons() & QtCore.Qt.RightButton:
globalPos = event.globalPos()
moved = globalPos - self.mousePressPos
if moved.manhattanLength() > self.dragging_threshold:
# Move when user drag window more than dragging_threshold
diff = globalPos - self.mouseMovePos
self.move(diff)
self.mouseMovePos = globalPos - self.pos()
super(ResizableRubberBand, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self.mousePressPos is not None:
if event.button() == QtCore.Qt.RightButton:
moved = event.globalPos() - self.mousePressPos
if moved.manhattanLength() > self.dragging_threshold:
# Do not call click event or so on
event.ignore()
self.mousePressPos = None
super(ResizableRubberBand, self).mouseReleaseEvent(event)
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.button = QtWidgets.QPushButton('Show Rubber Band')
self.button.clicked.connect(self.handleButton)
self.label = QtWidgets.QLabel()
self.label.setScaledContents(True)
self.label.setPixmap(QtGui.QPixmap('image.JPG'))
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.button)
def handleButton(self):
self.band = ResizableRubberBand(self.label)
self.band.setGeometry(150, 150, 150, 150)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(800, 100, 600, 500)
window.show()
sys.exit(app.exec_())
| |
doc_23528653
|
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
def block(in_feat, out_feat, normalize=True):
layers = [nn.Linear(in_feat, out_feat)]
if normalize:
layers.append(nn.BatchNorm1d(out_feat, 0.8))
layers.append(nn.LeakyReLU(0.2, inplace=True))
return layers
self.model = nn.Sequential(
*block(opt.latent_dim, 128, normalize=False),
*block(128, 256),
*block(256, 512),
*block(512, 1024),
nn.Linear(1024, int(np.prod(img_shape))),
nn.Tanh()
)
A: *x is iterable unpacking notation in Python. See this related answer.
def block returns a list of layers, and *block(...) unpacks the returned list into positional arguments to the nn.Sequential call.
Here's a simpler example:
def block(in_feat, out_feat):
return (nn.Linear(in_feat, out_feat), nn.LeakyReLU(0.2, inplace=True))
self.model = nn.Sequential(
*block(128, 256),
)
# Equivalent to:
# layers = block(128, 256)
# self.model = nn.Sequential(layers[0], layers[1])
# Also equivalent to:
# layers = block(128, 256)
# self.model = nn.Sequential(*layers)
| |
doc_23528654
|
I have Vue component which has data object and pId -key with value.
I have checked that pId has value.
Profile ID: {{ pId }}
Gives value 1.
data() {
return {
pId: ''
}
},
methods: {
loadProfile(){
this.status = 'Loading ....';
axios.get("/profile/${pId} ")
.then(function(response){
this.profile = response.data.profile;
})
.catch(e => {
this.errors.push(e)
})
},
init(){
console.log('Profile mounted');
EventBus.$on('creds' , key =>{
[this.pId, this.uId] = key;
})
}
mounted(){
this.init()
},
created: function() {
this.loadProfile();
}
*
*When I pass pId like this:
axios.get("/profile/${pId} "
*URL is: http://192.168.10.101:8000/profile/$%7BpId%7D
*which means that pId is string not value.
*I have tried this
axios.get("/profile " + this.pId)
*which gives me http://192.168.10.101:8000/profile
*without profile id,
*also tried pass id as parameter, but it is not correct way.
*if I hard code profile id, I will get profile from Laravel,
*http://192.168.10.101:8000/profile/1
*so route is okey in Laravel side.
thanks Mika.
A: You have to use `` for template string.
So correct way is: axios.get(`/profile/${this.pId}`)
A: Strings containing variables need to be wrapped in a grave accent ( ` ) not single quote ( ' ) or double quote ( " )
const myValue
const myString = `This is the value: ${myValue}`
Also make use of passing props directly from the router:
https://router.vuejs.org/guide/essentials/passing-props.html
// ROUTER
const router = new VueRouter({
routes: [
{ path: '/profile/:pId', component: Profile, props: true }
]
})
So you code should look as follows:
// Profile.vue
<template></t
<script>
export default {
name: 'profile',
props: ['pId'],
methods: {
loadProfile() {
const vm = this // Ensure expected scope of reference to "this" is maintained in the anonymous Axios callback functions as the component:
const pId = this.$route.
vm.status = 'Loading ....';
axios.get(`/profile/${vm.pId}`)
.then(response => {
vm.profile = response.data.profile;
})
.catch(e => {
vm.errors.push(e)
})
}
init() {
console.log('Profile mounted');
const vm = this
EventBus.$on('creds' , key => {
[vm.pId, vm.uId] = key;
})
}
mounted () {
this.init()
},
created () {
this.loadProfile();
}
}
</script>
A: Finally resolved problem:
*
*first created separate file for EventBus.js.
import Vue from 'vue'
export default new Vue()
*sender component: (Dashboard)
convert props data to data object.
props: { pId: },
data() { return { profileId: this.pId } },
*created methods:
{ init(){ const payload = {
profileId: this.profileId }
EventBus.$emit('creds' , payload);
console.log('profile id sent: ', payload.profileId );
}
}
*Receiver component:
data() {
return {
status: '',
profileId:'Loading up...',
`methods: {`
` updateData (payload ) { `
this.profileId = payload
this.loadProfile(this.profileId);
},
init(){
EventBus.$on('creds', (payload) => {
this.updateData(payload.profileId)
})
},
Finally passed + this.profileId to Axios.
loadProfile(){
this.status = 'Loading ....';
axios({
url: '/profile/' + this.profileId,
method: 'get'
})
... No needed vue-router, only to understand how EventBus works.
Thanks to this link: https://medium.com/easyread/vue-as-event-bus-life-is-happier-7a04fe5231e1
| |
doc_23528655
|
.button {
-fx-background-color: #44c553;
-size: 100px;
-fx-min-height: -size;
-fx-min-width: -size;
-fx-max-height: -size;
-fx-max-width: -size;
-fx-shape: "m207.10955,279.95363l101.61276,-154.83848l101.61276,154.83848l-203.22552,0z" ;
}
the problem is that when i hover mouse on button i can press it from outside of its shape because the button borders are still rectangular. how can i make the button not clickable from outside of its shape?
A: Node has the pickOnBounds property:
Defines how the picking computation is done for this node when triggered by a MouseEvent or a contains function call. If pickOnBounds is true, then picking is computed by intersecting with the bounds of this node, else picking is computed by intersecting with the geometric shape of this node.
This property has a default value of false, which is what you want. However, the Region class sets this property to true in its only constructor:
Creates a new Region with an empty Background and and empty Border. The Region defaults to having pickOnBounds set to true, meaning that any pick (mouse picking or touch picking etc) that occurs within the bounds in local of the Region will return true, regardless of whether the Region is filled or transparent.
Since Button is a subclass of Region it also has its pickOnBounds property set to true. In order to have the behavior you want you'll need to set this property back to false. Unfortunately, pickOnBounds doesn't seem settable from CSS; meaning you'll need to set it from code or FXML.
| |
doc_23528656
| ||
doc_23528657
|
public JSONObject postRequest(String url) {
OutputStream output;
InputStream inputStream = null;
String result = "";
JSONObject response = null ;
File file = null;
HttpResponse httpResponse;
try {
String directoryPath = "SirConrad";
File newFolder = new File(Environment.getExternalStorageDirectory(), directoryPath);
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
file = new File(newFolder, "sachsd.docx");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("accessToken","29c1322d3072d8fadbf2478c61fb6ff6");
httpGet.addHeader("content_type","application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//httpGet.addHeader("UserID", "4");
httpResponse = httpclient.execute(httpGet);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
output = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return response;
}
P.S Link http://pp.sirconrad.com/img/EDDYAdminPanelDesignBreakdown.docx work for me to download attachment in above code but.
Note* i am using Pivotal Traker apis to download this file.
| |
doc_23528658
|
public enum Month {JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7),
AUG(8), SEPT(9), OCT(10), NOV(11), DEC(12);
final int monthBoundary;
Month(int y){
monthBoundary=y;}
}
public enum Date {FIRST(1), SECOND(2), THIRD(3), FORTH(4),
FIFTH(5)... THIRTYFIRST(31);
final int dateBoundary;
Date(int z){
dateBoundary=z;}
}
//constructor etc here
private static final List<Cal> calendar = new ArrayList<Cal>();
static {
for (Month month : Month.values()) {
for (Date date : Date.values()) {
calendar.add(new Cal(date, month));
}
}
}
//creates new calendar dates
public static ArrayList<Cal> newCal() {
return new ArrayList<Cal>(calendar);
}
Using the following statement i can print the array in the order its created.
System.out.print(Card.calendar());
How do you create a Comparator class to sort these dates in descending order?
Ideally i would like it to sort the array whether it was already in order or in a random order.
At this stage i am not concerned about dates that do not exist (e.g. Feb 31st) as i'm merely practising and self studying... Just trying to get the concept :)
Thanks.
ADDED:
public ArrayList<Cal> sortDescending(ArrayList<Cal> calList){
Comparator<Cal> c = Collections.reverseOrder();
Collections.sort(calList, c);
return calList;
}
A: Collections.sort(list, new Comparator<Cal>() {
@Override
public int compare(Cal cal1, Cal cal2) {
int result = -cal1.getMonth().compareTo(cal2.getMonth()));
if (result == 0) {
result = -cal1.getDate().compareTo(cal2.getDate()));
}
return result;
}
});
| |
doc_23528659
|
When running the application, it receives the message, generates the data and sends them on the right queue. The data are well received on the server and they are correct. But when the application tries to send an acknowledgement to the server, I get an AlreadyClosedException.
I have the following message in the logs of the server: closing AMQP connection.
Here is the code of the handleDelivery function, in the rabbitMQ consumer class:
public void handleDelivery( String consumerTag, Envelope envelope, asicProperties properties, byte[] body )
throws IOException {
actionManager.receivedSelectedData( body );
getChannel().basicAck( envelope.getDeliveryTag(), false );
}
Here is the code in the method receivedSelectedData(), where the data are generated before being sent:
public void receivedSelectedData( byte[] body ) {
differentialEquations = differentialEquationsObjectManager.fromBytes( body );
timeSeriesCollection.removeAllSeries();
for ( int i = 0; i < differentialEquations.size(); i++ ) {
differentialEquation = differentialEquations.get( i );
for ( int j = 0; j < differentialEquation.getSystems().size(); j++ ) {
try {
generator = new NumericalMethod( differentialEquation, j );
} catch ( Exception e ) {
e.printStackTrace();
}
try {
timeSeriesCollection.addSeries( generator.equationToTimeseriesRK4( 10.0 ) );
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
sender.publish( RabbitMQGenerateSender.GENERATE_DATA_QUEUE_NAME,
timeSeriesCollectionObjectMnanager.toBytes( timeSeriesCollection ) );
}
The queue seems to be correctly declared, here is my queue declaration:
protected void declareQueue( String queueName ) {
try {
channel.queueDeclare( queueName, true, false, false, null );
} catch ( IOException e ) {
e.printStackTrace();
}
}
and the channel declaration:
try {
connection = factory.newConnection();
channel = connection.createChannel();
int prefetchCount = 1;
channel.basicQos( prefetchCount );
} catch ( IOException | TimeoutException e ) {
e.printStackTrace();
}
I have some other applications using rabbitmq with the same channel and queue declaration parameters and they work well. I only have one application that systematically fails when sending acknowledgment.
Here is the getChannel() method:
public Channel getChannel() {
return channel;
}
A: The receiver queue must be declared as AutoDelete = false if ACK functionality is to be supported.
Here is an example in C# (there might be small differences than Java)
private bool PushDataToQueue(byte[] data, string queueName, ref string error)
{
try
{
if (_connection == null || !_connection.IsOpen)
_connection = _factory.CreateConnection();
using (IModel channel = _connection.CreateModel())
{
if (AutoCloseConnection)
_connection.AutoClose = AutoCloseConnection;
// Set the AutoDelete as false, fourth parameter!!!
channel.QueueDeclare(queueName, true, false, false, null);
channel.BasicPublish("", queueName, null, data);
if (!channel.IsClosed)
channel.Close();
}
}
catch (Exception e)
{
error = string.Format("Failed pushing data to queue name '{0}' on host '{1}' with user '{2}'. Error: {3}", queueName, _factory.HostName, _factory.UserName,
e.GetCompleteDetails());
return false;
}
return true;
}
| |
doc_23528660
|
import socket
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))
message = raw_input()
my_socket.send(message)
my_socket.close()
and a server
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
client_name = client_socket.recv(1024)
client_socket.send('Hello ' + client_name + '!')
client_socket.close()
server_sockrt.close()
in windows i run them through cmd, how to run them on mac? thanks for help.
A: Hit Cmd-Space and enter term then hit Enter. This should open a Mac terminal window. By default the Python will be 2.7, which should work with your code.
A: Save the following file as server.py in your HOME directory:
#!/usr/bin/python
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
client_data = client_socket.recv(1024)
print("Received: %s" % client_data)
client_socket.send('Hello ' + client_data + '!')
client_socket.close()
server_socket.close()
Save the following as client.py in your HOME directory:
#!/usr/bin/python
import socket
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))
message = raw_input('Enter some data: ')
my_socket.send(message)
response_data = my_socket.recv(1024)
print("Received: %s" % response_data)
my_socket.close
Start Terminal, by hitting ⌘SPACE and typing "Terminal" followed by Enter.
Make both the scripts executable by running the following command once (it changes their mode by adding the x executable bit):
chmod +x *py
Now run the server with:
./server.py
Now press ⌘N, to get a New Terminal and in the new Terminal type:
./client.py
And everything should work.
The first line of each script is called a "shebang" in Unix if you want to learn about it.
| |
doc_23528661
|
My goal is to have something like the average and having each time the average rate on the filtered rows.
I have tried to implement the solution I want using this function I have found in another thread.
var col1DimTotal = col1Dim.group().reduce(reduceAdd, reduceRemove,
reduceInitial);
function reduceAdd(p, v) {
++p.count;
p.total += v.value;
return p;
}
function reduceRemove(p, v) {
--p.count;
p.total -= v.value;
return p;
}
function reduceInitial() {
return {count: 0, total: 0};
}
However, this did not achieve what I wanted.
This is my rate dimension and the grouping with another dimension:
var ratesDim = ndx.dimension(function(d) {return
d.suicidesPercentage;});
var ageDim = ndx.dimension(function(d) {return d.age});
var ratesPerAge = ageDim.group().reduceSum(function(d) {return
+d.suicidesPercentage});
I would like to filter trough the average rate of the rows I am selecting.
A: I think I solved this and I managed to achieve what I wanted:
var yearDim = ndx.dimension(function(d) { return new Date(d.year); });
function reduceAddAvg(p,v) {
++p.count
p.sum += v.suicidesPercentage;
p.avg = p.sum/p.count;
return p;
}
function reduceRemoveAvg(p,v) {
--p.count
p.sum -= v.suicidesPercentage;
p.avg = p.count ? p.sum/p.count : 0;
return p;
}
function reduceInitAvg() {
return {count:0, sum:0, avg:0};
}
var ratesPerYear = yearDim.group().reduce(reduceAddAvg, reduceRemoveAvg, reduceInitAvg);
yearChart // line chart
.width(660)
.height(400)
.dimension(yearDim)
.group(ratesPerYear).valueAccessor(function (d) {
return d.value.avg;
}) // this is the reference of the AVG
.x(d3.scaleTime().domain([new Date("January 1, 1987 00:00"), new
Date("January 4, 2015 00:00:00")]))
.elasticY(true)
.controlsUseVisibility(true)
.yAxisLabel("Rates over 100k people")
.xAxisLabel("Year")
.centerBar(true);
| |
doc_23528662
|
Thanks in advance
let res = {
Zw== : { price: "500", code: "Zw==", name: "Word 2013", image: "path/d360f0.jpg", total: 1},
aA== : { price: "300", code: "aA==", name: "Power point 2013", image: "path/80fa572.png", total: 1},
xH== : { price: "300", code: "aA==", name: "Power point 2013", image: "path/80fa572.png", total: 1}
};
A: Your object properties look broken, so I would look into that.
I think what you're looking for is Object.keys..
Example:
function printKeys(obj) {
console.log(Object.keys(obj));
}
You can pass in your res object and it will give you have the property keys of the object.
From there then you can use the property as the next key.
printKeys(res['Zw']);
JSFiddle
| |
doc_23528663
|
Here providing couple of text file lines, where each of the '|' acts as a delimiter behind company name, address, type and activity. I have tried replacing the delimiter with a different character, or setting up a regex condition in case '|' is somehow a special character, but to no avail.
'3sun Group' '|'
'3 Sun House Boundary Road, Southtown, Great Yarmouth, Norfolk, NR31 0FB'
'|' 'Private limited Company' '|' '71129 - Other engineering activities'
'Abacus' '|'
'100 Cedarwood Crockford Lane, Chineham Business Park, Chineham, Basingstoke, Hampshire, England, RG24 8WD'
'|' 'Private limited Company' '|'
'66220 - Activities of insurance agents and brokers'
'Accsys Group' '|'
'Lea Cottage Old Harrowden Road, Harrowden, Bedford, United Kingdom, MK42 0TB'
'|' '27 November 2018' '|'
'72110 - Research and experimental development on biotechnology'
'Acro' '|' '291 Green Lanes, London, England, N13 4XS' '|'
'Private limited Company' '|' '46410 - Wholesale of textiles'
df = pd.read_csv('creg.txt', sep='|', names=["Company", "Address", "Type", "Industry"])
print (df)
Expected result is a dataframe containing entries as such:
Company
'3sun Group' '
Address
'
'3 Sun House Boundary Road, Southtown, Great Yarmouth, Norfolk, NR31 0FB'
'
Type
' 'Private limited Company'
Industry
' '71129 - Other engineering activities'
Current results look like this:
Company \
0 '3sun Group' '
1 '3 Sun House Boundary Road, Southtown, Great ...
2 '
3 'Abacus' '
4 '100 Cedarwood Crockford Lane, Chineham Busin...
5 '
6 '66220 - Activities of insurance agents and b...
7 'Accsys Group' '
8 'Lea Cottage Old Harrowden Road, Harrowden, B...
9 '
Address \
0 '
1 NaN
2 ' 'Private limited Company' '
3 '
4 NaN
5 ' 'Private limited Company' '
6 NaN
Type Industry
0 NaN NaN
1 NaN NaN
2 ' '71129 - Other engineering activities' NaN
3 NaN NaN
4 NaN NaN
5 ' NaN
6 NaN NaN
A: You could use re.sub() to perform some preliminary cleanup of your .txt file and then use io.StringIO() to pass this string to pd.read_csv() as the constructor for your dataframe:
import pandas as pd
import re, io
with open('test.txt', 'r') as f:
text = re.sub(r'\s+\|\s+', ';', re.sub(r'\'', '', f.read()))
df = pd.read_csv(io.StringIO(text), sep=r';', names=["Company", "Address", "Type", "Industry"], engine='python')
Outputs:
Company Address \
0 3sun Group 3 Sun House Boundary Road, Southtown, Great Ya...
1 Abacus 100 Cedarwood Crockford Lane, Chineham Busines...
2 Accsys Group Lea Cottage Old Harrowden Road, Harrowden, Bed...
3 Acro 291 Green Lanes, London, England, N13 4XS
Type Industry
0 Private limited Company 71129 - Other engineering activities
1 Private limited Company 66220 - Activities of insurance agents and bro...
2 27 November 2018 72110 - Research and experimental development ...
3 Private limited Company 46410 - Wholesale of textiles
| |
doc_23528664
|
such as the infamous:
' or '1'='1
I sometimes get lazy and usually my PDO SQL queries end up like this:
SELECT * FROM users WHERE id = ?
(I'd then bind ? to the $_GET['id'] or something)
Now notice I don't use ` or ' anywhere in the query, is SQL injection still possibly after prepared statements? What exactly does prepared statements stop? Thank you!
| |
doc_23528665
|
#!/usr/bin/perl
use strict;
use warnings;
use Dancer2;
$| = 1;
set host => '127.0.0.1';
set port => 7071;
get '/foo' => sub {
`sleep 5`;
'ok'
};
start;
Then I am run the following for loop:
for i in $(seq 1 3)
> do
> time curl http://localhost:7071/foo &
> done
Output:
ok
real 0m5.032s
user 0m0.013s
sys 0m0.000s
ok
real 0m10.037s
user 0m0.012s
sys 0m0.000s
ok
real 0m15.043s
user 0m0.004s
sys 0m0.008s
It seems to Dancer2 can only accept one request one time, how to allow multiple connections to Dancer2?
A: Perl programs are generally single-threaded. If you want to handle multiple things at the same time, you need to manage that explicitly.
*
*You can run multiple instances of your Dancer app. When one instance is busy, the other instances can still handle requests. Some servers automatically support such “pre-forking”, for example Starman. This is the classic solution to your problem, coupled with the observation that your backend shouldn't do lots of stuff that block execution.
*You can explicitly write your app to work asynchronously. Your sleep invocation is blocking the entire process, but you could also use libraries that let you resume handling of a request when some event occurs. For example, the Dancer2 docs show examples for using the AnyEvent timers.
If you are familiar with the Express web framework in JavaScript, it generally uses the second approach: NodeJS doesn't let you block the process by sleeping, and instead requires you to use promises (async/await) or callbacks to explicitly account for asynchronous execution.
A: Thanks for amon's suggestion, I have resolve the problem with the following code(foo.pl):
#!/usr/bin/perl
use strict;
use warnings;
use Dancer2;
$| = 1;
get '/foo' => sub {
`sleep 5`;
'ok';
};
to_app;
And run the program as:
$ plackup -s Starman foo.pl
Resolved [*]:5000 to [0.0.0.0]:5000, IPv4
Binding to TCP port 5000 on host 0.0.0.0 with IPv4
Setting gid to "0 0 0"
Starman: Accepting connections at http://*:5000/
Then I am run the following for loop:
for i in $(seq 1 3)
> do
> time curl http://localhost:5000/foo &
> done
Output:
ok
real 0m5.077s
user 0m0.004s
sys 0m0.010s
ok
real 0m5.079s
user 0m0.001s
sys 0m0.012s
ok
real 0m5.097s
user 0m0.009s
sys 0m0.004s
Now Dancer2 can accept multiple request.
A: Last time I setup a dancer app, used plackup and Starman so a PSGI interface is provided.
cd $APP_DIR
$PLACKUP -E $ENV -s Starman --workers=20 -p 9000 \
-a bin/app.pl 2>&1 > $LOGFILE &
There is a reverse proxy in front of the perl to handle static files faster and provide some anti-cracking protections in more commonly used tools for the Perl-deficient.
simbabque's answer is better. It shows this and other options.
| |
doc_23528666
|
A: You seem to be using SQL Server, so here are some points to consider.
*
*Indexed view may or may not contain aggregations.
*There is a list of functions (operators, keywords) that can not be used in indexed views, many of them aggregate.
*Indexed view binds schema to tables referenced by the view.
Also, disabling an index on the view physically deletes the data. In data-warehousing, all indexes are usually dropped or disabled during loading. So, rebuilding this index would have to re-aggregate whole table after every major (daily?) load -- as opposed to an aggregate table which may be updated only for a last day or so.
| |
doc_23528667
|
'DataFrame' object has no attribute 'data not available'
sample df:
col1 col2
abc 10
def 20
ghi 30
function:
def fun1():
if (df['col1'].isin(['xyz'])).any():
output=df.loc[df['col1']=='xyz',['col2']]
return output
else:
output = "data not available"
return output
Calling function like below:
df['new_column'] = df.apply(fun1(),axis=1)
When I called function I am getting above error. I have searched about it but could not able to find solution. What has gone wrong?
A: try:
def fun1(val):
if (val['col1'] in 'xyz'):
return val['col2']
else:
return "data not available"
Finally:
df['new_column'] = df.apply(fun1,axis=1)
Note: You can reduce the cost of apply() by:
df['new_column']=df['col2'].where(df['col1'].eq('xyz'),"data not available")
OR
#import numpy as np
df['new_column']=np.where(df['col1'].eq('xyz'),df['col2'],"data not available")
| |
doc_23528668
|
EXAMPLE-
0110
0000
0000
0001
Then player 1 will win(will remove one "1" in first row in first turn,in 2nd turn player 2 will take one 1,& thus p1 takes the final 1.
A: You cannot apply the Sprague-Grundy theorem here. The theorem is used whenever you play multiple games, like for instance you play two games on two boards.
You can simply decide if the board is a winning or loosing state if you apply the usually recursive definitions: A board is in a winning state, if at least one move leads to a loosing state. And a board is in a loosing state, if no move leads to a loosing state.
def is_winning_state(board):
for each rectangle rect of 1s on the board:
if not is_winning_state(board - rect):
return True
return false
You also want to apply dynamic programming, otherwise the program will not finish in a reasonable time.
| |
doc_23528669
|
from _pytest.monkeypatch import MonkeyPatch
from third_party import ThirdParty
def test_my_func():
resp1= "resp1"
monkeypatch = MonkeyPatch()
def mock_other_method(*args, **kwargs):
return resp1
monkeypatch.setattr(ThirdParty, "other_method", mock_other_method)
assert ThirdParty().other_method() == "resp1"
# Some assertions
def test_my_func2():
monkeypatch = MonkeyPatch()
expected_result = "This is expected"
result_third_party = ThirdParty().other_method()
assert result_third_party == expected_result
where,
third_party.py has:
class ThirdParty:
def other_method(self):
return "This is expected"
These tests when ran independently run fine (I just wrote it, so there might be some syntax error). But when I run it as pytest -v, 2nd test will fail. The reason is that on calling other_method, it will return the mocked method: mock_other_method, and since the response is different it will fail. Please suggest some solution to this
A: monkeypatch is a pytest fixture and as such
not supposed to be imported. Instead, you have to provide it as an argument in the test functions. Pytest loads all fixtures at test start and looks them up by name, so the correct usage would be:
from third_party import ThirdParty
# no import from pytest internal module!
def test_my_func(monkeypatch):
resp1 = "resp1"
def mock_other_method(*args, **kwargs):
return resp1
monkeypatch.setattr(ThirdParty, "other_method", mock_other_method)
assert ThirdParty().other_method() == resp1
The monkeypatch fixture has function scope, meaning that the patching will be reverted after each test function automatically.
Note that using the internal pytest API (e.g. importing _pytest) is discouraged, both because it may change with a new version, and because there are more convenient and secure methods to use the features (and not last because these are documented). You should never bother about fixture cleanup yourself, if you use a fixture provided by pytest or a pytest plugin - it would be too easy to forget the cleanup and get unwanted side effects.
A: I found the solution by adding monkeypatch.undo() at the end of every test. This will prevent the monkeypatch() from leaking into other functions
| |
doc_23528670
|
*Remember the OFF in relation to the fries in the background
Then check out this
I'm very confused on what to do.
A: If you want a View to be in a certain portion of its superview, you can use align constraint with multiplier. First apply these constraints you your view:
Then modify each of the multiplier to the portion you want it to be, from the center to the edge is between value 1 to 2:
Note the values I used(1.7 & 1.9) brings the center of the view to 70% and 90% point between the center and edge of the superview. Having the multiplier at 2 will guarantee half your view be outside your superview.
Reminder too that these two constraints only determines the X and Y position of your view. You will need to add more to determine its width and height which I did beforehand.
| |
doc_23528671
|
i have issue in sending parameters in json format
get is working fine,post without parameters is also working fine,but post with some data(payload) as key value is not working
dont know whats the issue,tried sending data in many forms but still no luck,is the issue with ajax call or service file or any issue with the port numbers or browsers?or any configuration issue?
here is the sample java service code:
@Path("/getNotes")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getStates(Countries countries) {
logger.info("In UserRegistration Controller");
return Response.status(200).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Methods", "POST,OPTIONS")
.entity(userService.getStates(countries.getCountryId()))
.build();
}
and js code:
callLocal: function (callback) {
alert("in function");
// $http.post('http://domain//server/rest/dashboard/Notes')//post with out any data //working fine giving output and output format is jsu a string not in json
var payload = {"noteId": 251};
$http({method: "POST",
crossDomain: true,
url: " http://domain/server/rest/register/getnotes",
dataType: 'json',
//contentType: "application/json;charset=utf-8",
//processData: true,
// data: JSON.stringify({"noteId": 251}),
data: {"noteId": 251},
//data: $.param({"noteId": 251}),
//data: $.param(payload),
// headers: {
// 'Content-Type': 'application/json; charset=utf-8'
// }
// headers: {'Content-Type': 'application/json'}
// header("Access-Control-Allow-Origin", "*")
// .header("Access-Control-Allow-Headers", "Content-Type")
// .header("Access-Control-Allow-Methods", "POST,OPTIONS")
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json; charset=utf-8'
}
})
.success(function (data) {
alert("S");
alert(JSON.stringify(data));
callback(data);
})
.error(function (data, status, headers, config) {
alert("No data json"+status);
console.log(status);
});
}
status response is :0 and console error is
XMLHttpRequest cannot load http://domain/server/rest/register/getnoteId. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.net' is therefore not allowed access.
| |
doc_23528672
|
Currently I'm doing that with GET method. I think that I have complicated it too much. On page load all check box are checked, and when users uncheck checkbox, a post with that taxonomy is filtered out. My code is currently working and here it is:
Setting checkbox checked:
$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ( $actual_link == 'https://www.example.com/') {
$var_check = 1;
}
Checkboxes:
<form action="<?php echo get_permalink() ?>" method="GET" id="filter">
<input type='hidden' value='0' name='f'>
<input type="checkbox" name="f" value="1" onchange="this.form.submit()" <?php if ( ($face =='1') || ($var_check == 1) ) {echo 'checked';}?>> <div class="sprite facebook" style="margin-left:5px;"> <span class="tooltiptext">Filter by Facebook</span></div><br>
<input type='hidden' value='0' name='t'>
<input type="checkbox" name="t" value="1" onchange="this.form.submit()" <?php if ( ($twitter=='1') || ($var_check == 1) ) {echo 'checked';}?>> <div class="sprite twitter2" style="margin-left:5px;"> <span class="tooltiptext">Filter by Twitter</span></div><br>
<input type='hidden' value='0' name='te'>
<input type="checkbox" name="te" value="1" onchange="this.form.submit()" <?php if ( ($telegram=='1') || ($var_check == 1) ) {echo 'checked';}?>> <div class="sprite telegram2" style="margin-left:5px;"><span class="tooltiptext">Filter by Telegram</span></div><br>
<input type='hidden' value='0' name='r'>
<input type="checkbox" name="r" value="1" onchange="this.form.submit()" <?php if ( ($reddit=='1') || ($var_check == 1) ) {echo 'checked';}?>> <div class="sprite reddit" style="margin-left:5px;"> <span class="tooltiptext">Filter by Reddit</span></div><br>
<input type='hidden' value='0' name='e'>
<input type="checkbox" name="e" value="1" onchange="this.form.submit()" <?php if ( ($email=='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="sprite email" style="margin-left:5px;"> <span class="tooltiptext">Flter by Email</span></div><br>
<input type='hidden' value='0' name='ph'>
<input type="checkbox" name="ph" value="1" onchange="this.form.submit()" <?php if ( ($phone=='1') || ($var_check == 1) ) {echo 'checked';}?>> <div class="sprite phone" style="margin-left:2px;"> <span class="tooltiptext">Filter by Phone</span></div><br>
<input type='hidden' value='0' name='b'>
<input type="checkbox" name="b" value="1" onchange="this.form.submit()" <?php if ( ($bitcointalk=='1') || ($var_check == 1) ) {echo 'checked';}?>> <div class="sprite bitcointalk" style="margin-left:3px;"> <span class="tooltiptext">Filter by BitcoinTalk</span></div><br>
<input type='hidden' value='0' name='k'>
<input type="checkbox" name="k" value="1" onchange="this.form.submit()" <?php if ( ($kyc=='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="sprite kyc" style="margin-left:5px;"> <span class="tooltiptext">Filter by KYC</span></div><br>
<input type='hidden' value='0' name='y'>
<input type="checkbox" name="y" value="1" onchange="this.form.submit()" <?php if ( ($youtube=='1') || ($var_check == 1) ) {echo 'checked';}?>> <div class="sprite youtube" style="margin-left:2px;"> <span class="tooltiptext">Filter by YouTube</span></div><br>
<input type='hidden' value='0' name='l'>
<input type="checkbox" name="l" value="1" onchange="this.form.submit()" <?php if ( ($linkedin=='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="sprite linkedin" style="margin-left:5px;"> <span class="tooltiptext">Flter by LinkedIn</span></div><br>
<input type='hidden' value='0' name='eth'>
<input type="checkbox" name="eth" value="1" onchange="this.form.submit()" <?php if ( ($ethereum =='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="ethereum" style="margin-left:5px;">ETH<span class="tooltiptext">Filter by Ethereum</span></div><br>
<input type='hidden' value='0' name='neo'>
<input type="checkbox" name="neo" value="1" onchange="this.form.submit()" <?php if ( ($neo =='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="neo" style="margin-left:5px;">NEO<span class="tooltiptext">Filter by NEO</span></div><br>
<input type='hidden' value='0' name='xml'>
<input type="checkbox" name="xml" value="1" onchange="this.form.submit()" <?php if ( ($stellar =='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="stellar" style="margin-left:5px;">XML<span class="tooltiptext">Filter by Stellar</span></div><br>
<input type='hidden' value='0' name='waves'>
<input type="checkbox" name="waves" value="1" onchange="this.form.submit()" <?php if ( ($waves =='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="waves" style="margin-left:5px;">WAVES<span class="tooltiptext">Filter by Waves</span></div><br>
<input type='hidden' value='0' name='kmd'>
<input type="checkbox" name="kmd" value="1" onchange="this.form.submit()" <?php if ( ($komodo =='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="komodo" style="margin-left:5px;">KMD<span class="tooltiptext">Filter by Komodo</span></div><br>
<input type='hidden' value='0' name='own'>
<input type="checkbox" name="own" value="1" onchange="this.form.submit()" <?php if ( ($own =='1') || ($var_check == 1) ) {echo 'checked';}?>><div class="own" style="margin-left:5px;">OWN<span class="tooltiptext">Filter by Own chain</span></div><br>
<input type="hidden" name="action" value="req">
</form>
Here is getting of the variables:
if ( isset($_GET['f']) && $_GET['f'] == '1') {$face='1';} elseif ( !isset($_GET['f']) ) {$face = '0'; } else {$face='facebook';}
if ( isset($_GET['t']) && $_GET['t'] == '1' ) {$twitter='1';} elseif ( !isset($_GET['t']) ) {$twitter = '0'; } else {$twitter='twitter';}
if ( isset($_GET['te']) && $_GET['te'] == '1' ) {$telegram='1';} elseif ( !isset($_GET['te']) ) {$telegram = '0'; } else {$telegram='telegram';}
if ( isset($_GET['r']) && $_GET['r'] == '1' ) {$reddit='1';} elseif ( !isset($_GET['r']) ) {$reddit = '0'; } else {$reddit='reddit';}
if ( isset($_GET['e']) && $_GET['e'] == '1' ) {$email='1';} elseif ( !isset($_GET['e']) ) {$email = '0'; } else {$email='email';}
if ( isset($_GET['ph']) && $_GET['ph'] == '1' ) {$phone='1';} elseif ( !isset($_GET['ph']) ) {$phone = '0'; } else {$phone='phone';}
if ( isset($_GET['b']) && $_GET['b'] == '1' ) {$bitcointalk='1';} elseif ( !isset($_GET['b']) ) {$bitcointalk = '0'; } else {$bitcointalk='bitcointalk';}
if ( isset($_GET['k']) && $_GET['k'] == '1' ) {$kyc='1';} elseif ( !isset($_GET['k']) ) {$kyc = '0'; } else {$kyc='kyc';}
if ( isset($_GET['y']) && $_GET['y'] == '1' ) {$youtube='1';} elseif ( !isset($_GET['y']) ) {$youtube = '0'; } else {$youtube='youtube';}
if ( isset($_GET['l']) && $_GET['l'] == '1' ) {$linkedin='1';} elseif ( !isset($_GET['l']) ) {$linkedin = '0'; } else {$linkedin='linkedin';}
if ( isset($_GET['eth']) && $_GET['eth'] == '1' ) {$ethereum='1';} elseif ( !isset($_GET['eth']) ) {$ethereum = '0'; } else {$ethereum='ethereum';}
if ( isset($_GET['neo']) && $_GET['neo'] == '1' ) {$neo='1';} elseif ( !isset($_GET['neo']) ) {$neo = '0'; } else {$neo='neo';}
if ( isset($_GET['xml']) && $_GET['xml'] == '1' ) {$stellar='1';} elseif ( !isset($_GET['xml']) ) {$stellar = '0'; } else {$stellar='stellar';}
if ( isset($_GET['waves']) && $_GET['waves'] == '1' ) {$waves='1';} elseif ( !isset($_GET['waves']) ) {$waves = '0'; } else {$waves='waves';}
if ( isset($_GET['kmd']) && $_GET['kmd'] == '1' ) {$komodo='1';} elseif ( !isset($_GET['kmd']) ) {$komodo = '0'; } else {$komodo='komodo';}
if ( isset($_GET['own']) && $_GET['own'] == '1' ) {$own='1';} elseif ( !isset($_GET['own']) ) {$own = '0'; } else {$own='own';}
And finally the query:
$tax_query_args[] = array(
'relation' => 'AND',
array(
'taxonomy' => 'filters',
'field' => 'slug',
'terms' => array ($face, $twitter, $telegram, $reddit, $email, $phone, $bitcointalk, $kyc, $youtube, $linkedin),
'relation' => 'AND',
'operator' => 'NOT IN'
),
array(
'taxonomy' => 'platform',
'field' => 'slug',
'terms' => array ($ethereum, $neo, $stellar, $waves, $komodo, $own),
'relation' => 'AND',
'operator' => 'NOT IN'
),
);
This is currently working and I'm getting the desired result. But how to do with POST method on the same page, so that URL is not changed with parameters. I suppose I will have to use AJAX, but I'm not experienced with it.
I will appreciate any help or guidance.
Thank you.
| |
doc_23528673
|
these instructions:
Total Escapes has a wide variety of tours on offer to its customers.
Each tour can be uniquely identified by a route ID. A tour also has
associated with it an estimated duration and a description of the tour
itself.
Customer details are to be recorded in the database, with a unique
customer ID generated for each customer. Additional details include a
name, date of birth and contact phone number. A Tour run is defined as
one instance of a tour, i.e. a tour has a number of tour runs. For
example, a ‘Melbourne City Tour’ runs twice every day, 8:30am and
2:30pm. In other words, a Tour run is identified by not only a
specific tour but the date and time that tour was operated.
A customer can book tour runs. The price paid for the booking is
recorded. A vehicle is used by a driver to perform his/her duties in
taking tourists on a route. Each vehicle can be identified by it
registration plates. Other attributes such as vehicle type, capacity
and colour are also recorded.
A Tour guide organizes a tour run in coordination with the driver. The
tour guide must have a unique certificate number to be recorded in the
system. Their name, mobile number and address are also required. The
driver responsible for operating the tour vehicle on a tour run can be
identified by their D/L number. A name and mobile phone number are
also recorded in the database for each driver.
Some tour guides train other tour guides to manage tours themselves.
Each trainee has one supervisor while a supervisor can guide many
trainees.
On the diagram that i have created I am wondering if the link between instance and tour would be the many to exactly one?
OR is the tour run not even a weak entity?
ER Model
A: I agree that Tour Run is a weak entity - the instructions are very specific about this. That means Instance is an identifying relationship, mapping Route_ID values to Route_ID,Date,Time values. This is a trivial relation that wouldn't need to be recorded separately from Tour Run keys. You're also correct that the association between Instance and Tour is many-to-one - many Route_ID,Date,Time triplets map to one Route_ID.
| |
doc_23528674
|
This is how i am trying to get him to walk and turn:
public float Speed = 1f;
public float TurnSpeed = 1f;
void Start () {
transform.position = new Vector3(-10, 0, -79);
}
void Update () {
transform.Translate(new Vector3(0, 0, 1) * Speed * Time.deltaTime);
if (transform.position.x < -1)
{
transform.Translate(new Vector3(0, 0, 0));
transform.Rotate(0, 180 * Time.deltaTime, 0);
}
}
He will keep moving and not stop not sure why any help?
A: I am new to the content, but every time you update - your first line says:
Move foreward by one
you need to reverse this after reaching your turningpoint, maybe like this:
void Update () {
static boolean direction;
if (direction)
transform.Translate(new Vector3(0, 0, 1) * Speed * Time.deltaTime);
else
transform.Translate(new Vector3(0, 0, -1) * Speed * Time.deltaTime);
if (transform.position.x < -1) //or whenever you want to turn
direction = !direction;
}
dont forget to rotate or you just walking backwards ;)
| |
doc_23528675
|
By following the method described in the paper[Link] in the section 3.1. I've written the code generate the perturbed mesh but I don't know how to map this pixels from source image onto this mesh to form the perturbed image.
This is the code to generate the perturbed mesh.
import numpy as np
import matplotlib.pyplot as plt
mr = 88
mc = 68
xx = np.arange(mr-1, -1, -1)
yy = np.arange(0, mc, 1)
[Y, X] = np.meshgrid(xx, yy)
ms = np.transpose(np.asarray([X.flatten('F'), Y.flatten('F')]), (1,0))
perturbed_mesh = ms
nv = np.random.randint(20) - 1
for k in range(nv):
#Choosing one vertex randomly
vidx = np.random.randint(np.shape(ms)[0])
vtex = ms[vidx, :]
#Vector between all vertices and the selected one
xv = perturbed_mesh - vtex
#Random movement
mv = (np.random.rand(1,2) - 0.5)*20
hxv = np.zeros((np.shape(xv)[0], np.shape(xv)[1] +1) )
hxv[:, :-1] = xv
hmv = np.tile(np.append(mv, 0), (np.shape(xv)[0],1))
d = np.cross(hxv, hmv)
d = np.absolute(d[:, 2])
d = d / (np.linalg.norm(mv, ord=2))
wt = d
curve_type = np.random.rand(1)
if curve_type > 0.3:
alpha = np.random.rand(1) * 50 + 50
wt = alpha / (wt + alpha)
else:
alpha = np.random.rand(1) + 1
wt = 1 - (wt / 100 )**alpha
msmv = mv * np.expand_dims(wt, axis=1)
perturbed_mesh = perturbed_mesh + msmv
plt.scatter(perturbed_mesh[:, 0], perturbed_mesh[:, 1], c=np.arange(0, mr*mc))
plt.show()
This is how the perturbed mesh looks like:
This is the screenshot from the paper illustrating the synthetic image generation:
Sample source image for testing:
https://i.stack.imgur.com/26KN4.jpg
I'm stuck with mapping the source image pixels onto the mesh. I'll be grateful if someone can help.
A: (1) Use cv2.copyMakeBorder to enlarge the image, to avoid the warpped points going out of range of the original image size.
cv2.copyMakeBorder(...)
copyMakeBorder(src, top, bottom, left, right, borderType[, dst[, value]]) -> dst
. @brief Forms a border around an image.
.
. The function copies the source image into the middle of the destination image. The areas to the
. left, to the right, above and below the copied source image will be filled with extrapolated
. pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but
. what other more complex functions, including your own, may do to simplify image boundary handling.
useage:
img = cv2.copyMakeBorder(img, dh, dh, dw, dw, borderType=cv2.BORDER_CONSTANT, value=(0,0,0))
Set dw=nw//2, dh=nh//2 maybe ok, adjust if necessary. The nh, nw is the height and width of the source image.
(2) Create perturbed mesh grid using the method from the paper
xs, ys = create_grid() # the result is like np.meshgrid
Notice make sure the type and the size.
# xs = xs.reshape(nh, nw).astype(np.float32)
# nh, nw is the height and width of the coppied image
(3) Use cv2.remap to remap:
cv2.remap(...)
remap(src, map1, map2, interpolation[, dst[, borderMode[, borderValue]]]) -> dst
. @brief Applies a generic geometrical transformation to an image.
.
. The function remap transforms the source image using the specified map:
. \f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f]
usage:
dst= cv2.remap(img, xs, ys, cv2.INTER_CUBIC)
This is a demo result:
(4) Crop the nonzero region and resize if necessary:
Related:
*
*Converting opencv remap code from c++ to python
*Split text lines in scanned document
A: I'm leaving a minimum working demo for other readers.
Currently, trying to figure out in which condition perturbed_mesh becomes None.
def deform(img, perturbed_mesh):
h,w = img.shape[:2]
perturbed_mesh_x = perturbed_mesh[:,0]
perturbed_mesh_y = perturbed_mesh[:,1]
perturbed_mesh_x =perturbed_mesh_x.reshape((h,w))
perturbed_mesh_y =perturbed_mesh_y.reshape((h,w))
remapped = cv2.remap(img, perturbed_mesh_x, perturbed_mesh_y, cv2.INTER_LINEAR)
return remapped
def get_perturbed_mesh(img):
"""
Author: papabiceps
https://stackoverflow.com/q/53907633
"""
# mesh row & col
mr,mc = img.shape[:2]
xx = np.arange(0, mr, 1)
yy = np.arange(mc-1, -1, -1)
# yy = np.arange(0, mc, 1)
[Y, X] = np.meshgrid(xx, yy)
ms = np.transpose(np.asarray([X.flatten('F'), Y.flatten('F')]), (1,0))
perturbed_mesh = ms
nv = np.random.randint(20) - 1
for k in range(nv):
#Choosing one vertex randomly
vidx = np.random.randint(np.shape(ms)[0])
vtex = ms[vidx, :]
#Vector between all vertices and the selected one
xv = perturbed_mesh - vtex
#Random movement
mv = (np.random.rand(1,2) - 0.5)*20
hxv = np.zeros((np.shape(xv)[0], np.shape(xv)[1] +1) )
hxv[:, :-1] = xv
hmv = np.tile(np.append(mv, 0), (np.shape(xv)[0],1))
d = np.cross(hxv, hmv)
d = np.absolute(d[:, 2])
d = d / (np.linalg.norm(mv, ord=2))
wt = d
curve_type = np.random.rand(1)
if curve_type > 0.3:
alpha = np.random.rand(1) * 50 + 50
wt = alpha / (wt + alpha)
else:
alpha = np.random.rand(1) + 1
wt = 1 - (wt / 100 )**alpha
msmv = mv * np.expand_dims(wt, axis=1)
perturbed_mesh = perturbed_mesh + msmv
perturbed_mesh = perturbed_mesh.astype(np.float32)
if perturbed_mesh is not None:
result = deform(img, perturbed_mesh)
flipped = cv2.flip(result,1)
cv2.imshow("before",result)
cv2.imshow("after",flipped)
cv2.waitKey(0)
def main():
img = cv2.imread("./sample.png")
get_perturbed_mesh(img)
| |
doc_23528676
|
If the ID does not exist, it gets no row in the final result.
If the ID does exist, I want to do some logic to figure out if it gets a row. For simplicity, assume that the logic is: if column Q > 0.
So the final result is simply a column of IDs, throwing out some because they are disqualified for one of two reasons as above.
thanks.
A: If I got your question right this might be what you are looking for:
select id from your_table
where X = 'Y'
and id in (select id from other_table where Q > 0)
A: This is what JOINs are made for.
SELECT table1.* FROM table1
INNER JOIN table2
ON table1.ID = table2.table1_ID
AND table2.Q > 0;
This will select all records in table1 (which have IDs) and then remove any records that do not have a matching record in table2 or do not have a Q > 0.
A: You can use a subquery:
SELECT id FROM table1 WHERE table1.id IN (SELECT q FROM table2 WHERE table2.q > 0) AND table1.x='y'
SQL will check to see if the results from the outermost query are in the subquery (the part in parentheses) and won't return anything if they aren't.
| |
doc_23528677
|
For example I would like to return the texts that look like the following:
row1 -> hello \nthere
row2 -> see you tomorrow\n
I tried using something like the following:
select descr from description_tb where descr like '%\n%'
However this won't work since \n probably needs to be escaped, but I can't figure out how to do it for my case.
A: It doesn't need to be escaped as it already is escaped. It needs to be un-escaped!
You can do this by prefacing the quote mark with an E.
select descr from description_tb where descr like E'%\n%'
Or you could just write a literal new line but there you may be at the mercy of how your client program conveys it:
select descr from description_tb where descr like '%
%'
| |
doc_23528678
|
I also apply Berkeley Packet Filter on pcap resource handle, which according to documentation for pcap_get_selectable_fd caused some issues on BSD and Mac OS X. Could it be somehow related even that I am running Linux?
My test machine runs Linux kernel 3.13.3-1-ARCH and uses libpcap-1.6.2. On my development machine everything runs as I would expect (kernel 3.17.7-200.fc20.x86_64, libpcap-1.5.3).
Excerpt from packet capture initialization
for ( i = 0; i < etherpoke_conf->filter_cnt; i++ ){
struct bpf_program bpf_prog;
session_data_init (&(pcap_session[i]));
pcap_session[i].handle = pcap_create (etherpoke_conf->filter[i].interface, pcap_errbuff);
rval = pcap_set_promisc (pcap_session[i].handle, !etherpoke_conf->filter[i].rfmon);
if ( etherpoke_conf->filter[i].rfmon ){
rval = pcap_can_set_rfmon (pcap_session[i].handle);
if ( rval == 1 ){
rval = pcap_set_rfmon (pcap_session[i].handle, 1);
} else {
fprintf (stderr, "%s: cannot enable monitor mode on interface '%s': %s\n", argv[0], etherpoke_conf->filter[i].interface, pcap_geterr (pcap_session[i].handle));
exitno = EXIT_FAILURE;
goto cleanup;
}
}
rval = pcap_set_timeout (pcap_session[i].handle, SELECT_TIMEOUT_MS);
rval = pcap_setnonblock (pcap_session[i].handle, 1, pcap_errbuff);
rval = pcap_activate (pcap_session[i].handle);
rval = pcap_compile (pcap_session[i].handle, &bpf_prog, etherpoke_conf->filter[i].match, 0, PCAP_NETMASK_UNKNOWN);
rval = pcap_setfilter (pcap_session[i].handle, &bpf_prog);
pcap_freecode (&bpf_prog);
pcap_session[i].fd = pcap_get_selectable_fd (pcap_session[i].handle);
}
Excerpt from the main loop
while ( main_loop ){
time_t current_time;
struct pcap_pkthdr *pkt_header;
const u_char *pkt_data;
struct timeval timeout;
fd_set fdset_read;
int last_fd;
FD_ZERO (&fdset_read);
last_fd = 0;
timeout.tv_sec = 0;
timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
for ( i = 0; i < etherpoke_conf->filter_cnt; i++ ){
if ( pcap_session[i].fd == -1 )
continue;
FD_SET (pcap_session[i].fd, &fdset_read);
last_fd = pcap_session[i].fd;
}
if ( last_fd == 0 ){
syslog (LOG_ERR, "no more applicable filters left to use. Dying!");
break;
}
rval = select (last_fd + 1, &fdset_read, NULL, NULL, &timeout);
if ( rval == -1 ){
if ( errno != EINTR )
syslog (LOG_ERR, "select system call failed: %s", strerror (errno));
break;
}
time (¤t_time);
for ( i = 0; i < etherpoke_conf->filter_cnt; i++ ){
if ( FD_ISSET (pcap_session[i].fd, &fdset_read) ){
rval = pcap_next_ex (pcap_session[i].handle, &pkt_header, &pkt_data);
if ( rval < 0 ){
syslog (LOG_ERR, "could not obtain packet from the queue: %s", pcap_geterr (pcap_session[i].handle));
main_loop = 0;
break;
} else if ( rval == 0 ){
continue;
}
}
if ( (pcap_session[i].ts > 0)
&& (difftime (current_time, pcap_session[i].ts) >= etherpoke_conf->filter[i].session_timeout) ){
pcap_session[i].evt_flag = FILTER_EVENT_END;
}
}
}
| |
doc_23528679
|
Inner Exception 1:
IOException: Authentication failed because the remote party has closed the transport stream.
I am using below code:
string svcCredentials = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "Basic " + svcCredentials);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
Error during GetResponse().
I tried all the references in SO:
Authentication failed because the remote party has closed the transport stream exception when getting a response from webservice
Failure on HttpWebrequest with inner exception Authentication failed because the remote party has closed the transport stream
But of no use, still getting same error. Any problem in my code?
A: This issue is solved after changing ServicePointManager.SecurityProtocol as below:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
As Tls 1.1, 1.2 are not available in .net framework 4.0 directly in System.Net.
| |
doc_23528680
|
A: You can apparently do it by accessing the Admin app from your own code - see this thread.
The other option is to not use container-managed datasources.
| |
doc_23528681
|
what is the benefit or drawback (in terms of performance or any) if I go for creating COM dll.
I have gone through this LINK It didn't answer my question well.
Thanks!
A: The answers in the link you posted (COM vs non-COM DLL) address the major relevant points. If that didn't answer my question well then you should consider framing the question more narrowly.
A couple more notes in addition to the ones touched already in the other topic.
*
*A C++ DLL being consumed (only) by other C++ code can expose full C++ interfaces. See for example Using dllimport and dllexport in C++ Classes: You can declare C++ classes with the dllimport or dllexport attribute. These forms imply that the entire class is imported or exported..
In contrast, a COM DLL can only publish COM interfaces, which are language neutral and less friendly to C++. See for example What Is a COM Interface? .
*Related to the previous point, a DLL C++ interface is very strongly coupled with any C++ code that uses it. With rare exceptions, this means that both the DLL and the client code need to be compiled with the same compiler, and same version thereof. Also, whenever DLL exported classes change (including private changes), potentially all client code needs to be recompiled.
In contrast, a COM interface is an ABI contract (What is Application Binary Interface (ABI)?) far more loosely coupled with the client code. Essentially, as long as the published interfaces don't change, DLL code can change at will without requiring client recompiles.
As far as performance, that's premature to compare and impossible to second-guess without a lot more specifics. The C++ vs. COM interfaces have wildly different semantics and capabilities.
| |
doc_23528682
|
int index(int *arr, unsigned int i) {
return arr[i];
}
With x86-64 gcc 11.2, on -O2 the following code is generated:
index(int*, unsigned int):
mov esi, esi
mov eax, DWORD PTR [rdi+rsi*4]
ret
I've seen this answer, which says that moving a register to itself is an 'inefficient NOP' and was deemed to be 'an artifact of code-generation from a non-optimizing compiler'.
Why does GCC generate mov esi, esi here on -O2?
https://godbolt.org/z/bE4xhc8Tx
| |
doc_23528683
|
contactRoutes.get('/:id', async(req, res) => {
cb.getDoc(req.bucket, req.params.id ).then(result=>{
var tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
console.log(JSON.stringify(tasks))
res.json({ Success: true , Error: "", Message:"", Data: result.value})
}).catch(err=>{
res.json({ Success: false , Error: err, Message: ""})
})
})
A: Try this:
contactRoutes.get('/:id', async(req, res) => {
try{
let result = await cb.getDoc(req.bucket, req.params.id );
let tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
console.log(JSON.stringify(tasks))
res.json({ Success: true , Error: "", Message:"", Data: result.value})
}
catch(err){
res.json({ Success: false , Error: err, Message: ""})
}
})
A: You have to pass a aync callback into your promise resolver then like this,
contactRoutes.get('/:id', async(req, res) => {
cb.getDoc(req.bucket, req.params.id ).then(async (result)=>{
...........
}
})
or you may also use await in your promise call like this,
contactRoutes.get('/:id', async (req, res) => {
var result = await cb.getDoc(req.bucket, req.params.id)
var tasks = await cb.n1qlQuery_wId(req.bucket, req.N1qlQuery, cbQ.qContactTasks, req.params.id)
console.log(JSON.stringify(tasks))
res.json({ Success: true, Error: "", Message: "", Data: result.value })
}).catch(err => {
res.json({ Success: false, Error: err, Message: "" })
});
A: Make the callback function in .then async. See code below.
contactRoutes.get('/:id', async(req, res) => {
cb.getDoc(req.bucket, req.params.id ).then(async result=>{
var tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
console.log(JSON.stringify(tasks))
res.json({ Success: true , Error: "", Message:"", Data: result.value})
}).catch(err=>{
res.json({ Success: false , Error: err, Message: ""})
})
})
A: you have add async to then(...)'s handler AND not the route. Why? Since, await is used in that handler.
A: You can do this:
contactRoutes.get('/:id', async(req, res) => {
try {
const result = await cb.getDoc(req.bucket, req.params.id )
var tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
console.log(JSON.stringify(tasks))
res.json({ Success: true , Error: "", Message:"", Data: result.value})
} catch (err) {
res.json({ Success: false , Error: err, Message: ""})
}
})
| |
doc_23528684
|
Let's assume the following:
Vue.component("v-select", VueSelect.VueSelect);
new Vue({
el: "#app",
data: {
options: []
},
methods: {
onSearch(search, loading) {
if(search.length) {
loading(true);
this.search(loading, search, this);
}
},
search: _.debounce((loading, search, vm) => {
fetch(
`https://api.github.com/search/repositories?q=${escape(search)}`
).then(res => {
res.json().then(json => (vm.options = json.items));
loading(false);
});
}, 350)
}
});
img {
height: auto;
max-width: 2.5rem;
margin-right: 1rem;
}
.d-center {
display: flex;
align-items: center;
}
.selected img {
width: auto;
max-height: 23px;
margin-right: 0.5rem;
}
.v-select .dropdown li {
border-bottom: 1px solid rgba(112, 128, 144, 0.1);
}
.v-select .dropdown li:last-child {
border-bottom: none;
}
.v-select .dropdown li a {
padding: 10px 20px;
width: 100%;
font-size: 1.25em;
color: #3c3c3c;
}
.v-select .dropdown-menu .active > a {
color: #fff;
}
<link href="https://unpkg.com/vue-select/dist/vue-select.css" rel="stylesheet"/>
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
<script src="https://unpkg.com/lodash@latest/lodash.min.js"></script>
<script src="https://unpkg.com/vue-select@3.11.2/dist/vue-select.js"></script>
<div id="app">
<h1>Vue Select - Ajax</h1>
<v-select label="name" multiple :filterable="false" :options="options" @search="onSearch">
<template slot="no-options">
type to search GitHub repositories..
</template>
<template slot="option" slot-scope="option">
<div class="d-center">
<img :src='option.owner.avatar_url'/>
{{ option.full_name }}
</div>
</template>
<template slot="selected-option" slot-scope="option">
<div class="selected d-center">
<img :src='option.owner.avatar_url'/>
{{ option.full_name }}
</div>
</template>
</v-select>
</div>
If I search for eg: "javascript" and select the first four, I have this
But I want something like this:
or like this
0r even this
Is that possible?
I know that there are other plugins that can do that (eg: vue multiselect) but I need to implement it with this plugin because the other plugins missing some other functionality that I need
| |
doc_23528685
|
These control have same rows and columns count. Dgv keeps number result value and dt_formula keeps its formula. To more specific:
dgv.Rows[0].Cells[0].Value = "8" // that keeps the result
dt_formula.Rows[0][0] "=5+3"// that keeps its formula.
I know how to copy clipboard from Datagridview SelectedCells.
private void copyToClipboard()
{
DataObject dataObj = dgv.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
But I do not want this.
What I want is after selected cells when clicked copy I want to copy clipboard from dt_formula with the same selected rows and column index of dgv. I added pic explanation. Is there any solution for this?
| |
doc_23528686
|
Or can maybe the format function fix this?
A: Window-->Preferences--> Java > Editor > Save Actions-->Additional actions-->Configure-->Code Style--> Use blocks in if/while... here you can configure the style you want.
A: CheckStyle is a nice tool which can also be used as a plugin for eclipse. You can specify different kinds of coding styles you want to enforce on you / your team, by configuring rules in this tool. This could help you create your custom check.
| |
doc_23528687
|
Edit: I'd like to use the define function, thank you.
index.php
require_once 'config.php';
require_once '$TEMPLATES/template.php';
$tpl = new Template\template('main.tpl');
$tpl->set('city', 'London');
$tpl->render();
config.php
*mysql_details*
$TEMPLATES = 'templates/';
A: Single quotes don't parse variables the same way double quotes do, either use single quotes without the variable surrounded by the quotes or use double quotes with the variable inside.
Secondly, consider using an actual define.
Reading Material
Strings
| |
doc_23528688
|
@Override
public List<Address> extractData(ResultSet rs) throws SQLException, DataAccessException {
List<Address> addresses = new ArrayList<>();
while (rs.next()) {
Address address = new Address();
address.setCity(rs.getString("CITY") == null ? "" : rs.getString("CITY"));
address.setState(rs.getString("STATE") == null ? "" : rs.getString("STATE"));
address.setZip(rs.getString("ZIP") == null ? "" : rs.getString("ZIP"));
addresses.add(address);
}
return addresses;
}
A: From: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/ResultSetExtractor.html
rs - the ResultSet to extract data from. Implementations should not close this: it will be closed by the calling JdbcTemplate.
| |
doc_23528689
|
To be specific, the character should have a silhouette of an upper body and a plus sign.
A: There are a couple of Unicode symbols which look like "user".
U+1F464 Bust in Silhouette
U+1F465 Busts in Silhouette
You will need to test with users to see which they associate more with "Add User". You might need to use a couple of characters. For example
➕
Or, if your users are technologists, doctors, students etc you could use their emoji.
⚕️
A: As of Unicode 12.1, there is no such symbol expressing this meaning.
Do use an image, e.g. https://material.io/resources/icons/static/icons/baseline-person_add-24px.svg
| |
doc_23528690
|
for example, When I want to know if the include , but the include two many headers and header include other headers.So I have to check the source code one by one, So is there any quick method to find if one include another?
A: You should use an include guard. This will ensure the compiler does not include the header contents more than once.
An example header file, MyClass.h, using a standard include guard:
// MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
// Your header contents goes here
#endif
This will ensure that the compiler only includes the header contents once.
Alternatively, you can use #pragma once.
An example header file, MyClass.h, using non-standard #pragma once:
// MyClass.h
#pragma once
// Your header contents goes here
Note that #pragma once is not standard, so it will make your code less portable. However, it does use less code, and can avoid name clashes.
A: If myheader.h has what we call an include guard, then it will usually #define a macro with a name like MYHEADER_H. So first check whether your header file has this kind of thing.
If it does, you can check at any point whether it has been included (up to that point), using the #ifdef and #ifndef directives.
A: in some cases, the header guard mentioned in other answers will not suffice (e.g. your file is used on multiple systems or is built against separate versions or libraries and the hguard is inconsistent). In those cases, you can:
*
*look for another identifier which is #defined in that header
*or simply replace your inclusion of that header with your own little wrapper header which has a #define which does not vary by platform/architecture, then replace your #includes with the wrapper header. To illustrate:
#ifndef MON_HGUARD_CXX_CSTDIO
#define MON_HGUARD_CXX_CSTDIO
// now replace the following #include with inclusion of this header
#include <cstdio>
#endif // MON_HGUARD_CXX_CSTDIO
| |
doc_23528691
|
A: Because in Haskell all types are known at compile-time. There's no such thing as waiting until runtime to see what the type will be. And because this is sufficient to do anything you could want to do in a dynamically-typed system, while being easier to reason about to boot.
A: Just so you know, there actually is a package for heterogeneous lists, using non-trivial techniques and you really should make sure you understand the type system well before diving into this. You don't have this by default because of the type system. A list in Haskell isn't just a list. It's a list of a's, 'a' being Int, String, whatever you want. BUT, one list can contain only one type of values.
Note that you can define "heterogeneous lists" of elements satisfying some constraints using existential quantification, but I think you're not there yet and really should focus on understanding the other answers here before going any further.
A: There is a heteregenous list type called HList (available on Hackage), but note that there probably is a type for the contents of your list. Consider something like this:
history = [-12, "STATEMENT END", (-244, time January 4 2010), ...]
Your data has a type struggling to emerge, e.g.:
data HistoryEntry = Withdrawal Int | StatementClosing | ScheduledPayment Int CalendarTime
history = [Withdrawal 12, StatementClosing, ScheduledPayment 244 (time January 4 2010)]
In many cases, your data has a type that you just need to seek out.
A: Look at Heterogenous collections
{-# OPTIONS -fglasgow-exts #-}
--
-- An existential type encapsulating types that can be Shown
-- The interface to the type is held in the show method dictionary
--
-- Create your own typeclass for packing up other interfaces
--
data Showable = forall a . Show a => MkShowable a
--
-- And a nice existential builder
--
pack :: Show a => a -> Showable
pack = MkShowable
--
-- A heteoregenous list of Showable values
--
hlist :: [Showable]
hlist = [ pack 3
, pack 'x'
, pack pi
, pack "string"
, pack (Just ()) ]
--
-- The only thing we can do to Showable values is show them
--
main :: IO ()
main = print $ map f hlist
where
f (MkShowable a) = show a
{-
*Main> main
["3","'x'","3.141592653589793","\"string\"","Just ()"]
-}
A: It is indeed the typing that prevents this. Consider the definition of a list (notice the type parameter a, which is missing from your types):
data List a = Nil | Cons a (List a)
In the Cons a (List a) you can see that the type of thing at the head of the list must be the same type as the elements that follow it. To answer your question, you're not missing a lot: as you say the runtime could do it, but in Haskell you want to make these typing decisions at compile-time, not runtime.
If you want heterogeneous lists, you can see some wizardry by Oleg Kiselyov in his work on HList (= Heterogeneous List). It may not be exactly what you want, but it's in the same rough direction.
| |
doc_23528692
|
my t-sql code :
use rh_usc
declare @month as varchar(100)
declare @query as varchar(max)
set @month += @month(select [Affichage période (AAAAMM)] from employees)
print @month
if object_id('employees_202205') is not null drop table [dbo.employees_202205]
set @query = 'select * into [employees_' + @month + '] from [employees]'
print @query
exec(@query)
Could you please help me?
Best regards
A: In this example, @month will actually be NULL since you don't initialize it when you declare it, nor do you account for NULL in the concatenation. Concatenating anything with NULL will return NULL.
DECLARE @month AS VARCHAR(100);
SET @month += @month + (SELECT [Affichage période (AAAAMM)] from employees);
PRINT @month;
Since @month is NULL to start, this concatenation will yield NULL and the print statement won't output anything.
If you change the first line to
declare @month as varchar(100) = '';
then you should get a result, assuming there is a value in the table.
Better yet, account for a NULL value in the code. CONCAT checks for NULL values.
DECLARE @month AS VARCHAR(100);
DECLARE @query AS VARCHAR(MAX);
SET @month = CONCAT(@month, (SELECT [Affichage période (AAAAMM)] FROM employees));
PRINT @month;
IF OBJECT_ID('employees_202205') IS NOT NULL DROP TABLE [dbo.employees_202205];
SET @query = 'select * into [employees_' + ISNULL(@month, '') + '] from [employees]';
PRINT @query;
EXEC (@query);
Note: In the above examples I also fixed a syntax error in your code in the first SET statement
SET @month += @month(SELECT [Affichage période (AAAAMM)] FROM employees)
will set @month and then execute a SELECT as an individual statement.
| |
doc_23528693
|
serverless deploy --stage dev
Extracted from the docs
https://serverless.com/framework/docs/providers/aws/guide/deploying/
However when above command is used to deploy a service, it creates a new service with name dev-aws-nodejs in API Gateway.
Is it possible to create a service with name aws-nodejs and have different stages like dev, stag, prod etc.. Therefore, when you run the following command
serverless deploy --stage stag
A new stage called stag will be created under service aws-nodejs.
A: By design the current version of serverless framework doesn't support this feature. But the version 0.5.6 had been designed to deploy multiple stages into api single api gateway project. Following open issues are related to this. Some have suggested few workarounds.
AWS API Gateway stages and names are separated
Issue below, mainly highlight different services into same api gateway. But it also has some comments related to your query as well.
Deploy many micro/nano services to one API Gateway
Update:
In the recent release of serverless (v1.19), they have mentioned that they have started working on a solution for this.
Serverless v1.19 Changelog
| |
doc_23528694
|
I'm only finding examples which use the older versions of the Google SDK. If anyone has a link to example of a current version of Google admob please let me know.
FYI - I took Tim's suggestion. I found a complete sample of code from http://jmsliu.com/1482/adding-admob-banner-in-android-listview-header.html.
Its a different one that I first showed you but is set up with 3 Activities. After several hours of testing I thought I would show you my code and the error I'm currently getting, and the original code. I added "Log.i" throughout the program to determine which line causes the abend. It appears that the ads is returning null. Also, note that the original version of code (after the error section) has special "keytwordSet" logic. I was unable to get rid of the syntax errors so I removed it from my version.
AdRequest adRequest = new AdRequest();
Set keywordsSet = new HashSet();
keywordsSet.add("game");
keywordsSet.add("dating");
keywordsSet.add("money");
keywordsSet.add("girl");
adRequest.addKeywords(keywordsSet);
adView.loadAd(adRequest);
New Code:
*
*PostItemAdapter.java
*
*
*Adapter Class which configs and returns the View for ListView
**/
package com.jms.admobinlistview;
import java.util.HashSet;
import java.util.Set;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class PostItemAdapter extends ArrayAdapter {
private LayoutInflater inflater;
private PostData[] datas;
private Activity mainActivity;
private AdView adView;
public PostItemAdapter(Context context, int textViewResourceId,
PostData[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
mainActivity = (Activity) context;
inflater = mainActivity.getLayoutInflater();
datas = objects;
}
static class ViewHolder {
TextView postTitleView;
TextView postDateView;
ImageView postThumbView;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (position == 0) {
if (convertView == null || !(convertView instanceof AdView)) {
if (adView == null) {
Log.i("1", "msg1");
AdView adView = new AdView(mainActivity);
Log.i("2", "msg2");
adView.setAdUnitId("ca-app-pub-4409647944042499/8301167762");
Log.i("3", "msg3");
adView.setAdSize(AdSize.BANNER);
Log.i("4", "msg4");
// Convert the default layout parameters so that they play > nice with
// ListView.
float density = mainActivity.getResources().getDisplayMetrics>
().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.FILL_PARENT,
height);
adView.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("TEST_DEVICE_ID")
.build();
Log.i("5", "msg5");
adView.loadAd(adRequest);
Log.i("6", "msg6");
}
Log.i("7", "msg7");
convertView = adView;
Log.i("8", "msg8");
}
} else {
Log.i("8", "msg8");
if (convertView == null || convertView instanceof AdView) {
Log.i("9", "msg9");
convertView = inflater.inflate(R.layout.postitem, null);
Log.i("10", "msg10");
viewHolder = new ViewHolder();
Log.i("11", "msg11");
viewHolder.postThumbView = (ImageView) convertView
.findViewById(R.id.postThumb);
Log.i("12", "msg12");
viewHolder.postTitleView = (TextView) convertView
.findViewById(R.id.postTitleLabel);
Log.i("13", "msg13");
viewHolder.postDateView = (TextView) convertView
.findViewById(R.id.postDateLabel);
Log.i("14", "msg14");
convertView.setTag(viewHolder);
Log.i("15", "msg15");
} else {
Log.i("16", "msg16");
viewHolder = (ViewHolder) convertView.getTag();
Log.i("17", "msg17");
}
Log.i("18", "msg18");
if (datas[position].postThumbUrl == null) {
Log.i("19", "msg19");
viewHolder.postThumbView
.setImageResource(R.drawable.postthumb_loading);
}
Log.i("20", "msg20");
viewHolder.postTitleView.setText(datas[position].postTitle);
viewHolder.postDateView.setText(datas[position].postDate);
}
Log.i("21", "msg21");
return convertView;
}
}
Error:
03-16 21:34:10.509: I/1(415): msg1
03-16 21:34:10.530: I/2(415): msg2
03-16 21:34:10.530: I/3(415): msg3
03-16 21:34:10.530: I/4(415): msg4
03-16 21:34:10.582: I/5(415): msg5
03-16 21:34:10.609: D/dalvikvm(415): DexOpt: couldn't find field
Landroid/content/res/Configuration;.smallestScreenWidthDp
03-16 21:34:10.609: W/dalvikvm(415): VFY: unable to resolve instance field 36
03-16 21:34:10.609: D/dalvikvm(415): VFY: replacing opcode 0x52 at 0x0012
03-16 21:34:10.623: D/dalvikvm(415): VFY: dead code 0x0014-0018 in
Lcom/google/android/gms/common/GooglePlayServicesUtil;.b (Landroid/content/res/Resources;)Z
03-16 21:34:10.649: W/GooglePlayServicesUtil(415): Google Play Store is missing.
03-16 21:34:10.730: D/dalvikvm(415): DexOpt: --- BEGIN 'ads256706667.jar' (bootstrap=0) ---
03-16 21:34:10.919: D/dalvikvm(415): DexOpt: --- END 'ads256706667.jar' (success) ---
03-16 21:34:10.919: D/dalvikvm(415): DEX
prep '/data/data/com.jms.admobinlistview/cache/ads256706667.jar': unzip in 2ms, rewrite 193ms
03-16 21:34:11.019: I/Ads(415): Use AdRequest.Builder.addTestDevice
("B3EEABB8EE11C2BE770B684D95219ECB") to get test ads on this device.
03-16 21:34:11.059: I/Ads(415): Starting ad request.
03-16 21:34:11.179: D/dalvikvm(415): GC_EXTERNAL_ALLOC freed 269K, 52% free 2677K/5575K,
external 2032K/2137K, paused 74ms
03-16 21:34:11.499: I/6(415): msg6
03-16 21:34:11.499: I/7(415): msg7
03-16 21:34:11.499: I/8(415): msg8
03-16 21:34:11.509: I/21(415): msg21
03-16 21:34:11.509: D/AndroidRuntime(415): Shutting down VM
03-16 21:34:11.509: W/dalvikvm(415): threadid=1: thread exiting with uncaught exception
(group=0x40015560)
03-16 21:34:11.589: E/AndroidRuntime(415): FATAL EXCEPTION: main
03-16 21:34:11.589: E/AndroidRuntime(415): java.lang.NullPointerException
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.AbsListView.obtainView
(AbsListView.java:1432)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.makeAndAddView
(ListView.java:1745)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.fillDown
(ListView.java:670)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.fillFromTop
(ListView.java:727)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.layoutChildren
(ListView.java:1598)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.AbsListView.onLayout
(AbsListView.java:1260)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.setChildFrame
(LinearLayout.java:1254)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.layoutVertical
(LinearLayout.java:1130)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.onLayout
(LinearLayout.java:1047)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.FrameLayout.onLayout
(FrameLayout.java:338)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.setChildFrame
(LinearLayout.java:1254)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.layoutVertical
(LinearLayout.java:1130)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.onLayout
(LinearLayout.java:1047)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.FrameLayout.onLayout
(FrameLayout.java:338)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.ViewRoot.performTraversals
(ViewRoot.java:1140)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.ViewRoot.handleMessage
(ViewRoot.java:1859)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.os.Handler.dispatchMessage
(Handler.java:99)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.os.Looper.loop(Looper.java:123)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.app.ActivityThread.main
(ActivityThread.java:3683)
03-16 21:34:11.589: E/AndroidRuntime(415): at java.lang.reflect.Method.invokeNative(Native
Method)
03-16 21:34:11.589: E/AndroidRuntime(415): at java.lang.reflect.Method.invoke(Method.java:507)
03-16 21:34:11.589: E/AndroidRuntime(415): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-16 21:34:11.589: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:597)
03-16 21:34:11.589: E/AndroidRuntime(415): at dalvik.system.NativeStart.main(Native Method)
03-16 21:34:17.879: I/Process(415): Sending signal. PID: 415 SIG: 9
Original Code with previous version of adMob:
/**
* PostItemAdapter.java
*
* Adapter Class which configs and returns the View for ListView
*
*/
package com.jms.admobinlistview;
import java.util.HashSet;
import java.util.Set;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class PostItemAdapter extends ArrayAdapter {
private LayoutInflater inflater;
private PostData[] datas;
private Activity mainActivity;
private AdView adView;
public PostItemAdapter(Context context, int textViewResourceId,
PostData[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
mainActivity = (Activity) context;
inflater = mainActivity.getLayoutInflater();
datas = objects;
}
static class ViewHolder {
TextView postTitleView;
TextView postDateView;
ImageView postThumbView;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (position == 0) {
if (convertView == null || !(convertView instanceof AdView)) {
if (adView == null) {
adView = new AdView(mainActivity, AdSize.SMART_BANNER,
"a151bd35eeb068d");
AdRequest adRequest = new AdRequest();
Set<String> keywordsSet = new HashSet<String>();
keywordsSet.add("game");
keywordsSet.add("dating");
keywordsSet.add("money");
keywordsSet.add("girl");
adRequest.addKeywords(keywordsSet);
adView.loadAd(adRequest);
}
convertView = adView;
}
} else {
if (convertView == null || convertView instanceof AdView) {
convertView = inflater.inflate(R.layout.postitem, null);
viewHolder = new ViewHolder();
viewHolder.postThumbView = (ImageView) convertView
.findViewById(R.id.postThumb);
viewHolder.postTitleView = (TextView) convertView
.findViewById(R.id.postTitleLabel);
viewHolder.postDateView = (TextView) convertView
.findViewById(R.id.postDateLabel);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (datas[position].postThumbUrl == null) {
viewHolder.postThumbView
.setImageResource(R.drawable.postthumb_loading);
}
viewHolder.postTitleView.setText(datas[position].postTitle);
viewHolder.postDateView.setText(datas[position].postDate);
}
return convertView;
}
}
===============================================================================
Tim, thanks for getting back to me. The following is my code and error message that I'm getting. I tried several things and I keep getting the same type of errors. Can you please clarify your explanation you gave? Is purview really preview?
package com.robertrichardson.bxxxyxxxxzxxxxLite;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.MenuInflater;
import android.app.Activity;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdRequest.Builder;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.doubleclick.PublisherAdRequest;
import com.google.android.gms.ads.doubleclick.PublisherAdView;
import com.google.android.gms.drive.query.internal.InFilter;
import com.robertrichardson.bxxxyxxxxzxxxxLite.R.string;
/*
* BxxxxListFragment Class: Sets up and displays all Bxxxx Activity on the list.
*/
public class BxxxxListFragment extends SherlockListFragment {
private ArrayList<Bxxxx> mBxxxx;
private boolean mSubtitleVisible;
private LayoutInflater inflater;
private Activity mainActivity;
private static final String AD_UNIT_ID = "ca-app-pub-4409647944042499/8301167762";
public static final String TAG = "BxxxxListFragment";
// private AdView adView;
private AdView adView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* New ads Logic
*/
setHasOptionsMenu(true);
getSherlockActivity().setTitle(R.string.app_name);
mBxxxx = BxxxxLab.get(getSherlockActivity()).getBxxxx();
BxxxxAdapter adapter = new BxxxxAdapter(mBxxxx);
setListAdapter(adapter);
setRetainInstance(true);
mSubtitleVisible = false;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setEmptyText(getResources().getString(string.new_bxxxx_attack_empty_desc));
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
@TargetApi(11)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mSubtitleVisible) {
getSherlockActivity().getSupportActionBar().setSubtitle(R.string.subtitle);
}
}
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Use floating point context menus on Froyer and Gingerbread
registerForContextMenu(listView);
} else {
// Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
public boolean onActionItemClicked(
android.view.ActionMode arg0, android.view.MenuItem arg1) {
// TODO Auto-generated method stub
return false;
}
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(android.view.ActionMode mode) {
// TODO Auto-generated method stub
}
public boolean onPrepareActionMode(
android.view.ActionMode mode, android.view.Menu menu) {
// TODO Auto-generated method stub
return false;
}
public void onItemCheckedStateChanged(
android.view.ActionMode mode, int position, long id,
boolean checked) {
// TODO Auto-generated method stub
}
// ActionMode.Callback methods
});
}
return v;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Bxxxx c = ((BxxxxAdapter)getListAdapter()).getItem(position);
// Start Bxxxx Activity
Intent i = new Intent(getSherlockActivity(), BxxxxPagerActivity.class);
i.putExtra(BxxxxFragment.EXTRA_BULLIED_ID, c.getId());
startActivityForResult(i, 0);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {>
((BxxxxAdapter)getListAdapter()).notifyDataSetChanged();
}
@Override
public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_bxxxx_list, menu);
}
@TargetApi(11)
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item)
{
switch (item.getItemId()) {
case R.id.settings:
Intent i=new Intent(getSherlockActivity(), Preferences.class);
startActivity(i);
return(true);
case R.id.about:
i=new Intent(getSherlockActivity(),BxxxxContentActivity.class);
i.putExtra(BxxxxContentActivity.EXTRA_FILE,
"file:///android_asset/misc/about.html");
startActivity(i);
return(true);
case R.id.help:
i=new Intent(getSherlockActivity(),BxxxxContentActivity.class);
i.putExtra(BxxxxContentActivity.EXTRA_FILE,
"file:///android_asset/misc/help.html");
startActivity(i);
return(true);
case R.id.disclaimer:
i=new Intent(getSherlockActivity(),BxxxxContentActivity.class);
i.putExtra(BxxxxContentActivity.EXTRA_FILE,
"file:///android_asset/misc/disclaimer.html");
startActivity(i);
return(true);
case R.id.menu_item_new_bxxxx:
Bxxxx bxxxx = new Bxxxx();
BxxxxLab.get(getSherlockActivity()).addBxxxx(bxxxx);
i = new Intent(getSherlockActivity(), BxxxxPagerActivity.class);
i.putExtra(BxxxxFragment.EXTRA_BULLIED_ID, bxxxx.getId());
startActivityForResult(i,0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.bxxxx_list_item_context, menu);
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
BxxxxAdapter adapter = (BxxxxAdapter)getListAdapter();
Bxxxx bxxxx = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_bxxxx:
BxxxxLab.get(getActivity()).deleteBxxxx(bxxxx);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
private class BxxxxAdapter extends ArrayAdapter<Bxxxx> {
public BxxxxAdapter(ArrayList<Bxxxx> bxxxx) {
super(getSherlockActivity(), android.R.layout.simple_list_item_1, bxxxx);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
* New ads Logic
*/
Log.i("1", "msg1");
if (position == 0)
{
if (convertView == null || !(convertView instanceof AdView)) {
if (adView == null) {
Log.i("2", "msg2");
adView = new AdView(mainActivity); <=== Abends on this line
Log.i("3", "msg3");
adView.setAdUnitId("ca-app-pub-4409647944042499/8301167762");
Log.i("4", "msg4");
adView.setAdSize(AdSize.BANNER);
Log.i("5", "msg5");
// Convert the default layout parameters so that they play nice with
// ListView.
float density = mainActivity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.FILL_PARENT,
height);
adView.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("TEST_DEVICE_ID")
.build();
adView.loadAd(adRequest);
}
convertView = adView;
return convertView;
}
return convertView;
} else {
if (convertView == null || convertView instanceof AdView) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getSherlockActivity().getLayoutInflater()
.inflate(R.layout.list_item_bxxxx, null);
}
// Enter the view of this Bxxxx Attack
Bxxxx c = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.bxxxx_list_item_titleTextView);
titleTextView.setText(c.getTitle());
TextView dateTextView =
(TextView)convertView.findViewById(R.id.bxxxx_list_item_dateTextView);
dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy hh : mm a", c.getDate()).toString());
CheckBox resolvedCheckBox =
(CheckBox)convertView.findViewById(R.id.bxxxx_list_item_resolvedCheckBox);
resolvedCheckBox.setChecked(c.isResolved());
return convertView;
}
return convertView;
}
}
}
@Override
public void onResume() {
super.onResume();
((BxxxxAdapter)getListAdapter()).notifyDataSetChanged();
}
}
03-18 06:52:29.785: D/dalvikvm(932): VFY: replacing opcode 0x6f at 0x0006
03-18 06:52:30.085: I/1(932): msg1
03-18 06:52:30.085: I/2(932): msg2
03-18 06:52:30.085: D/AndroidRuntime(932): Shutting down VM
03-18 06:52:30.095: W/dalvikvm(932): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-18 06:52:30.135: E/AndroidRuntime(932): FATAL EXCEPTION: main
03-18 06:52:30.135: E/AndroidRuntime(932): java.lang.NullPointerException
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.ViewConfiguration.get(ViewConfiguration.java:228)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.(View.java:1878)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.ViewGroup.(ViewGroup.java:281)
03-18 06:52:30.135: E/AndroidRuntime(932): at com.google.android.gms.ads.AdView.(Unknown Source)
03-18 06:52:30.135: E/AndroidRuntime(932): at com.robertrichardson.bxxxyxxxxzxxxLite.BxxxxListFragment$BxxxxAdapter.getView(BxxxxListFragment.java:251)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.AbsListView.obtainView(AbsListView.java:1430)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.makeAndAddView(ListView.java:1745)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.fillDown(ListView.java:670)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.fillFromTop(ListView.java:727)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.layoutChildren(ListView.java:1598)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.AbsListView.onLayout(AbsListView.java:1260)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
A: It looks like you are hiding the class variable 'adView' in the new code by declaring a local variable of the same name. Due to the scope, you're setting convertView to the global adView, which is always null. Just change "AdView adView =" to "adView ="
| |
doc_23528695
|
This code works fine with other Android API but not in this phone with Android 4.0.3:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/root_menu"
android:icon="@android:drawable/ic_menu_help"
android:showAsAction="always"
android:title="Help">
<menu>
<item
android:id="@+id/menu_about"
android:onClick="aboutDialog"
android:showAsAction="never"
android:title="About"/>
</menu>
</item>
</menu>
This is the Activity
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
}
/**
* Crea l'action bar
*
* @param menu
* @return
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_actionbar, menu);
return true;
}
/**
* Apertura del dialog box con le informazioni sulla versione del programma
*
* @param v
*/
public void aboutDialog(MenuItem v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Test")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
builder.create().show();
}
}
So nothing strange in this code. But when I try to run on the device I've this exception:
android.view.InflateException: Couldn't resolve menu item onClick handler
aboutDialog in class android.view.ContextThemeWrapper
at android.view.MenuInflater$InflatedOnMenuItemClickListener.<init> (MenuInflater.java:202)
at android.view.MenuInflater$MenuState.setItem(MenuInflater.java:402)
at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:436)
at android.view.MenuInflater.parseMenu(MenuInflater.java:173)
at android.view.MenuInflater.parseMenu(MenuInflater.java:151)
at android.view.MenuInflater.inflate(MenuInflater.java:95)
at
it.mobile.activity.home.HomeActivity.onCreateOptionsMenu(HomeActivity.java:38)
at android.app.Activity.onCreatePanelMenu(Activity.java:2444)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:388)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:739)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:2833)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: aboutDialog
[interface android.view.MenuItem]
at java.lang.Class.getConstructorOrMethod(Class.java:460)
at java.lang.Class.getMethod(Class.java:915)
at android.view.MenuInflater$InflatedOnMenuItemClickListener.<init>
But I don't understand where is the problem. With another device all works fine!
A: Not sure how to solve it with just xml.
From code perspective you will have to implement
public boolean onOptionsItemSelected(MenuItem item)
and then depending on the menu item call the required handler.
A: Although this is out of date, here is the reason for the exception. When you look into the sources of android API 15 (4.0.3-4.0.4) in the class MenuInflator you will see this method:
public InflatedOnMenuItemClickListener(Context context, String methodName) {
mContext = context;
Class<?> c = context.getClass();
try {
mMethod = c.getMethod(methodName, PARAM_TYPES);
} catch (Exception e) {
InflateException ex = new InflateException(
"Couldn't resolve menu item onClick handler " + methodName +
" in class " + c.getName());
ex.initCause(e);
throw ex;
}
This is were the exception happens. As we see the method tries to find the Callback method on the class of the context item passed. So instead of calling getMenuInflator() in onCreateOptionsMenu you should call new MenuInflator(this), so that this is passed as a context and then the code will work.
Another bug fix was to remove the theme from the manifest and i am still very puzzeled why that works. But well, it's just a workaround.
A: I was having similar issues and I found this here -https://code.google.com/p/android/issues/detail?id=62795
This is affecting Android 5.0 when applying the android:theme attribute.
<Button
android:theme="@android:style/Theme.Material"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onLoginEmail"
Clicking on the button throws
java.lang.IllegalStateException: Could not find a method onLoginEmail(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button
at android.view.View$1.onClick(View.java:3994)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchMethodException: onLoginEmail [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:3987)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
/>
I got around it by removing android:theme from the TextView
| |
doc_23528696
|
function showmenu(elem) {
// Clear any currently open menu
var openMenu = document.getElementById("activeMenu");
if (openMenu) {
openMenu.removeAttribute("id");
// Stop if we're just closing the current menu
if (openMenu === elem) {
return;
}
}
// Only apply it if the element actually has LI child nodes.
// OPTIONAL: Will still work without if statement.
if (elem.getElementsByTagName("li").length > 0) {
elem.setAttribute("id", "activeMenu");
}
}
A: Well you can add event.stopPropagation() to the nested ul:
<ul id="nav">
<li onclick="showmenu(this)" class="sectionMenu">
Service
<ul onclick="event.stopPropagation()">
<li><a> Ro </a> </li>
<li> <a>List</a> </li>
<li><a>Service Plan</a> </li>
</ul>
</li>
....
</ul>
A: You could check if the actual element clicked is a parent (i.e. has class sectionMenu). If not then return.
You can do this by adding the following code to your javascript:
// Checks if element clicked has class sectionMenu. Otherwise return.
var $elementClicked = event.target;
if ($elementClicked.className != 'sectionMenu')
return;
CodePen
function showmenu(elem) {
// Checks if element clicked has class sectionMenu. Otherwise return.
var $elementClicked = event.target;
if ($elementClicked.className != 'sectionMenu')
return;
// Clear any currently open menu
var openMenu = document.getElementById("activeMenu");
if (openMenu) {
openMenu.removeAttribute("id");
// Stop if we're just closing the current menu
if (openMenu === elem) {
return;
}
}
// Only apply it if the element actually has LI child nodes.
// OPTIONAL: Will still work without if statement.
if (elem.getElementsByTagName("li").length > 0) {
elem.setAttribute("id", "activeMenu");
}
}
img {
padding-left: 5px;
}
#nav {
height: 100%;
padding: 20px;
cursor: pointer;
border: 3px solid #3e4547;
box-shadow: 2px 2px 8px #000000;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
ul {
width: 200px;
list-style: none;
margin: 0;
padding: 5px;
}
ul li {
display: block;
padding: 0 10px;
overflow: hidden;
padding: 5px;
}
ul ul {
display: none;
}
ul ul li {
float: none;
user-select: #b6ff00;
}
#activeMenu ul {
display: block;
}
ul li:hover {
background-color: #bcbdc1;
}
ul ul li:hover {
background-color: red;
}
.arrow {
background-image: url("./png/2.png");
transition: 0.3s;
transform: rotateX(-180deg);
}
li.sectionMenu:before {
content: '\2795';
font-size: 13px;
color: #777;
float: right;
margin-left: 5px;
}
li.sectionMenu#activeMenu:before {
content: "\2796";
}
<div>
<ul id="nav">
<li onclick="showmenu(this)" class="sectionMenu">
Service
<ul>
<li><a> Ro </a>
</li>
<li> <a>List</a>
</li>
<li><a>Service Plan</a>
</li>
</ul>
</li>
<li onclick="showmenu(this)" class="sectionMenu">
Customer
<ul>
<li>New Customer</li>
<li>customer List</li>
</ul>
</li>
<li onclick="showmenu(this)" class="sectionMenu">
Parts
<ul>
<li>New Part</li>
<li>Parts List</li>
</ul>
</li>
<li onclick="showmenu(this)" class="sectionMenu">
Admin
<ul>
<li>New Employee</li>
<li>Employee List</li>
<li>Employee Roles</li>
<li>Employee Work Schedulee</li>
<li>Holidays</li>
<li>Employee List</li>
</ul>
</li>
</ul>
</div>
A: Even U could try this....Remember to pass event argument for the onclick handlers
function showmenu(elem,event) {
// Clear any currently open menu
event.preventDefault();
// alert(event.currentTarget.getAttribute("id"))
var openMenu = document.getElementById("activeMenu");
if (openMenu) {
if(openMenu.children[0]==event.target.parentNode)
return;
openMenu.removeAttribute("id");
// Stop if we're just closing the current menu
if (openMenu === elem) {
return;
}
}
// Only apply it if the element actually has LI child nodes.
// OPTIONAL: Will still work without if statement.
if (elem.getElementsByTagName("li").length > 0) {
event.currentTarget.setAttribute("id", "activeMenu");
}
}
CodePen
| |
doc_23528697
|
RestKit adds an NSManagedObject(ActiveRecord) category which can be used for retrieving a managed object through various class-methods, however I can find no way of adding a new managed object or deleting one.
Should I pull a reference to the managedObjectContext RestKit's object manager, then manipulate the database directly?
A:
Should I pull a reference to the managedObjectContext RestKit's object manager, then manipulate the database directly?
I'm by no means an expert at RestKit, but this seems like the way to go.
I don't think RestKit is trying to replace Core Data, it merely adds some convenience stuff for setting up the database and for converting objects as they come through a web service. Everything you do with them locally is still your responsibility, so use the Core Data methods.
| |
doc_23528698
|
Essentially what I'm trying to do is take every 66th character from a string in Sheet1.Cells(2, 3) starting at the first character (total would be 20 times, the string length is 1,320 characters in all). Once I get those 20 occurrences of the 66th character, I would like to print those 20 instances on Sheet2.Cells(i, 2) where i = 2 to 21. Finally, I would like to loop to the next string at Sheet1.Cells(3, 3), do the same calculation, and print the results in Sheet2.Cells(i + 20, 2) where still i = 2 to 21.
Below is the code that I have, and it does work. Problem is I would have to reiterate those blocks of code over a thousand times. Is there any way to condense this so it does this calculation to say every row until it hits Sheet1.Cells(2, 100)? Link attached of screenshot describing what I'm trying to accomplish. https://imgur.com/a/aBrlAzd
Sub Decode_String()
Dim Fault_Block(2000)
For i = 2 To 21
For j = 1 To 20
Fault_Block(i) = Mid(Sheet1.Cells(2, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 1, 2) = Fault_Block(i)
Next
Next
For i = 22 To 41
For j = 1 To 20
Fault_Block(i) = Mid(Sheet1.Cells(3, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 21, 2) = Fault_Block(i)
Next
Next
For i = 42 To 61
For j = 1 To 20
Fault_Block(i) = Mid(Sheet1.Cells(4, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 41, 2) = Fault_Block(i)
Next
Next
End Sub
A: You're on the right track, you just need to add a loop around your logic to move through the Sheet1 cells
Sub Decode_String()
Dim Fault_Block(2000)
Dim counter
' loop through cells
For c = 2 To 100
For j = 1 To 20
counter = counter + 1
Fault_Block(counter) = Mid(Sheet1.Cells(c, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + ((c - 2) * 20) + 1, 2) = Fault_Block(counter)
Next
Next
End Sub
If you don't need the Fault_Block array for another reason, you can simplify it to:
Sub Decode_String()
' loop through cells
For c = 2 To 100
For j = 1 To 20
Sheet2.Cells(j + ((c - 2) * 20) + 1, 2) = Mid(Sheet1.Cells(c, 3), (66 * j) - 65, 4)
Next
Next
End Sub
A: Here are the loops condensed:
Sub Decode_String()
For i = 2 To 21
For j = 1 To 20
Sheet2.Cells(j + 1, 2) = Mid(Sheet1.Cells(2, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 21, 2) = Mid(Sheet1.Cells(3, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 41, 2) = Mid(Sheet1.Cells(4, 3), (66 * j) - 65, 4)
Next
Next
End Sub
If you wanted it to loop all the way to row 100, try this:
Sub Decode_String()
For i = 2 To 21
For j = 1 To 100
Sheet2.Cells(j + 1, 2) = Mid(Sheet1.Cells(2, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 21, 2) = Mid(Sheet1.Cells(3, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 41, 2) = Mid(Sheet1.Cells(4, 3), (66 * j) - 65, 4)
Next
Next
End Sub
| |
doc_23528699
|
Under the input field i needed to see last 5 cities i’ve looked for.
To do this, I create an array of the all entered cities and through props, Ill forward them to the component and using Array.from(new Set(props.arr)) and .slice(-5) to create a new arr.
import React from 'react';
.....
function SearchedCitys(props) {
const uniqueSet = Array.from(new Set(props.citys));
const citys = uniqueSet.slice(-5);
return (
<Fragment>
<div className="searched-citys-container">
{citys.map((city) => (
<City city={city} />
))}
</div>
</Fragment>
);
}
.......
export default connect(mapStateToProps)(SearchedCitys);
There is an bug in this method, when I re-enter the old values that were dropped from the new array of 5 items, they do not repeat again. What a convenient way to filter the source array to display the last 5 searched items?
LIVE sniped
A: it's because you're using a set.
here's what's happening, let's say you typed 6 cities:
props.cities = [ a , b , c , d , e , f ]
uniqueSet = [ a , b , c , d , e , f ]
citys = [ b , c , d , e , f ]
now when you add another "a", your "uniqueSet" will keep the first a, that's why it won't be on the end of your sliced array.
so what you need to do is :
on your reducer, add the the new city on the start of your array:
case actionTypes.ADD_SEARCHED_CITY:
return {
...state,
citys: [action.payload,...state.citys],
};
and on your searchCities component :
function SearchedCitys(props) {
const r = props.citys
const uniqueSet = Array.from(new Set(r));
const citys = uniqueSet.slice(0,5)
return (
<Fragment>
<div className="searched-citys-container">
{citys.map(city => (
<City key={uuidv4()} city={city} />
))}
</div>
</Fragment>
);
}
if you want to show the last added city on the right, just reverse the sliced array
const citys = uniqueSet.slice(0,5).reverse()
A: Instead of actually deriving the cities while rendering, you can actually update your reducer to only have 5 cities
case actionTypes.GET_WEATHER_SUCCESS:
return {
...state,
error: null,
loading: false,
currentWeather: action.payload.currentWeather,
forecast: action.payload.forecast,
citys: [
...new Set(state.citys.concat(action.payload.city.payload))
].slice(-5)
};
The reason you face problem in your solution is because while creating a Set it uses the first instance of the duplicate value and since its before the last 5 elements its not being used at all
Working demo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.