import * as saveAsFunctions from 'file-saver';
..........
.......
let saveAs;
beforeEach(() => {
saveAs = jasmine.createSpy('saveAs');
})
it('should generate the excel on sample request details page', () => {
spyOn(saveAsFunctions, 'saveAs').and.callFake(saveAs);
expect(saveAsFunctions.saveAs).toHaveBeenCalled();
})
This worked for me.
You don't need to wait. Protractor automatically waits for angular to be ready and then it executes the next step in the control flow.
Suppose there is a method like this that needs testing
The src
property of the tiny image needs checking
function reportABCEvent(cat, type, val) {
var i1 = new Image(1, 1);
var link = getABC('creosote');
link += "&category=" + String(cat);
link += "&event_type=" + String(type);
link += "&event_value=" + String(val);
i1.src = link;
}
The spyOn() below causes the "new Image" to be fed the fake code from the test the spyOn code returns an object that only has a src property
As the variable "hook" is scoped to be visible in the fake code in the SpyOn and also later after the "reportABCEvent" is called
describe("Alphabetic.ads", function() {
it("ABC events create an image request", function() {
var hook={};
spyOn(window, 'Image').andCallFake( function(x,y) {
hook={ src: {} }
return hook;
}
);
reportABCEvent('testa', 'testb', 'testc');
expect(hook.src).
toEqual('[zubzub]&arg1=testa&arg2=testb&event_value=testc');
});
This is for jasmine 1.3 but might work on 2.0 if the "andCallFake" is altered to the 2.0 name
I'm up to the latest as of today and found the best way to resolve this is to do nothing...no typeRoots
no types
no exclude
no include
all the defaults seem to be working just fine. Actually it didn't work right for me until I removed them all. I had:
"exclude": [
"node_modules"
]
but that's in the defaults so I removed that.
I had:
"types": [
"node"
]
to get past some compiler warning. But now I removed that too.
The warning that shouldn't be is:
error TS2304: Cannot find name 'AsyncIterable'.
from node_modules\@types\graphql\subscription\subscribe.d.ts
which is very obnoxious so I did this in tsconfig so that it loads it:
"compilerOptions": {
"target": "esnext",
}
since it's in the esnext set. I'm not using it directly so no worries here about compatibility just yet. Hope that doesn't burn me later.
What I did was: Added/Updated the following code:
framework: 'jasmine',
jasmineNodeOpts:
{
// Jasmine default timeout
defaultTimeoutInterval: 60000,
expectationResultHandler(passed, assertion)
{
// do something
},
}
I found that useful, stabbing service function as sinon.stub().returns($q.when({})):
this.myService = {
myFunction: sinon.stub().returns( $q.when( {} ) )
};
this.scope = $rootScope.$new();
this.angularStubs = {
myService: this.myService,
$scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );
controller:
this.someMethod = function(someObj) {
myService.myFunction( someObj ).then( function() {
someObj.loaded = 'bla-bla';
}, function() {
// failure
} );
};
and test
const obj = {
field: 'value'
};
this.ctrl.someMethod( obj );
this.scope.$digest();
expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );
There are a lot many good answers out there, i just wanted to add a scenario where the usage of these expectations might be helpful. Using element.all(xxx)
, if i need to check if all elements are displayed at a single run, i can perform -
expect(element.all(xxx).isDisplayed()).toBeTruthy(); //Expectation passes
expect(element.all(xxx).isDisplayed()).toBe(true); //Expectation fails
expect(element.all(xxx).isDisplayed()).toBeTrue(); //Expectation fails
Reason being .all()
returns an array of values and so all kinds of expectations(getText
, isPresent
, etc...) can be performed with toBeTruthy()
when .all()
comes into picture. Hope this helps.
toBe()
versus toEqual()
: toEqual()
checks equivalence. toBe()
, on the other hand, makes sure that they're the exact same object.
I would say use toBe()
when comparing values, and toEqual()
when comparing objects.
When comparing primitive types, toEqual()
and toBe()
will yield the same result. When comparing objects, toBe()
is a stricter comparison, and if it is not the exact same object in memory this will return false. So unless you want to make sure it's the exact same object in memory, use toEqual()
for comparing objects.
Check this link out for more info : http://evanhahn.com/how-do-i-jasmine/
Now when looking at the difference between toBe()
and toEqual()
when it comes to numbers, there shouldn't be any difference so long as your comparison is correct. 5
will always be equivalent to 5
.
A nice place to play around with this to see different outcomes is here
An easy way to look at toBe()
and toEqual()
is to understand what exactly they do in JavaScript. According to Jasmine API, found here:
toEqual() works for simple literals and variables, and should work for objects
toBe() compares with
===
Essentially what that is saying is toEqual()
and toBe()
are similar Javascripts ===
operator except toBe()
is also checking to make sure it is the exact same object, in that for the example below objectOne === objectTwo //returns false
as well. However, toEqual()
will return true in that situation.
Now, you can at least understand why when given:
var objectOne = {
propertyOne: str,
propertyTwo: num
}
var objectTwo = {
propertyOne: str,
propertyTwo: num
}
expect(objectOne).toBe(objectTwo); //returns false
That is because, as stated in this answer to a different, but similar question, the ===
operator actually means that both operands reference the same object, or in case of value types, have the same value.
In my case the function throwing error was async so I followed here:
await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);
This worked for me in every case:
ng test --include='**/dealer.service.spec.ts'
However, I usually got "TypeError: Cannot read property 'ngModule' of null" for this:
ng test --main src/app/services/dealer.service.spec.ts
Version of @angular/cli 10.0.4
just for the record you can always compare using JSON.stringify
const arr = [1,2,3];
expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3]));
expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));
It's all meter of taste, this will also work for complex literal objects
As most of the developers don't recommend testing private function, Why not test it?.
Eg.
YourClass.ts
export class FooBar {
private _status: number;
constructor( private foo : Bar ) {
this.initFooBar({});
}
private initFooBar(data){
this.foo.bar( data );
this._status = this.foo.foo();
}
}
TestYourClass.spec.ts
describe("Testing foo bar for status being set", function() {
...
//Variable with type any
let fooBar;
fooBar = new FooBar();
...
//Method 1
//Now this will be visible
fooBar.initFooBar();
//Method 2
//This doesn't require variable with any type
fooBar['initFooBar']();
...
}
Thanks to @Aaron, @Thierry Templier.
I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges();
was really necessary so I removed it and it still worked. Then I removed tick();
to see if it worked and it did. Finally I removed the test from the fakeAsync()
wrap, and surprise, it worked.
So I ended up with this:
it('should call onClick method', () => {
const onClickMock = spyOn(component, 'onClick');
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
expect(onClickMock).toHaveBeenCalled();
});
And it worked just fine.
Also, you can create your own outerHeight
for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle
, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
grep --include={*.php,*.html} -rnl './' -e "old" | xargs -i@ sed -i 's/old/new/g' @
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
MySQL has restrictions about referring to the table you are deleting from. You can work around that with a temporary table, like:
create temporary table tmpTable (id int);
insert into tmpTable
(id)
select id
from YourTable yt
where exists
(
select *
from YourTabe yt2
where yt2.title = yt.title
and yt2.company = yt.company
and yt2.site_id = yt.site_id
and yt2.id > yt.id
);
delete
from YourTable
where ID in (select id from tmpTable);
From Kostanos' suggestion in the comments:
The only slow query above is DELETE, for cases where you have a very large database. This query could be faster:
DELETE FROM YourTable USING YourTable, tmpTable WHERE YourTable.id=tmpTable.id
You can bulk import all aliases from one keystore to another:
keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks
You can unload a ClassLoader but you cannot unload specific classes. More specifically you cannot unload classes created in a ClassLoader that's not under your control.
If possible, I suggest using your own ClassLoader so you can unload.
Your question may mean two different things:
1.) Open a web page with a browser.
#include <windows.h>
#include <shellapi.h>
...
ShellExecute(0, 0, L"http://www.google.com", 0, 0 , SW_SHOW );
This should work, it opens the file with the associated program. Should open the browser, which is usually the default web browser.
2.) Get the code of a webpage and you will render it yourself or do some other thing. For this I recommend to read this or/and this.
I hope it's at least a little helpful.
EDIT: Did not notice, what you are asking for UNIX, this only work on Windows.
<script type="text/javascript">
$('input:text, input:password, textarea').blur(function()
{
var check = $(this).val();
if(check == '')
{
$(this).parent().addClass('ym-error');
}
else
{
$(this).parent().removeClass('ym-error');
}
});
</script>// :)
For .NET 2.0 you could implement a class which inherits from Dictionary
and implements ICloneable
.
public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : ICloneable
{
public IDictionary<TKey, TValue> Clone()
{
CloneableDictionary<TKey, TValue> clone = new CloneableDictionary<TKey, TValue>();
foreach (KeyValuePair<TKey, TValue> pair in this)
{
clone.Add(pair.Key, (TValue)pair.Value.Clone());
}
return clone;
}
}
You can then clone the dictionary simply by calling the Clone
method. Of course this implementation requires that the value type of the dictionary implements ICloneable
, but otherwise a generic implementation isn't practical at all.
Software & Database is usually not in the Standard edition of Visio, only the Pro version.
Try looking here for some templates that will work in standard edition
If you want to collapse/expand
an area within a class/method
(instead of collapsing the entire class/method
), you may create custom regions as follow:
#region AnyNameforCollapsableRegion
//Code to collapse
#endregion
What I ended up doing is:
internal void LoadExternalData() {
FileStream file;
if (TryOpenRead("filepath/filename", 5, out file)) {
using (file)
using (StreamReader reader = new StreamReader(file)) {
// do something
}
}
}
internal bool TryOpenRead(string path, int timeout, out FileStream file) {
bool isLocked = true;
bool condition = true;
do {
try {
file = File.OpenRead(path);
return true;
}
catch (IOException e) {
var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
isLocked = errorCode == 32 || errorCode == 33;
condition = (isLocked && timeout > 0);
if (condition) {
// we only wait if the file is locked. If the exception is of any other type, there's no point on keep trying. just return false and null;
timeout--;
new System.Threading.ManualResetEvent(false).WaitOne(1000);
}
}
}
while (condition);
file = null;
return false;
}
Do you have a local user.name
or user.email
that's overriding the global one?
git config --list --global | grep user
user.name=YOUR NAME
user.email=YOUR@EMAIL
git config --list --local | grep user
user.name=YOUR NAME
user.email=
If so, remove them
git config --unset --local user.name
git config --unset --local user.email
The local settings are per-clone, so you'll have to unset the local user.name
and user.email
for each of the repos on your machine.
Find a note here: https://code.visualstudio.com/docs/python/environments#_conda-environments
As noted earlier, the Python extension automatically detects existing conda environments provided that the environment contains a Python interpreter. For example, the following command creates a conda environment with the Python 3.4 interpreter and several libraries, which VS Code then shows in the list of available interpreters:
conda create -n env-01 python=3.4 scipy=0.15.0 astroid babel
In contrast, if you fail to specify an interpreter, as with conda create --name env-00, the environment won't appear in the list.
public class Arr {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {1,2,3};
//let a[] is your original array
System.out.println(a[0] + " " + a[1] + " " + a[2]);
int b[];
//let b[] is your temporary array with size greater than a[]
//I have took 5
b = new int[5];
//now assign all a[] values to b[]
for(int i = 0 ; i < a.length ; i ++)
b[i] = a[i];
//add next index values to b
b[3] = 4;
b[4] = 5;
//now assign b[] to a[]
a = b;
//now you can heck that size of an original array increased
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " "
+ a[4]);
}
}
Output for the above code is:
1 2 3
1 2 3 4 5
A Compiler translates lines of code from the programming language into machine language.
A Linker creates a link between two programs.
A Loader loads the program into memory in the main database, program, etc.
Peters' python 2 workaround fails on an edge case:
d = {u'keyword': u'bad credit \xe7redit cards'}
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(d, ensure_ascii=False).decode('utf8')
try:
json_file.write(data)
except TypeError:
# Decode data to Unicode first
json_file.write(data.decode('utf8'))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 25: ordinal not in range(128)
It was crashing on the .decode('utf8') part of line 3. I fixed the problem by making the program much simpler by avoiding that step as well as the special casing of ascii:
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(d, ensure_ascii=False, encoding='utf8')
json_file.write(unicode(data))
cat filename
{"keyword": "bad credit çredit cards"}
In React.js latest version v17.0.1, we can not require the local image we have to import it. like we use to do before = require('../../src/Assets/images/fruits.png'); Now we have to import it like = import fruits from '../../src/Assets/images/fruits.png';
Before React V17.0.1 we can use require(../) and it is working fine.
After some research, I found out some solution, and thanks to @Günter Zöchbauer,
I used column instead of Container and
set the property to column CrossAxisAlignment.stretch to Fill match parent of Button
new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new RaisedButton(
child: new Text(
"Submit",
style: new TextStyle(
color: Colors.white,
)
),
colorBrightness: Brightness.dark,
onPressed: () {
_loginAttempt(context);
},
color: Colors.blue,
),
],
),
Working with all types of Radio Buttons and Browsers
if($('#radio_button_id')[0].checked) {
alert("radiobutton checked")
}
else{
alert("not checked");
}
One point: you have to set NumberFormat property BEFORE loading the value into the cell. I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded. Setting the property before loading the value made the number appear as I wanted, as straight text.
OR:
Could you try an autofit first:
Excel_Obj.Columns("A:V").EntireColumn.AutoFit
In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent
so you don't need to wrap it with a call to Html.Raw()
.
It should be as simple as:
<script>
var json = @Json.Serialize(Model.CollegeInformationlist);
</script>
For everyone asking for code in C#, below is a simplified version of my implementation.
public static void TakeScreenshot(IWebDriver driver, IWebElement element)
{
try
{
string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
System.Drawing.Rectangle croppedImage = new System.Drawing.Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
screenshot = screenshot.Clone(croppedImage, screenshot.PixelFormat);
screenshot.Save(String.Format(@"C:\SeleniumScreenshots\" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg));
}
catch (Exception e)
{
logger.Error(e.StackTrace + ' ' + e.Message);
}
}
You are POSTing the json incorrectly -- but even if it were correct, you would not be able to test using print_r($_POST)
(read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input")
, which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
In your code, you are indicating Content-Type:application/json
, but you are not json-encoding all of the POST data -- only the value of the "customer" POST field. Instead, do something like this:
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";
Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.
I received the same error when trying to clone a heroku git repository.
Upon accessing heroku dashboard I saw a warning that the tool was under maintenance, and should come back in a few hours.
Cloning into 'foo-repository'...
remote: ! Heroku has temporarily disabled this feature, please try again shortly. See https://status.heroku.com for current Heroku platform status.
fatal: unable to access 'https://git.heroku.com/foo-repository.git/': The requested URL returned error: 503
If you receive the same error, check the service status
Firt add a reference to System.web
, if you don't have. Do that in the References folder.
You can then use Hosting.HostingEnvironment.MapPath(path);
It seems problem is not in JDK bug 6602600 ( it was solved at 2010-05-22), but in incorrect call of sleep(10) in circle. Addition note, that the main Thread must give directly CHANCE to other threads to realize thier tasks by invoke SLEEP(0) in EVERY branch of outer circle. It is better, I think, to use Thread.yield() instead of Thread.sleep(0)
The result corrected part of previous problem code is such like this:
.......................
........................
Thread.yield();
if (i % 1000== 0) {
System.out.println(i + "/" + counter.get()+ "/"+service.toString());
}
//
// while (i > counter.get()) {
// Thread.sleep(10);
// }
It works correctly with amount of outer counter up to 150 000 000 tested circles.
if you are trying DB first then be sure that your table has primary key
I know this is an old thread but I just stumbled across.
So heres how I would do it, with your local template variable on the input field you can set the value of the input like below
<input mdInput placeholder="Name" #filterName name="filterName" >
@ViewChild() input: ElementRef
public clear() {
this.input.NativeElement.value = '';
}
Pretty sure this will not set the form back to pristine but you can then reset this in the same function using the markAsPristine()
function
Another option compatible to 4.0:
Before committing the changes, you can recover the new CayenneDataObject
object(s) from the collection associated to the context, like this:
CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();
then access the ObjectId
for each one in the collection, like:
ObjectId objectId = dataObject.getObjectId();
Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot()
, it contains also the column name(s) associated to the PK as key(s):
objectId.getIdSnapshot().values()
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
If you have too many installers to find what you are looking for easily, here is some powershell to provide a filter and narrow it down a little by display name.
$filter = "*core*sdk*"; (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name | % { $path = "Registry::$_"; Get-ItemProperty $path } | Where-Object { $_.DisplayName -like $filter } | Select-Object -Property DisplayName, PsChildName
UPDATE: As TimK pointed out, this isn't needed with jquery 1.5.2 any more. But if you want to add custom headers or allow the use of credentials (username, password, or cookies, etc), read on.
I think I found the answer! (4 hours and a lot of cursing later)
//This does not work!!
Access-Control-Allow-Headers: *
You need to manually specify all the headers you will accept (at least that was the case for me in FF 4.0 & Chrome 10.0.648.204).
jQuery's $.ajax method sends the "x-requested-with" header for all cross domain requests (i think its only cross domain).
So the missing header needed to respond to the OPTIONS request is:
//no longer needed as of jquery 1.5.2
Access-Control-Allow-Headers: x-requested-with
If you are passing any non "simple" headers, you will need to include them in your list (i send one more):
//only need part of this for my custom header
Access-Control-Allow-Headers: x-requested-with, x-requested-by
So to put it all together, here is my PHP:
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: http://www.example.com');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'OPTIONS')
{
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
exit(0);
}
Check this link
get distinct rows from datatable using Linq (distinct with mulitiple columns)
Or try this
var distinctRows = (from DataRow dRow in dTable.Rows
select new { col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();
EDIT: Placed the missing first curly brace.
Juste add ShowHeaderWhenEmpty property and set it at true
This solution works for me
I already had python3 installed(via miniconda3) and needed to install python2 alongside in that case brew install python
won't install python2, so you would need
brew install python@2
.
Now alias python2
refers to python2.x from /usr/bin/python
and alias python3
refers to python3.x from /Users/ishandutta2007/miniconda3/bin/python
and alias python
refers to python3 by default.
Now to use python
as alias for python2, I added the following to .bashrc
file
alias python='/usr/bin/python'
.
To go back to python3 as default just remove this line when required.
You can check if string contains numbers only:
Regex.IsMatch(myStringVariable, @"^-?\d+$")
But number can be bigger than Int32.MaxValue
or less than Int32.MinValue
- you should keep that in mind.
Another option - create extension method and move ugly code there:
public static bool IsInteger(this string s)
{
if (String.IsNullOrEmpty(s))
return false;
int i;
return Int32.TryParse(s, out i);
}
That will make your code more clean:
if (myStringVariable.IsInteger())
// ...
Try:
require(Hmisc)
sapply(name, function(x) {
paste(sapply(strsplit(x, ' '), capitalize), collapse=' ')
})
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n0 = input.nextInt(); // number of intended input.
int [] MyList = new int [n0];
for (int i = 0; i < n0; i++)
MyList[i] = input.nextInt();
//input values stored in an array
int i = 0;
int count = 0;
int gcd = 1; // Initial gcd is 1
int k = 2; // Possible gcd
while (k <= MyList[i] && k <= MyList[i]) {
if (MyList[i] % k == 0 && MyList[i] % k == 0)
gcd = k; // Update gcd
k++;
count++; //checking array for gcd
}
// int i = 0;
MyList [i] = gcd;
for (int e: MyList) {
System.out.println(e);
}
}
}
You can use nunique
in pandas:
df.hID.nunique()
# 5
It looks like you may be confused as to when commands are run. In your example, you are calling the get
method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop
.
Try adding a button that calls the get
method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
IF,
Then,
It is highly recommended that you install xampp 1.7.0 . Download Link
Note: This is not a solution to the above problem, but a FIX which would allow you to continue with your development.
From the Intel's manual - Instruction Set Reference, the JE
and JZ
have the same opcode (74
for rel8 / 0F 84
for rel 16/32) also JNE
and JNZ
(75
for rel8 / 0F 85
for rel 16/32) share opcodes.
JE
and JZ
they both check for the ZF
(or zero flag), although the manual differs slightly in the descriptions of the first JE
rel8 and JZ
rel8 ZF
usage, but basically they are the same.
Here is an extract from the manual's pages 464, 465 and 467.
Op Code | mnemonic | Description
-----------|-----------|-----------------------------------------------
74 cb | JE rel8 | Jump short if equal (ZF=1).
74 cb | JZ rel8 | Jump short if zero (ZF ? 1).
0F 84 cw | JE rel16 | Jump near if equal (ZF=1). Not supported in 64-bit mode.
0F 84 cw | JZ rel16 | Jump near if 0 (ZF=1). Not supported in 64-bit mode.
0F 84 cd | JE rel32 | Jump near if equal (ZF=1).
0F 84 cd | JZ rel32 | Jump near if 0 (ZF=1).
75 cb | JNE rel8 | Jump short if not equal (ZF=0).
75 cb | JNZ rel8 | Jump short if not zero (ZF=0).
0F 85 cd | JNE rel32 | Jump near if not equal (ZF=0).
0F 85 cd | JNZ rel32 | Jump near if not zero (ZF=0).
I had this issue - across iOS & Android, developing on Mac - after I had been fiddling with a dependency's code in the node_modules
dir.
I solved it with:
rm -rf node_modules
npm i
npx pod-install ios
Which basically just re-installs your dependencies fresh.
I saw this error when my header file was missing closing brackets.
Causing this error:
// Obj.h
class Obj {
public:
Obj();
Fixing this error:
// Obj.h
class Obj {
public:
Obj();
};
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file
Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:
wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz
And then proceed to install it.
UPDATE: Adding complete instructions (copied from the comment below)
run the following to extract the tar:
tar xvf apache-maven-3.2.1-bin.tar.gz
Next add the env varibles such as
export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Verify
mvn -version
If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.
Code:
// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
HttpRequestHeaders DefaultRequestHeaders { get; }
Uri BaseAddress { get; set; }
// ...
// All the other methods from peeking at HttpClient
}
public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
public static HashSet<Uri> _uris;
static HttpClientHander()
{
_httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
_uris = new HashSet<Uri>();
SetupGlobalPoolFinalizer();
}
private DateTime _delayFinalization = DateTime.MinValue;
private bool _isDisposed = false;
public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
{
HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
_uris.Add(baseUrl);
httpClient._delayFinalization = DateTime.MinValue;
httpClient.BaseAddress = baseUrl;
return httpClient;
}
void IDisposable.Dispose()
{
_isDisposed = true;
GC.SuppressFinalize(this);
base.Dispose();
}
~HttpClientHander()
{
if (_delayFinalization == DateTime.MinValue)
_delayFinalization = DateTime.UtcNow;
if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
GC.ReRegisterForFinalize(this);
}
private static void SetupGlobalPoolFinalizer()
{
AppDomain.CurrentDomain.ProcessExit +=
(sender, eventArgs) => { FinalizeGlobalPool(); };
}
private static void FinalizeGlobalPool()
{
foreach (var key in _uris)
{
HttpClientHander value = null;
if (_httpClientsPool.TryGetValue(key, out value))
try { value.Dispose(); } catch { }
}
_uris.Clear();
_httpClientsPool = null;
}
}
var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).
According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.
See in the android sdk directory.
In \platforms\android-X\data\res\values\themes.xml
:
<item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
<item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
In \platforms\android-X\data\res\values\styles.xml
:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
</style>
<style name="TextAppearance.Medium">
<item name="android:textSize">18sp</item>
</style>
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
TextAppearance.Large
means style is inheriting from TextAppearance
style, you have to trace it also if you want to see full definition of a style.
Link: http://developer.android.com/design/style/typography.html
Update 2018
Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.
<input type="email" class="form-control" id="exampleInputEmail1" required>
or in compliant HTML5:
<input type="email" class="form-control" id="exampleInputEmail1" required="true">
Read more on Bootstrap 4 validation
In Bootstrap 3, you can apply a "validation state" class to the parent element: http://getbootstrap.com/css/#forms-control-validation
For example has-error
will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.
Demo: http://bootply.com/90564
First give your form an id
attribute, then use code like this:
$(document).ready( function() {
var form = $('#my_awesome_form');
form.find('select:first').change( function() {
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
} );
} );
So this code uses .serialize()
to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.
For future reference, the jQuery docs are very, very good.
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
While @Aaron Maenpaa's answer just works, a user recently asked:
Is there any more simply way? 'fhand.read().decode("ASCII")' [...] It's so long!
You can use:
command_stdout.decode()
decode()
has a standard argument:
codecs.decode(obj, encoding='utf-8', errors='strict')
First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.
After that, use this code to draw the text:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img = Image.open("filename.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size
img.save('sample-out.jpg')
Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?
var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone',
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike
v7.6 release 92', 'Pike v7.8 release 517'];
// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
// Execute code
}
// If NOT on Apple device
else {
// Execute code
}
For anyone else who gets caught, ensure setCustomAnimations is called before the call to replace/add when building the transaction.
#define GENERAL__GET_BITS_FROM_U8(source,lsb,msb) \
((uint8_t)((source) & \
((uint8_t)(((uint8_t)(0xFF >> ((uint8_t)(7-((uint8_t)(msb) & 7))))) & \
((uint8_t)(0xFF << ((uint8_t)(lsb) & 7)))))))
#define GENERAL__GET_BITS_FROM_U16(source,lsb,msb) \
((uint16_t)((source) & \
((uint16_t)(((uint16_t)(0xFFFF >> ((uint8_t)(15-((uint8_t)(msb) & 15))))) & \
((uint16_t)(0xFFFF << ((uint8_t)(lsb) & 15)))))))
#define GENERAL__GET_BITS_FROM_U32(source,lsb,msb) \
((uint32_t)((source) & \
((uint32_t)(((uint32_t)(0xFFFFFFFF >> ((uint8_t)(31-((uint8_t)(msb) & 31))))) & \
((uint32_t)(0xFFFFFFFF << ((uint8_t)(lsb) & 31)))))))
Hmm, I actually think I'm onto something (this is like the most interesting question ever - so it'd be a shame not to continue trying to find the "perfect" answer, even though an acceptable one has been found)...
Once you find the logo, your troubles are half done. Then you only have to figure out the differences between what's around the logo. Additionally, we want to do as little extra as possible. I think this is actually this easy part...
What is around the logo? For a can, we can see metal, which despite the effects of lighting, does not change whatsoever in its basic colour. As long as we know the angle of the label, we can tell what's directly above it, so we're looking at the difference between these:
Here, what's above and below the logo is completely dark, consistent in colour. Relatively easy in that respect.
Here, what's above and below is light, but still consistent in colour. It's all-silver, and all-silver metal actually seems pretty rare, as well as silver colours in general. Additionally, it's in a thin slither and close enough to the red that has already been identified so you could trace its shape for its entire length to calculate a percentage of what can be considered the metal ring of the can. Really, you only need a small fraction of that anywhere along the can to tell it is part of it, but you still need to find a balance that ensures it's not just an empty bottle with something metal behind it.
And finally, the tricky one. But not so tricky, once we're only going by what we can see directly above (and below) the red wrapper. Its transparent, which means it will show whatever is behind it. That's good, because things that are behind it aren't likely to be as consistent in colour as the silver circular metal of the can. There could be many different things behind it, which would tell us that it's an empty (or filled with clear liquid) bottle, or a consistent colour, which could either mean that it's filled with liquid or that the bottle is simply in front of a solid colour. We're working with what's closest to the top and bottom, and the chances of the right colours being in the right place are relatively slim. We know it's a bottle, because it hasn't got that key visual element of the can, which is relatively simplistic compared to what could be behind a bottle.
(that last one was the best I could find of an empty large coca cola bottle - interestingly the cap AND ring are yellow, indicating that the redness of the cap probably shouldn't be relied upon)
In the rare circumstance that a similar shade of silver is behind the bottle, even after the abstraction of the plastic, or the bottle is somehow filled with the same shade of silver liquid, we can fall back on what we can roughly estimate as being the shape of the silver - which as I mentioned, is circular and follows the shape of the can. But even though I lack any certain knowledge in image processing, that sounds slow. Better yet, why not deduce this by for once checking around the sides of the logo to ensure there is nothing of the same silver colour there? Ah, but what if there's the same shade of silver behind a can? Then, we do indeed have to pay more attention to shapes, looking at the top and bottom of the can again.
Depending on how flawless this all needs to be, it could be very slow, but I guess my basic concept is to check the easiest and closest things first. Go by colour differences around the already matched shape (which seems the most trivial part of this anyway) before going to the effort of working out the shape of the other elements. To list it, it goes:
In the event you can't do this, it probably means the top and bottom of the can are covered, and the only possible things that a human could have used to reliably make a distinction between the can and the bottle is the occlusion and reflection of the can, which would be a much harder battle to process. However, to go even further, you could follow the angle of the can/bottle to check for more bottle-like traits, using the semi-transparent scanning techniques mentioned in the other answers.
Interesting additional nightmares might include a can conveniently sitting behind the bottle at such a distance that the metal of it just so happens to show above and below the label, which would still fail as long as you're scanning along the entire length of the red label - which is actually more of a problem because you're not detecting a can where you could have, as opposed to considering that you're actually detecting a bottle, including the can by accident. The glass is half empty, in that case!
As a disclaimer, I have no experience in nor have ever thought about image processing outside of this question, but it is so interesting that it got me thinking pretty deeply about it, and after reading all the other answers, I consider this to possibly be the easiest and most efficient way to get it done. Personally, I'm just glad I don't actually have to think about programming this!
EDIT
Additionally, look at this drawing I did in MS Paint... It's absolutely awful and quite incomplete, but based on the shape and colours alone, you can guess what it's probably going to be. In essence, these are the only things that one needs to bother scanning for. When you look at that very distinctive shape and combination of colours so close, what else could it possibly be? The bit I didn't paint, the white background, should be considered "anything inconsistent". If it had a transparent background, it could go over almost any other image and you could still see it.
Using balexandre's info:
SELECT usesysid, usename FROM pg_stat_activity;
use this way in xml
<TextView
android:id="@+id/myText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Time is precious, so love now."
android:gravity="center"
android:textSize="30dp"
android:textColor="#fff"
/>
On the etymology the term boilerplate: from http://www.takeourword.com/Issue009.html...
Interestingly, the term arose from the newspaper business. Columns and other pieces that were syndicated were sent out to subscribing newspapers in the form of a mat (i.e. a matrix). Once received, boiling lead was poured into this mat to create the plate used to print the piece, hence the name boilerplate. As the article printed on a boilerplate could not be altered, the term came to be used by attorneys to refer to the portions of a contract which did not change through repeated uses in different applications, and finally to language in general which did not change in any document that was used repeatedly for different occasions.
What constitutes boilerplate in programming? As may others have pointed out, it is just a chunk of code that is copied over and over again with little or no changes made to it in the process.
Wanted to add the UI portal Way to do as well. In case you want to create the folder structure, you would have to do it with the complete path for each file.
You need to Click on Upload Blob, Expand the Advanced and put it the path saying "Upload to Folder"
So Lets say you have a folder assets you want to upload and the content of the folder look like below
And if you have a folder under js folder with name main.js, you need to type in the path "assets/js" in upload to folder. Now This has to be done for each file. In case you have a lot of file, its recommended you do it programmatically.
Let's illustrate what's happening here:
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self, x=[]):
... x.append(1)
...
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)
You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults
.
As other posters have pointed out, you probably want to use None
as a sentinel value and give each instance it's own list.
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
To see all the branches with out using git branch -a
you should execute:
for remote in `git branch -r`; do git branch --track $remote; done
git fetch --all
git pull --all
Now you can see all the branches:
git branch
To push all the branches try:
git push --all
I would try
Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy
Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste
For those that are wondering how to copy your extensions from Visual Studio Code to Visual Studio Code insiders, use this modification of Benny's answer:
code --list-extensions | xargs -L 1 echo code-insiders --install-extension
Altering a view could be accomplished by dropping the view and recreating it. Use the following to drop and recreate your view.
IF EXISTS
(SELECT NAME FROM SYS.VIEWS WHERE NAME = 'dbo.test_abc_def')
DROP VIEW dbo.test_abc_def) go
CREATE VIEW dbo.test_abc_def AS
SELECT
VCV.xxxx,
VCV.yyyy AS yyyy
,VCV.zzzz AS zzzz
FROM TABLE_A
I solved the same problem by add android:elevation="1dp"
to which view you want it over another. But it can't display below 5.0, and it will have a little shadow, if you can accept it, it's OK.
So, the most correct solution which is @kcoppock said.
The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.
You need to create an int
variable somewhere in memory for the int *
variable to point at.
Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:
int main(){
int variable;
int *ptr = &variable;
*ptr = 20;
printf("%d", *ptr);
return 0;
}
Here, the int
variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20
. The key is that the pointer is initialized to point to the variable
. In fact, you could just allocate some raw memory to point to, if you want:
int main(){
void *memory = malloc(sizeof(int));
int *ptr = (int *)memory;
*ptr = 20;
printf("%d", *ptr);
free(memory);
return 0;
}
Liquibase was getting this error for me. I resolved this after I debugged and watched liquibase try to load the libraries and found that it was erroring on the manifest files for commons-codec-1.6.jar. Essentially, there is either a corrupt zip file somewhere in your path or there is a incompatible version being used. When I did an explore on Maven repository for this library, I found there were newer versions and added the newer version to the pom.xml. I was able to proceed at this point.
If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:
Markup:
<span runat="server" id="FooSpan"></span>
Code:
FooSpan.Text = "Foo";
Use
ax.xaxis.tick_top()
to place the tick marks at the top of the image. The command
ax.set_xlabel('X LABEL')
ax.xaxis.set_label_position('top')
affects the label, not the tick marks.
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()
Unmanaged object:
Marshal.SizeOf(object yourObj);
Value Types:
sizeof(object val)
Managed object:
for those searching for an alternative to $result = $stmt->get_result()
I've made this function which allows you to mimic the $result->fetch_assoc()
but using directly the stmt object:
function fetchAssocStatement($stmt)
{
if($stmt->num_rows>0)
{
$result = array();
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
if($stmt->fetch())
return $result;
}
return null;
}
as you can see it creates an array and fetches it with the row data, since it uses $stmt->fetch()
internally, you can call it just as you would call mysqli_result::fetch_assoc
(just be sure that the $stmt
object is open and result is stored):
//mysqliConnection is your mysqli connection object
if($stmt = $mysqli_connection->prepare($query))
{
$stmt->execute();
$stmt->store_result();
while($assoc_array = fetchAssocStatement($stmt))
{
//do your magic
}
$stmt->close();
}
This article describes maximum transmission unit (MTU) http://en.wikipedia.org/wiki/Maximum_transmission_unit. It states that IP hosts must be able to process 576 bytes for an IP packet. However, it notes the minumum is 68. RFC 791: "Every internet module must be able to forward a datagram of 68 octets without further fragmentation. This is because an internet header may be up to 60 octets, and the minimum fragment is 8 octets."
Thus, safe packet size of 508 = 576 - 60 (IP header) - 8 (udp header) is reasonable.
As mentioned by user607811, fragmentation by other network layers must be reassembled. https://tools.ietf.org/html/rfc1122#page-56 3.3.2 Reassembly The IP layer MUST implement reassembly of IP datagrams. We designate the largest datagram size that can be reassembled by EMTU_R ("Effective MTU to receive"); this is sometimes called the "reassembly buffer size". EMTU_R MUST be greater than or equal to 576
Each call to nextLine()
moves onto the next line, so when you are actually at the last readable line and the while
check passes inspection, the next call to nextLine()
will return EOF
.
Perhaps you could do one of the following instead:
If fileReader
is of type Scanner
:
while ((line = fileReader.hasNextLine()) != null) {
String line = fileReader.nextLine();
System.out.println(line);
}
If fileReader
is of type BufferedReader
:
String line;
while ((line = fileReader.readLine()) != null) {
System.out.println(line);
}
So you're reading the current line in the while condition and saving the line in a string for later use.
There is a C# wrapper for that which is open source, hosted on Codeplex called Web Image Cropping
Register the control
<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>
Resizing
<asp:Image ID="Image1" runat="server" ImageUrl="images/328.jpg" />
<cs:CropImage ID="wci1" runat="server" Image="Image1"
X="10" Y="10" X2="50" Y2="50" />
Cropping in code behind - Call Crop method when button clicked for example;
wci1.Crop(Server.MapPath("images/sample1.jpg"));
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
I think what you're looking for is FROM_UNIXTIME()
If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
Create the Button
and add it to Form.Controls
list to display it on your form:
Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45); //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list
Create the button click method here:
void buttonOk_Click(object sender, EventArgs e)
{
MessageBox.Show("clicked");
this.Close(); //all your choice to close it or remove this line
}
First Import the package as :
import org.openqa.selenium.support.ui.Select;
then write in single line as:
new Select (driver.findElement(By.id("sampleid"))).selectByValue("SampleValue");
You can use the 're' module in Python 3.
If you indeed do, use this:
re.search('\s', word)
This should return either 'true' if there's a match, or 'false' if there isn't any.
I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child View
s in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.
For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.
private List<View> getAllChildrenBFS(View v) {
List<View> visited = new ArrayList<View>();
List<View> unvisited = new ArrayList<View>();
unvisited.add(v);
while (!unvisited.isEmpty()) {
View child = unvisited.remove(0);
visited.add(child);
if (!(child instanceof ViewGroup)) continue;
ViewGroup group = (ViewGroup) child;
final int childCount = group.getChildCount();
for (int i=0; i<childCount; i++) unvisited.add(group.getChildAt(i));
}
return visited;
}
A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList
instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.
Cross-posted from: Android | Get all children elements of a ViewGroup
Because it's all just about memory, in the end all the numerical values are stored in binary.
A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.
When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.
If you work on Windows , you must start Android Studio name by Administrator. It solved my problem
I've used this much simpler solution:
setOnScrollListener( new OnScrollListener()
{
private int mInitialScroll = 0;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
{
int scrolledOffset = computeVerticalScrollOffset();
boolean scrollUp = scrolledOffset > mInitialScroll;
mInitialScroll = scrolledOffset;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
It can be done by three different ways,though all them are nearly the same
Javascript way
document.getElementById('test').value
Jquery way
$("#test").val()
$("#test")[0].value
$("#test").get(0).value
As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
td { width: 30px; overflow: hidden; }
table { width : 90px; table-layout: fixed; }
</style>
</head>
<body>
<table border="2">
<tr>
<td>word</td>
<td>two words</td>
<td>onereallylongword</td>
</tr>
</table>
</body>
</html>
I've tested this in IE6 and 7 and it seems to work fine.
I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
from names
group by author_id) n2
on (n2.author_id = n1.author_id)
// create a vector of unknown players.
std::vector<player> players;
// resize said vector to only contain 6 players.
players.resize(6);
Values are always initialized, so a vector of 6 players is a vector of 6 valid player objects.
As for the second part, you need to use pointers. Instantiating c++ interface as a child class
When echoing something to redirect to a file, multiple echo commands will not work. I think maybe the ">>" redirector is a good choice:
echo hello > temp echo world >> temp
A char
is an integral type. When you write
char ch = 'A';
you're setting the value of ch
to whatever number your compiler uses to represent the character 'A'
. That's usually the ASCII code for 'A'
these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char
value, just do it: ch = ch + 1;
etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char
values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
One option, if you're looking for the actual queried page, rather than the page ID or slug is to intercept the query:
add_action('parse_request', 'show_query', 10, 1);
Within your function, you have access to the $wp object and you can get either the pagename or the post name with:
function show_query($wp){
if ( ! is_admin() ){ // heck we don't need the admin pages
echo $wp->query_vars['pagename'];
echo $wp->query_vars['name'];
}
}
If, on the other hand, you really need the post data, the first place to get it (and arguably in this context, the best) is:
add_action('wp', 'show_page_name', 10, 1);
function show_page_name($wp){
if ( ! is_admin() ){
global $post;
echo $post->ID, " : ", $post->post_name;
}
}
Finally, I realize this probably wasn't the OP's question, but if you're looking for the Admin page name, use the global $pagenow
.
Based on your comment to Issun:
Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>
You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.
I did test several common objects and found that an instantiated Collection
with no items added shows <No Variables>
in the watch window. If your object is indeed a collection, you can check for the <No Variables>
condition using the .Count
property:
Sub TestObj()
Dim Obj As Object
Set Obj = New Collection
If Obj Is Nothing Then
Debug.Print "Object not instantiated"
Else
If Obj.Count = 0 Then
Debug.Print "<No Variables> (ie, no items added to the collection)"
Else
Debug.Print "Object instantiated and at least one item added"
End If
End If
End Sub
It is also worth noting that if you declare any object As New
then the Is Nothing
check becomes useless. The reason is that when you declare an object As New
then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!
Dim MyObject As New Collection
If MyObject Is Nothing Then ' <--- This check always returns False
This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe
(the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe
you'll get output in your console window.
I just found out that regexp_substr()
is perfect for this purpose :)
My challenge is picking the right-hand 16 chars from a reference string which theoretically can be everything from 7ish to 250ish chars long. It annoys me that substr( OurReference , -16 )
returns null
when length( OurReference ) < 16
. (On the other hand, it's kind of logical, too, that Oracle consequently returns null
whenever a call to substr()
goes beyond a string's boundaries.) However, I can set a regular expression to recognise everything between 1 and 16 of any char right before the end of the string:
regexp_substr( OurReference , '.{1,16}$' )
When it comes to performance issues regarding regular expressions, I can't say which of the GREATER()
solution and this one performs best. Anyone test this? Generally I've experienced that regular expressions are quite fast if they're written neat and well (as this one).
Good luck! :)
To check whether select box has any values:
if( $('#fruit_name').has('option').length > 0 ) {
To check whether selected value is empty:
if( !$('#fruit_name').val() ) {
You can use two ways to resolve this problem, first way that i think it as best way is replace importing segment of your code with bellow one:
import Home from './layouts/Home'
or export your component without default which is called named export like this
import React, { Component } from 'react';
class Home extends Component{
render(){
return(
<p className="App-intro">
Hello Man
</p>
)
}
}
export {Home};
It says that it should be a 64-bit JDK. I have a feeling that you installed (at a previous time) a 32-bit version of Java. The path for all 32-bit applications in Windows 7 and Vista is:
C:\Program Files (x86)\
You were setting the JAVA_HOME
variable to the 32-bit version of Java. Set your JAVA_HOME
variable to the following:
C:\Program Files\Java\jdk1.7.0_45
If that does not work, check that the JDK version is 1.7.0_45. If not, change the JAVA_HOME
variable to (with JAVAVERSION
as the Java version number:
C:\Program Files\Java\jdkJAVAVERSION
If you only call print
without any arguments, it will output a blank line.
print
You can pipe the output to a file like this (considering your example):
f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()
Not only is it OS-agnostic (without even having to use the os
package), it's also more readable than putting \n
within strings.
The print()
function has an optional keyword argument for the end of the string, called end
, which defaults to the OS's newline character, for eg. \n
. So, when you're calling print('hello')
, Python is actually printing 'hello' + '\n'
. Which means that when you're calling just print
without any arguments, it's actually printing '' + '\n'
, which results in a newline.
Use multi-line strings.
s = """First line
Second line
Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()
I was facing the same issue, to solve it I have added the below entry in pom.xml
and performed a maven update
.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
Cause they're not equal, ie: they're different arrays with equal elements inside.
Try using Arrays.equals()
or Arrays.deepEquals()
.
For a loop where you want to convert an array
of strings
to an array
of bigIntegers
do this:
String[] unsorted = new String[n]; //array of Strings
BigInteger[] series = new BigInteger[n]; //array of BigIntegers
for(int i=0; i<n; i++){
series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
}
I know two methods:
List<int> myList1 = new List<int>(myArray);
Or,
List<int> myList2 = myArray.ToList();
I'm assuming you know about data types and will change the types as you please.
.fadeOut('slow', this.remove);
When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com
Regarding how you log messages within code, I would opt for the second approach:
ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");
Where messages sent to the log above will be 'named' using the fully-qualifed type Bar
, e.g.
MyNamespace.Foo.Bar [INFO] message
The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar
specifically to DEBUG:
<log4net>
<!-- appenders go here -->
<root>
<level value="INFO" />
<appender-ref ref="myLogAppender" />
</root>
<logger name="MyNamespace.Foo.Bar">
<level value="DEBUG" />
</logger>
</log4net>
The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog"
, you loose much of this power!
Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.
For further reading, here is a codeproject article I wrote on logging:
In my case, I was passsing all models 'Users' to column and it wasn't mapped correctly, so I just passed 'Users.Name' and it fixed it.
var data = db.ApplicationTranceLogs
.Include(q=>q.Users)
.Include(q => q.LookupItems)
.Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users,*** ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data })
.ToList();
var data = db.ApplicationTranceLogs
.Include(q=>q.Users).Include(q => q.LookupItems)
.Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users.Name***, ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data })
.ToList();
Even if this thread is old is the first on Google, so I'll post an Oracle equivalent to the function implemented here, using regular expressions.
Is fairly faster than nested replace(), and much cleaner.
To replace strings 'a','b','c' with 'd' in a string column from a given table
select regexp_replace(string_col,'a|b|c','d') from given_table
It is nothing else than a regular expression for several static patterns with 'or' operator.
Beware of regexp special characters!
You can have it this way:
It is important to mind the commas after each struct item or set of items.
earnings := []LineItemsType{
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
}
Working version of kgaidis's Objective C answer using Swift 3.0:
let flow = UICollectionViewFlowLayout()
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let numberOfItems = collectionView.numberOfItems(inSection: 0)
let combinedItemWidth:CGFloat = (CGFloat(numberOfItems) * flow.itemSize.width) + ((CGFloat(numberOfItems) - 1) * flow.minimumInteritemSpacing)
let padding = (collectionView.frame.size.width - combinedItemWidth) / 2
return UIEdgeInsetsMake(0, padding, 0, padding)
}
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
console.log
has nothing to do with jQuery.
It logs a message to a debugging console, such as Firebug.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
String.prototype.TrimStart = function (n) {
if (this.charAt(0) == n)
return this.substr(1);
};
String.prototype.TrimEnd = function (n) {
if (this.slice(-1) == n)
return this.slice(0, -1);
};
To solve this problem, github recommends Connecting over HTTPS.
Git's documentation discuss how to how to do exactly that using gitcredentials.
Solution 1
Static configuration of usernames for a given authentication context.
https://username:<personal-access-tokens>@repository-url.com
You will find the details in the documentation.
Solution 2
Use credential helpers to cache password (in memory for a short period of time).
git config --global credential.helper cache
Solution 3
Use credential helpers to store password (indefinitely on disk).
git config --global credential.helper 'store --file ~/.my-credentials'
You can find where the credential will be saved (If not set explicitly with --file) in the documentation.
If not set explicitly with --file, there are two files where git-credential-store will search for credentials in order of precedence:
~/.git-credentials
User-specific credentials file. $XDG_CONFIG_HOME/git/credentials Second user-specific credentials file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/credentials will be used. Any
credentials stored in this file will not be used if ~/.git-credentials has a matching credential as well. It is a good idea not to create this file if you sometimes use older versions of Git that do not support it.
P.S.
To address the concern:
your password is going to be stored completely unencrypted ("as is") at ~/.git-credentials.
You can always encrypt the file and decrypt it before using.
add a repository,
sudo apt-add-repository ppa:maarten-fonville/android-studio
sudo apt-get update
Then install using the command below:
sudo apt-get install android-studio
if not x is None
is more similar to other programming languages, but if x is not None
definitely sounds more clear (and is more grammatically correct in English) to me.
That said it seems like it's more of a preference thing to me.
Don't double click Project.xcodeproj to start your xcode project. Instead, close your project and open the xcworkspace.
File -> Close Workspace
File -> Open -> Search your project folder for Project.xcworkspace
All my errors are gone.
If you're dealing with multiple (html 5) file uploads, I took the top suggested comment and modified it a little:
var files = $('#file1')[0].files;
var len = $('#file1').get(0).files.length;
for (var i = 0; i < len; i++) {
f = files[i];
var ext = f.name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
alert('invalid extension!');
}
}
Another case of R. breakage is Annotations Processing.
Some processing could refer to classes located in certain folders or folder levels. If you move required classes to other location, you can get R. as an unknown class.
Unfortunately the error-pointer to this problem is not evident in Android Studio.
do you mean a method?
$('div.foo').attr('id', 'foo123');
Just be careful that you don't set multiple elements to the same ID.
Your regex looks correct, but you're splitting
with it instead of matching
with it. You want something like this:
// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
Using calendar module:
Number-to-Abbr
calendar.month_abbr[month_number]
Abbr-to-Number
list(calendar.month_abbr).index(month_abbr)
Swift 4,
private func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
if #available(iOS 10.0, *) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
application.openURL(phoneCallURL as URL)
}
}
}
}
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());
To summarize a bit from what people have been saying:
f=open('data.txt', 'w') # will make a new file or erase a file of that name if it is present
f=open('data.txt', 'r') # will open a file as read-only
f=open('data.txt', 'a') # will open a file for appending (appended data goes to the end of the file)
If you wish have something in place similar to a try/catch
with open('data.txt') as f:
for line in f:
print line
I think @movieyoda code is probably what you should use however
This procedure will remove all duplicates (incl multiples) in a table, keeping the last duplicate. This is an extension of Retrieving last record in each group
Hope this is useful to someone.
DROP TABLE IF EXISTS UniqueIDs;
CREATE Temporary table UniqueIDs (id Int(11));
INSERT INTO UniqueIDs
(SELECT T1.ID FROM Table T1 LEFT JOIN Table T2 ON
(T1.Field1 = T2.Field1 AND T1.Field2 = T2.Field2 #Comparison Fields
AND T1.ID < T2.ID)
WHERE T2.ID IS NULL);
DELETE FROM Table WHERE id NOT IN (SELECT ID FROM UniqueIDs);
Yes, thats right.
You can get an idea by the usage of these two.
If you need to tell that you are finished with some work and other (threads) waiting for this can now proceed, you should use ManualResetEvent.
If you need to have mutual exclusive access to any resource, you should use AutoResetEvent.
Edited on 2014/8/25: Here was where I forked it.
Thanks @anvarik.
Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @
<div ng-controller="MyCtrl">
<h2>Parent Scope</h2>
<input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>
<br><br>
<!-- attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated. -->
<my-component attribute-foo="{{foo}}" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>get:</strong> {{isolatedAttributeFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedBindingFoo">
<i>// This does update the parent scope.</i>
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
</div>
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'@attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.foo = 'Hello!';
$scope.updateFoo = function (newFoo) {
$scope.foo = newFoo;
}
}]);
There's a new library for traversing JSON data with JavaScript that supports many different use cases.
https://npmjs.org/package/traverse
https://github.com/substack/js-traverse
It works with all kinds of JavaScript objects. It even detects cycles.
It provides the path of each node, too.
Just download any eclipse with "EE" letters
In addition to Guffa's answer, you could use this variant to have a more shorthanded notation.
public static bool ScrambledEquals<T>(this IEnumerable<T> list1, IEnumerable<T> list2)
{
var deletedItems = list1.Except(list2).Any();
var newItems = list2.Except(list1).Any();
return !newItems && !deletedItems;
}
If you want to remove all pending tasks and also the active and reserved ones to completely stop Celery, this is what worked for me:
from proj.celery import app
from celery.task.control import inspect, revoke
# remove pending tasks
app.control.purge()
# remove active tasks
i = inspect()
jobs = i.active()
for hostname in jobs:
tasks = jobs[hostname]
for task in tasks:
revoke(task['id'], terminate=True)
# remove reserved tasks
jobs = i.reserved()
for hostname in jobs:
tasks = jobs[hostname]
for task in tasks:
revoke(task['id'], terminate=True)
<script type="text/javascript">
function test()
{
var path = "C:/es/h221.txt";
var pos =path.lastIndexOf( path.charAt( path.indexOf(":")+1) );
alert("pos=" + pos );
var filename = path.substring( pos+1);
alert( filename );
}
</script>
<form name="InputForm"
action="page2.asp"
method="post">
<P><input type="button" name="b1" value="test file button"
onClick="test()">
</form>
Combining the earlier suggestions to determine your personal permissions (ie 'USER' permissions), then use this:
-- your permissions
select * from USER_ROLE_PRIVS where USERNAME= USER;
select * from USER_TAB_PRIVS where Grantee = USER;
select * from USER_SYS_PRIVS where USERNAME = USER;
-- granted role permissions
select * from ROLE_ROLE_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_TAB_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_SYS_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
Login to mysql as root and type following query
select User from mysql.user;
+------+
| User |
+------+
| amon |
| root |
| root |
+------+
Running the following helped resolve the issue:
npm config set strict-ssl false
I cannot comment on whether it will cause any other issues at this point in time.
It's used for proxying requests to other servers.
An example from http://wiki.nginx.org/LoadBalanceExample is:
http {
upstream myproject {
server 127.0.0.1:8000 weight=3;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name www.domain.com;
location / {
proxy_pass http://myproject;
}
}
}
This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.
To get all indexes:
indexes = [i for i,x in enumerate(xs) if x == 'foo']
Every service that is bound in activity must be unbind on app close.
So try using
onPause(){
unbindService(YOUR_SERVICE);
super.onPause();
}
g++ -o foo foo.cpp
g++ --> Driver for cc1plus compiler
-o --> Indicates the output file (foo is the name of output file here. Can be any name)
foo.cpp --> Source file to be compiled
To execute the compiled file simply type
./foo
I had this issue myself, and I wanted to both be able to set the width, and have it update on rotate and allow the user to scale and zoom the page (the current answer provides the first but prevents the later as a side-effect).. so I came up with a fix that keeps the view width correct for the orientation, but still allows for zooming, though it is not super straight forward.
First, add the following Javascript to the webpage you are displaying:
<script type='text/javascript'>
function setViewPortWidth(width) {
var metatags = document.getElementsByTagName('meta');
for(cnt = 0; cnt < metatags.length; cnt++) {
var element = metatags[cnt];
if(element.getAttribute('name') == 'viewport') {
element.setAttribute('content','width = '+width+'; maximum-scale = 5; user-scalable = yes');
document.body.style['max-width'] = width+'px';
}
}
}
</script>
Then in your - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation method, add:
float availableWidth = [EmailVC webViewWidth];
NSString *stringJS;
stringJS = [NSString stringWithFormat:@"document.body.offsetWidth"];
float documentWidth = [[_webView stringByEvaluatingJavaScriptFromString:stringJS] floatValue];
if(documentWidth > availableWidth) return; // Don't perform if the document width is larger then available (allow auto-scale)
// Function setViewPortWidth defined in EmailBodyProtocolHandler prepend
stringJS = [NSString stringWithFormat:@"setViewPortWidth(%f);",availableWidth];
[_webView stringByEvaluatingJavaScriptFromString:stringJS];
Additional Tweaking can be done by modifying more of the viewportal content settings:
Also, I understand you can put a JS listener for onresize or something like to trigger the rescaling, but this worked for me as I'm doing it from Cocoa Touch UI frameworks.
Hope this helps someone :)
Because strip()
only strips trailing and leading characters, based on what you provided. I suggest:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
An established connection was aborted by the software in your host machine
That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.
The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.
You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.
If you are interested in parsing command line arguments to an R script try RScript which is bundled with R as of version 2.5.x
http://stat.ethz.ch/R-manual/R-patched/library/utils/html/Rscript.html
/**
* Get JSONP data for cross-domain AJAX requests
* @private
* @link http://cameronspear.com/blog/exactly-what-is-jsonp/
* @param {String} url The URL of the JSON request
* @param {String} callback The name of the callback to run on load
*/
var loadJSONP = function ( url, callback ) {
// Create script with url and callback (if specified)
var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
var script = window.document.createElement( 'script' );
script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;
// Insert script tag into the DOM (append to <head>)
ref.parentNode.insertBefore( script, ref );
// After the script is loaded (and executed), remove it
script.onload = function () {
this.remove();
};
};
/**
* Example
*/
// Function to run on success
var logAPI = function ( data ) {
console.log( data );
}
// Run request
loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );
This gives you last used row in a specified column.
Optionally you can specify worksheet, else it will takes active sheet.
Function shtRowCount(colm As Integer, Optional ws As Worksheet) As Long
If ws Is Nothing Then Set ws = ActiveSheet
If ws.Cells(Rows.Count, colm) <> "" Then
shtRowCount = ws.Cells(Rows.Count, colm).Row
Exit Function
End If
shtRowCount = ws.Cells(Rows.Count, colm).Row
If shtRowCount = 1 Then
If ws.Cells(1, colm) = "" Then
shtRowCount = 0
Else
shtRowCount = 1
End If
End If
End Function
Sub test()
Dim lgLastRow As Long
lgLastRow = shtRowCount(2) 'Column B
End Sub
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works
string = 'http://www.domain.com/?s=some&two=20'
cut_string = string.split('&')
new_string = cut_string[0]
print(new_string)
Try using a style and set colorControlActivated too desired ProgressBar color.
<style name="progressColor" parent="Widget.AppCompat.ProgressBar">
<item name="colorControlActivated">@color/COLOR</item>
</style>
Then set the theme of the ProgressBar to new style.
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/progressColor"
/>
If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!
When you add the first fragment you should use something like this:
getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit()
or
getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()
And when you want to show Fragments B,C and D you use this:
getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()
and other letters....
To return to Fragment
A, just call popBackStack(0, "A")
, yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack()
, not the one used in command replace or add.
You're welcome ;)
it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.
jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
public static void main(String args[]) {
Robot bot = null;
try {
bot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
bot.mouseMove(100, 100);
bot.mousePress(mask);
bot.mouseRelease(mask);
}
}
I'm assuming InputEvent.MOUSE_BUTTON1_DOWN
in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK
in mine; I'm using 1.6.
otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).
[added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?
In addition to the accepted answer (https://stackoverflow.com/a/4501084/6276704):
Since Java 1.7, if you want to compare two Objects which might be null, I recommend this function:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
Since: 1.7
git reset --hard HEAD^
Use the above command to revert merge changes.
ViewModel is the model containing fields to use in mvc View. Using ViewModel for the view has following benefits:
Here is an example how to use psql
to get a list of all sequences with their last_value
:
psql -U <username> -d <database> -t -c "SELECT 'SELECT ''' || c.relname || ''' as sequence_name, last_value FROM ' || c.relname || ';' FROM pg_class c WHERE (c.relkind = 'S')" | psql -U <username> -d <database> -t
You're changing the size of the list while iterating over it, which is probably not what you want and is the cause of your error.
Edit: As others have answered and commented, list comprehensions are better as a first choice and especially so in response to this question. I offered this as an alternative for that reason, and while not the best answer, it still solves the problem.
So on that note, you could also use filter
, which allows you to call a function to evaluate the items in the list you don't want.
Example:
>>> l = [1,2,3,0,0,1]
>>> filter(lambda x: x > 0, l)
[1, 2, 3]
Live and learn. Simple is better, except when you need things to be complex.
In my case, I have to get 2 values what are objects. I share this simple solution.
$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));
I use this so I can break out of PHP with a lot of HTML but not render it. It saves me from storing it as a string which disables IDE color-coding.
<?php
ob_start();
?>
<div>
<span>text</span>
<a href="#">link</a>
</div>
<?php
$content = ob_get_clean();
?>
Instead of:
<?php
$content = '<div>
<span>text</span>
<a href="#">link</a>
</div>';
?>
var arrLength = arr.length;
if(arrLength > maxNumber){
arr.splice( 0, arrLength - maxNumber);
}
This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.
The problem with:
arr.slice(0,5)
...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.
The problem with:
if (arr.length > 4) arr.length = 4;
...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().
<button type="button" class="btn btn-primary-outline pull-right" (click)="btnClick();"><i class="fa fa-plus"></i> Add</button>
import { Router } from '@angular/router';
btnClick= function () {
this.router.navigate(['/user']);
};
I had a package-lock.json
file from an old version of my package.json, I deleted that and then everything installed correctly.
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
decorate your model like this. can use a bootstrap date time picker I used this one. https://github.com/Eonasdan/bootstrap-datetimepicker/
I suppose you already have bundles for bootstrap css and js
Your date picker bundle entries
bundles.Add(new ScriptBundle("~/bundles/datePicker").Include(
"~/Scripts/moment.min.js",
"~/Scripts/bootstrap-datetimepicker.min.js"));
bundles.Add(new StyleBundle("~/Content/datepicker").Include(
"~/Content/bootstrap-datetimepicker.min.css"));
Render bundles on your Layout View
@Styles.Render("~/Content/datepicker")
@Scripts.Render("~/bundles/datePicker")
Your HTML in view
<div class="form-group">
@Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "lead col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.BirthDate, new { @class = "datetimepicker form-control" })
@Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
</div>
</div>
At the end of your view add this.
<script>
$(document).ready(function () {
$('.datetimepicker').datetimepicker({
format: 'lll'
});
});
</script>
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
Try to complete cmake process with following libs:
sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
I don't know why you want to do that, but try:
SELECT *
INTO NewTable
FROM OldTable
WHERE 1 = 2
It should work.
Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME
in your query for only true or false column
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var height:CGFloat = CGFloat()
if indexPath.row == 1 {
height = 150
}
else {
height = 50
}
return height
}
Non-numpy functions like math.abs()
or math.log10()
don't play nicely with numpy arrays. Just replace the line raising an error with:
m = np.log10(np.abs(x))
Apart from that the np.polyfit()
call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
SELECT d1.Short_Code
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL
I had this issue with MacOS. I had to uncheck "use download cache" under Android SDK Manager preferences. This worked. I also recreated the cache folder and set my user as the owner then check user download cache. This also worked.
These answers are all way too complicated!
The way he wrote the method is fine. The problem is where he invoked the method. He did not include parentheses after the method name, so the compiler thought he was trying to get a value from a variable instead of a method.
In Visual Basic and Delphi, those parentheses are optional, but in C#, they are required. So, to correct the last line of the original post:
Console.WriteLine("{0}", x.fullNameMethod());
In Spring, there is a rigorous way to convert a long to int
not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.
Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);
There is a difference, but subtle. Look at it this way: struct Foo
introduces a new type. The second one creates an alias called Foo (and not a new type) for an unnamed struct
type.
7.1.3 The typedef specifier
1 [...]
A name declared with the typedef specifier becomes a typedef-name. Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in Clause 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) or enum declaration does.
8 If the typedef declaration defines an unnamed class (or enum), the first typedef-name declared by the declaration to be that class type (or enum type) is used to denote the class type (or enum type) for linkage purposes only (3.5). [ Example:
typedef struct { } *ps, S; // S is the class name for linkage purposes
So, a typedef always is used as an placeholder/synonym for another type.
Another situation that is important to be aware of: The sort of default state for git is that you are working in the "master" branch. And for a lot of situations, you'll just hang out in that as your main working branch (although some people get fancy and do other things).
Anyway, that's just one branch. So a situation I might get into is:
My active branch is actually NOT the master branch. ... But I habitually do the command: git push
(and I had previously done git push origin master
, so it's a shortcut for THAT).
So I'm habitually pushing the master branch to the shared repo ... which is probably a good clean thing, in my case ...
But I have forgotten that the changes I have been working on are not yet IN the master branch !!!
So therefore everytime I try git push
, and I see "Everything up to date", I want to scream, but of course, it is not git's fault! It's mine.
So instead, I merge my branch into master, and then do push, and everything is happy again.
A free and easy to use service is provided at Webtechriser (click here to read the article) (called wipmania). This one is a JSONP service and requires plain javascript coding with HTML. It can also be used in JQuery. I modified the code a bit to change the output format and this is what I've used and found to be working: (it's the code of my HTML page)
<html>_x000D_
<body>_x000D_
<p id="loc"></p>_x000D_
_x000D_
_x000D_
<script type="text/javascript">_x000D_
var a = document.getElementById("loc");_x000D_
_x000D_
function jsonpCallback(data) { _x000D_
a.innerHTML = "Latitude: " + data.latitude + _x000D_
"<br/>Longitude: " + data.longitude + _x000D_
"<br/>Country: " + data.address.country; _x000D_
}_x000D_
</script>_x000D_
<script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"_x000D_
type="text/javascript"></script>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
PLEASE NOTE: This service gets the location of the visitor without prompting the visitor to choose whether to share their location, unlike the HTML 5 geolocation API (the code that you've written). Therefore, privacy is compromised. So, you should make judicial use of this service.
$restore = $this->createElement('submit', 'restore', array(
'label' => 'FILE_RESTORE',
'class' => 'restore btn btn-small btn-primary',
'attribs' => array(
'onClick' => 'restoreCheck();return false;'
)
));
As DigitalRoss pointed out, the trailing backslash is not necessary when the line woud end in |
. And you can put comments on a line following a |
:
cat ${MYSQLDUMP} | # Output MYSQLDUMP file
sed '1d' | # skip the top line
tr ",;" "\n" |
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' |
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' |
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' |
tr "\n" "," |
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | # hate phone numbers
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}
The below code will convert the JSON array of the format
[{"version":"70.3.0;3"},{"version":"6R_16B000I_J4;3"},{"version":"46.3.0;3"},{"version":"20.3.0;2"},{"version":"4.1.3;0"},{"version":"10.3.0;1"}]
to List of String
[70.3.0;3, 6R_16B000I_J4;3, 46.3.0;3, 20.3.0;2, 4.1.3;0, 10.3.0;1]
Code :
ObjectMapper mapper = new ObjectMapper();
ArrayNode node = (ArrayNode)mapper.readTree(dataFromDb);
data = node.findValuesAsText("version");
// "version" is the node in the JSON
and use com.fasterxml.jackson.databind.ObjectMapper
GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.
The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:
Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:
var foomodule = require('foo');
// do something with fooModule
What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...
var module = require(path); // Call RequireJS require
...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;
var moduleName = 'foo';
require([moduleName], function(fooModule){
// do something with fooModule
})
Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:
define(['dyn_modules'], function (dynModules) {
require(dynModules, function(){
// use arguments since you don't know how many modules you're getting in the callback
for (var i = 0; i < arguments.length; i++){
var mymodule = arguments[i];
// do something with mymodule...
}
});
});
EDIT: From your own answer, I see you're using underscore/lodash, so using _.values
and _.object
can simplify the looping through arguments array as above.
Assuming that your data in data.frame
called maxinozone
, you can do this
max(maxinozone[1, ], na.rm = TRUE)
This will round down correctly as well:
>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
... n = int(n / 10) * 10
... else:
... n = int((n + 10) / 10) * 10
...
>>> 50
If it really is a List<string>
you don't need LINQ, just use:
int GetItemIndex(string search)
{
return _list == null ? -1 : _list.IndexOf(search);
}
If you are looking for the item itself, try:
string GetItem(string search)
{
return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search));
}
Why is it necessary for an interface to be "declared" abstract?
It's not.
public abstract interface Interface {
\___.__/
|
'----> Neither this...
public void interfacing();
public abstract boolean interfacing(boolean really);
\___.__/
|
'----> nor this, are necessary.
}
Interfaces and their methods are implicitly abstract
and adding that modifier makes no difference.
Is there other rules that applies with an abstract interface?
No, same rules apply. The method must be implemented by any (concrete) implementing class.
If abstract is obsolete, why is it included in Java? Is there a history for abstract interface?
Interesting question. I dug up the first edition of JLS, and even there it says "This modifier is obsolete and should not be used in new Java programs".
Okay, digging even further... After hitting numerous broken links, I managed to find a copy of the original Oak 0.2 Specification (or "manual"). Quite interesting read I must say, and only 38 pages in total! :-)
Under Section 5, Interfaces, it provides the following example:
public interface Storing {
void freezeDry(Stream s) = 0;
void reconstitute(Stream s) = 0;
}
And in the margin it says
In the future, the " =0" part of declaring methods in interfaces may go away.
Assuming =0
got replaced by the abstract
keyword, I suspect that abstract
was at some point mandatory for interface methods!
Related article: Java: Abstract interfaces and abstract interface methods
L
: long i = 12345678910L;
.BTW: it doesn't have to be an upper case L, but lower case is confused with 1
many times :).
With the help of jquery it can be done as follows.
$("#color").prop('disabled', true);
You can apply little trick over this.
Change all the string to same case: either upper or lower case
For C# Code:
List searchResults = sl.FindAll(s => s.ToUpper().Contains(seachKeyword.ToUpper()));
For Java Code:
import java.util.*;
class Test
{
public static void main(String[] args)
{
String itemCheck="check";
ArrayList<String> listItem =new ArrayList<String>();
listItem.add("Check");
listItem.add("check");
listItem.add("CHeck");
listItem.add("Make");
listItem.add("CHecK");
for(String item :listItem)
{
if(item.toUpperCase().equals(itemCheck.toUpperCase()))
{
System.out.println(item);
}
}
}
}
if you want not the copies; then the best way is to use a pointer vector(or another structure that serves for the same goal). if you want the copies; use directly push_back(). you dont have any other choice.
If you were using JGraph, you should give a try to JGraphT which is designed for algorithms. One of its features is visualization using the JGraph library. It's still developed, but pretty stable. I analyzed the complexity of JGraphT algorithms some time ago. Some of them aren't the quickest, but if you're going to implement them on your own and need to display your graph, then it might be the best choice. I really liked using its API, when I quickly had to write an app that was working on graph and displaying it later.
I just found out that the following works:
https://www.youtube.com/embed/[video_id]?start=[start_at_second]&end=[end_at_second]
Note: the time must be an integer number of seconds (e.g. 119, not 1m59s).