Now, there are plenty of example of me answering questions with essays on why following validation rules are important. I've also said that sometimes you just have to be a rebel and break the rules, and document the reasons.
You can see in this example that framesets do work in HTML5 still. I had to download the code and add an HTML5 doctype at the top, however. But the frameset element was still recognized, and the desired result was achieved.
Therefore, knowing that using framesets is completely absurd, and knowing that you have to use this as dictated by your professor/teacher, you could just deal with the single validation error in the W3C validator and use both the HTML5 video element as well as the deprecated frameset element.
<!DOCTYPE html>
<html>
<head>
</head>
<!-- frameset is deprecated in html5, but it still works. -->
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="http://www.google.com" target="main">
</frameset>
</html>
Keep in mind that if it's a project for school, it's most likely not going to be something that will be around in a year or two once the browser vendors remove frameset support for HTML5 completely. Just know that you are right and just do what your teacher/professor asks just to get the grade :)
UPDATE:
The toplevel parent doc uses XHTML and the frame uses HTML5. The validator did not complain about the frameset being illegal, and it didn't complain about the video element.
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
</head>
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="video.html" target="main">
</frameset>
</html>
video.html:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="player-container">
<div class="arrow"></div>
<div class="player">
<video id="vid1" width="480" height="267"
poster="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb480.jpg"
durationHint="33" controls>
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb_trailer_iphone.m4v" />
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb400p.ogv" />
</video>
</div>
</body>
</html>
There is a plugin for Chrome, that drops that header entry (for personal use only):
The context that * is in, confuses the meaning sometimes.
// when declaring a function
int function(int*); // This function is being declared as a function that takes in an 'address' that holds a number (so int*), it's asking for a 'reference', interchangeably called 'address'. When I 'call'(use) this function later, I better give it a variable-address! So instead of var, or q, or w, or p, I give it the address of var so &var, or &q, or &w, or &p.
//even though the symbol ' * ' is typically used to mean 'dereferenced variable'(meaning: to use the value at the address of a variable)--despite it's common use, in this case, the symbol means a 'reference', again, in THIS context. (context here being the declaration of a 'prototype'.)
//when calling a function
int main(){
function(&var); // we are giving the function a 'reference', we are giving it an 'address'
}
So, in the context of declaring a type such as int or char, we would use the dereferencer ' * ' to actually mean the reference (the address), which makes it confusing if you see an error message from the compiler saying: 'expecting char*' which is asking for an address.
In that case, when the * is after a type (int, char, etc.) the compiler is expecting a variable's address. We give it this by using a reference operator, alos called the address-of operator ' & ' before a variable. Even further, in the case I just made up above, the compiler is expecting the address to hold a character value, not a number. (type char * == address of a value that has a character)
int* p;
int *a; // both are 'pointer' declarations. We are telling the compiler that we will soon give these variables an address (with &).
int c = 10; //declare and initialize a random variable
//assign the variable to a pointer, we do this so that we can modify the value of c from a different function regardless of the scope of that function (elaboration in a second)
p = c; //ERROR, we assigned a 'value' to this 'pointer'. We need to assign an 'address', a 'reference'.
p = &c; // instead of a value such as: 'q',5,'t', or 2.1 we gave the pointer an 'address', which we could actually print with printf(), and would be something like
//so
p = 0xab33d111; //the address of c, (not specifically this value for the address, it'll look like this though, with the 0x in the beggining, the computer treats these different from regular numbers)
*p = 10; // the value of c
a = &c; // I can still give c another pointer, even though it already has the pointer variable "p"
*a = 10;
a = 0xab33d111;
Think of each variable as having a position (or an index value if you are familiar with arrays) and a value. It might take some getting used-to to think of each variable having two values to it, one value being it's position, physically stored with electricity in your computer, and a value representing whatever quantity or letter(s) the programmer wants to store.
//Why it's used
int function(b){
b = b + 1; // we just want to add one to any variable that this function operates on.
}
int main(){
int c = 1; // I want this variable to be 3.
function(c);
function(c);// I call the function I made above twice, because I want c to be 3.
// this will return c as 1. Even though I called it twice.
// when you call a function it makes a copy of the variable.
// so the function that I call "function", made a copy of c, and that function is only changing the "copy" of c, so it doesn't affect the original
}
//let's redo this whole thing, and use pointers
int function(int* b){ // this time, the function is 'asking' (won't run without) for a variable that 'points' to a number-value (int). So it wants an integer pointer--an address that holds a number.
*b = *b + 1; //grab the value of the address, and add one to the value stored at that address
}
int main(){
int c = 1; //again, I want this to be three at the end of the program
int *p = &c; // on the left, I'm declaring a pointer, I'm telling the compiler that I'm about to have this letter point to an certain spot in my computer. Immediately after I used the assignment operator (the ' = ') to assign the address of c to this variable (pointer in this case) p. I do this using the address-of operator (referencer)' & '.
function(p); // not *p, because that will dereference. which would give an integer, not an integer pointer ( function wants a reference to an int called int*, we aren't going to use *p because that will give the function an int instead of an address that stores an int.
function(&c); // this is giving the same thing as above, p = the address of c, so we can pass the 'pointer' or we can pass the 'address' that the pointer(variable) is 'pointing','referencing' to. Which is &c. 0xaabbcc1122...
//now, the function is making a copy of c's address, but it doesn't matter if it's a copy or not, because it's going to point the computer to the exact same spot (hence, The Address), and it will be changed for main's version of c as well.
}
Inside each and every block, it copies the variables (if any) that are passed into (via parameters within "()"s). Within those blocks, the changes to a variable are made to a copy of that variable, the variable uses the same letters but is at a different address (from the original). By using the address "reference" of the original, we can change a variable using a block outside of main, or inside a child of main.
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
I think the question is a bit confusing.
If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied. For example, in an employee table, a row for an employee may have a column for storing manager's employee number where the manager is also an employee and hence will have a row in the table like a row of any other employee.
If you mean "can column(or set of columns) be a primary key as well as a foreign key in the same table?", the answer, in my view, is a no; it seems meaningless. However, the following definition succeeds in SQL Server!
create table t1(c1 int not null primary key foreign key references t1(c1))
But I think it is meaningless to have such a constraint unless somebody comes up with a practical example.
AmanS, in your example d_id in no circumstance can be a primary key in Employee table. A table can have only one primary key. I hope this clears your doubt. d_id is/can be a primary key only in department table.
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
ulimit -s unlimited
lets the stack grow unlimited.
This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.
I know this question had been answered years ago, but for those like me who needed to change where the debugger starts the application, change the command property under Project Properties -> Debugging.
Like others already wrote, in short:
shared project
reuse on the code (file) level, allowing for folder structure and resources as well
pcl
reuse on the assembly level
What was mostly missing from answers here for me is the info on reduced functionality available in a PCL: as an example you have limited file operations (I was missing a lot of File.IO fuctionality in a Xamarin cross-platform project).
In more detail
shared project:
+ Can use #if when targeting multiple platforms (e. g. Xamarin iOS, Android, WinPhone)
+ All framework functionality available for each target project (though has to be conditionally compiled)
o Integrates at compile time
- Slightly larger size of resulting assemblies
- Needs Visual Studio 2013 Update 2 or higher
pcl:
+ generates a shared assembly
+ usable with older versions of Visual Studio (pre-2013 Update 2)
o dynamically linked
- lmited functionality (subset of all projects it is being referenced by)
If you have the choice, I would recommend going for shared project, it is generally more flexible and more powerful. If you know your requirements in advance and a PCL can fulfill them, you might go that route as well. PCL also enforces clearer separation by not allowing you to write platform-specific code (which might not be a good choice to be put into a shared assembly in the first place).
Main focus of both is when you target multiple platforms, else you would normally use just an ordinary library/dll project.
Did encounter the same problem as I was trying to compile a maven project set to 1.7 on a windows 10 environment running JAVA = 1.8.
I resolved it by changing the java version from 1.7 to 1.8 as shown below.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
Another way (depending on your actual needs): If you want to pop the first n characters and save both the popped characters and the modified string:
s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum
KEYS pattern
Available since 1.0.0.
Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.
Returns all keys matching pattern.
Warning : This command is not recommended to use because it may ruin performance when it is executed against large databases instead of KEYS you can use SCAN or SETS.
Example of KEYS command to use :
redis> MSET firstname Jack lastname Stuntman age 35
"OK"
redis> KEYS *name*
1) "lastname"
2) "firstname"
redis> KEYS a??
1) "age"
redis> KEYS *
1) "lastname"
2) "age"
3) "firstname"
Training set: Is used for finding Nearest neighbors. Validation set: Is for finding different k which is applying to train set. Test set: Is used for finding the maximum accuracy and unseen data in future.
I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:
private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
{
return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
}
Calling it:
var entry = GetKey(dictList,"KeyValue1");
Gets the job done.
PowerShell (Core-compatible) one-liner to ease copypaste scenarios:
netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table
Output:
ProcessName State Protocol AddressLocal AddressForeign
----------- ----- -------- ------------ --------------
System LISTENING TCP [::]:8080 [::]:0
System LISTENING TCP 0.0.0.0:8080 0.0.0.0:0
Same code, developer-friendly:
$Port = 8080
# Get PID's listening to $Port, as PSObject
$PidsAtPortString = netstat -aon `
| Select-String $Port
$PidsAtPort = $PidsAtPortString `
| ForEach-Object { `
$_ -replace '\s+', ',' `
} `
| ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')
# Enrich port's list with ProcessName data
$ProcessesAtPort = $PidsAtPort `
| ForEach-Object { `
$portProcess = Get-Process `
| Where-Object Id -eq $_.PID; `
$_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
Write-Output $_;
}
# Show output
$ProcessesAtPort `
| Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Format-Table
If you want to rule out any problems with the else
part, try removing the else
and place the command on a new line. Like this:
IF EXIST D:\RPS_BACKUP\backups_temp\ goto tempexists
goto tempexistscontinue
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) DetailView.this
.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText("" + yourMessage.toString());
Toast.makeText(AppCstVar.getAppContext(),
"" + getResources().getString(R.string.txt_copiedtoclipboard),
Toast.LENGTH_SHORT).show();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) DetailView.this
.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("message", "" + yourMessage.toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(AppCstVar.getAppContext(),
"" + getResources().getString(R.string.txt_copiedtoclipboard),
Toast.LENGTH_SHORT).show();
}
Hope this will help to someone. Works fine in Angular 6 with reactive forms. Can operate by keyboard too.
dropdown.component.html
<div class="dropdown-wrapper {{className}} {{isFocused ? 'focus':''}}" [ngClass]="{'is-open':isOpen, 'disabled':isReadOnly}" *ngIf="options" (contextmenu)="$event.stopPropagation();">
<div class="box" (click)="toggle($event)">
<ng-container>
<div class="dropdown-selected" *ngIf="isSelectedValue" l10nTranslate><span>{{options[selected]}}</span></div>
<div class="dropdown-selected" *ngIf="!isSelectedValue" l10nTranslate><span>{{placeholder}}</span></div>
</ng-container>
</div>
<ul class="dropdown-options" *ngIf="options">
<li *ngIf="placeholder" (click)="$event.stopPropagation()">{{placeholder}}</li>
<ng-container>
<li id="li{{i}}"
*ngFor="let option of options; let i = index"
[class.active]="selected === i"
(click)="optionSelect(option, i, $event)"
l10nTranslate
>
{{option}}
</li>
</ng-container>
</ul>
</div>
dropdown.component.scss
@import "../../../assets/scss/variables";
// DROPDOWN STYLES
.dropdown-wrapper {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
border: 1px solid #DDDDDD;
border-radius: 3px;
cursor: pointer;
position: relative;
&.focus{
border: 1px solid #a8a8a8;
}
.box {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 100%;
}
// SELECTED
.dropdown-selected {
height: 30px;
position: relative;
padding: 10px 30px 10px 10px;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
width: 100%;
font-size: 12px;
color: #666666;
overflow: hidden;
background-color: #fff;
&::before {
content: "";
position: absolute;
top: 50%;
right: 5px;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
width: 22px;
height: 22px;
background: url('/assets/i/dropdown-open-selector.svg');
background-size: 22px 22px;
}
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
// DROPDOWN OPTIONS
.dropdown-options {
display: none;
position: absolute;
padding: 8px 6px 9px 5px;
max-height: 261px;
overflow-y: auto;
z-index: 999;
li {
padding: 10px 25px 10px 10px;
font-size: $regular-font-size;
color: $content-text-black;
position: relative;
line-height: 10px;
&:last-child {
border-bottom: none;
}
&:hover {
background-color: #245A88;
border-radius: 3px;
color: #fff;
border-bottom-color: transparent;
}
&:focus{
background-color: #245A88;
border-radius: 3px;
color: #fff;
}
&.active {
background-color: #245A88;
border-radius: 3px;
color: #fff;
border-bottom-color: transparent;
}
&:hover {
background-color: #7898B3
}
&.active {
font-weight: 600;
}
}
}
&.is-open {
.dropdown-selected {
&::before {
content: "";
position: absolute;
top: 50%;
right: 5px;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
width: 22px;
height: 22px;
background: url('/assets/i/dropdown-close-selector.svg');
background-size: 22px 22px;
}
}
.dropdown-options {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
width: 100%;
top: 32px;
border-radius: 3px;
background-color: #ffffff;
border: 1px solid #DDDDDD;
-webkit-box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
}
}
&.data-input-fields {
.box {
height: 35px;
}
}
&.send-email-table-select {
min-width: 140px;
border: none;
}
&.persoanal-settings {
width: 80px;
}
}
div.dropdown-wrapper.disabled
{
pointer-events: none;
background-color: #F1F1F1;
opacity: 0.7;
}
dropdown.component.ts
import { Component, OnInit, Input, Output, EventEmitter, HostListener, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DropdownComponent),
multi: true
};
@Component({
selector: 'app-dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.scss'],
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class DropdownComponent implements OnInit, ControlValueAccessor {
@Input() options: Array<string>;
@Input() selected: number;
@Input() className: string;
@Input() placeholder: string;
@Input() isReadOnly = false;
@Output() optSelect = new EventEmitter();
isOpen = false;
selectedOption;
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
isSelectedValue: boolean;
key: string;
isFocused: boolean;
/**
*Creates an instance of DropdownComponent.
* @memberof DropdownComponent
*/
ngOnInit() {
// Place default value in dropdown
if (this.selected) {
this.placeholder = '';
this.isOpen = false;
}
}
@HostListener('focus')
focusHandler() {
this.selected = 0;
this.isFocused = true;
}
@HostListener('focusout')
focusOutHandler() {
this.isFocused = false;
}
@HostListener('document:keydown', ['$event'])
keyPressHandle(event: KeyboardEvent) {
if (this.isFocused) {
this.key = event.code;
switch (this.key) {
case 'Space':
this.isOpen = true;
break;
case 'ArrowDown':
if (this.options.length - 1 > this.selected) {
this.selected = this.selected + 1;
}
break;
case 'ArrowUp':
if (this.selected > 0) {
this.selected = this.selected - 1;
}
break;
case 'Enter':
if (this.selected > 0) {
this.isSelectedValue = true;
this.isOpen = false;
this.onChangeCallback(this.selected);
this.optSelect.emit(this.options[this.selected]);
}
break;
}
}
}
/**
* option selection
* @param {string} selectedOption - text
* @param {number} idx - current index of item
* @param {any} event - object
*/
optionSelect(selectedOption: string, idx, e: any) {
e.stopPropagation();
this.selected = idx;
this.isSelectedValue = true;
// this.placeholder = '';
this.isOpen = false;
this.onChangeCallback(this.selected);
this.optSelect.emit(selectedOption);
}
/**
* toggle the dropdown
* @param {any} event object
*/
toggle(e: any) {
e.stopPropagation();
// close all previously opened dropdowns, before open
const allElems = document.querySelectorAll('.dropdown-wrapper');
for (let i = 0; i < allElems.length; i++) {
allElems[i].classList.remove('is-open');
}
this.isOpen = !this.isOpen;
if (this.selected >= 0) {
document.querySelector('#li' + this.selected).scrollIntoView(true);
}
}
/**
* dropdown click on outside
*/
@HostListener('document: click', ['$event'])
onClick() {
this.isOpen = false;
}
/**
* Method implemented from ControlValueAccessor and set default selected value
* @param {*} obj
* @memberof DropdownComponent
*/
writeValue(obj: any): void {
if (obj && obj !== '') {
this.isSelectedValue = true;
this.selected = obj;
} else {
this.isSelectedValue = false;
}
}
// From ControlValueAccessor interface
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
// From ControlValueAccessor interface
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
setDisabledState?(isDisabled: boolean): void {
}
}
Usage
<app-dropdown formControlName="type" [options]="types" [placeholder]="captureData.type" [isReadOnly]="isReadOnly">
</app-dropdown>
Options must bind an array as follows. It can change based on the requirement.
types= [
{
"id": "1",
"value": "Type 1"
},
{
"id": "2",
"value": "Type 2"
},
{
"id": "3",
"value": "Type 3"
}]
For me it was "Prefer 32bit": clearing the checkbox allowed CLR to load Crystal Reports 64bit runtime (the only one installed).
To retrieve the entire querystring from the current URL, beginning with the ?
character, you can use
location.search
https://developer.mozilla.org/en-US/docs/DOM/window.location
Example:
// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123"
In regards to retrieving specific querystring parameters, while although classes like URLSearchParams
and URL
exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:
/**
* Accepts either a URL or querystring and returns an object associating
* each querystring parameter to its value.
*
* Returns an empty object if no querystring parameters found.
*/
function getUrlParams(urlOrQueryString) {
if ((i = urlOrQueryString.indexOf('?')) >= 0) {
const queryString = urlOrQueryString.substring(i+1);
if (queryString) {
return _mapUrlParams(queryString);
}
}
return {};
}
/**
* Helper function for `getUrlParams()`
* Builds the querystring parameter to value object map.
*
* @param queryString {string} - The full querystring, without the leading '?'.
*/
function _mapUrlParams(queryString) {
return queryString
.split('&')
.map(function(keyValueString) { return keyValueString.split('=') })
.reduce(function(urlParams, [key, value]) {
if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
urlParams[key] = parseInt(value);
} else {
urlParams[key] = decodeURI(value);
}
return urlParams;
}, {});
}
You can use the above like so:
// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }
// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }
// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') {
console.log(urlParams.parameterName);
}
This is the working code for your question.
Enjoy Coding....
<html>
<head>
<style>
.animated {
background-color: green;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;animation-duration: 10s;
-webkit-animation-fill-mode: both;animation-fill-mode: both;
}
@-webkit-keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
@keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
.fadeOut {
-webkit-animation-name: fadeOut;
animation-name: fadeOut;
}
</style>
</head>
<body>
<div id="animated-example" class="animated fadeOut"></div>
</body>
</html>
plt.plot(X,y)
function just draws the plot on the canvas. In order to view the plot, you have to specify plt.show()
after plt.plot(X,y)
. So,
import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()
do this
$('select#id').val(selectYear).select2();
Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement
switch(value)
{
case 1:
case 2:
return true;
default:
return false
}
This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype
It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.
If you're using membership you can do: Membership.GetUser()
Your code is returning the Windows account which is assigned with ASP.NET.
Additional Info Edit: You will want to include System.Web.Security
using System.Web.Security
This will do:
#include <fstream>
#include <iostream>
using std::fstream;
int main(int argc, char *argv[]) {
fstream file;
file.open("test.txt",std::ios::out);
file << fflush;
file.close();
}
If all of these rows are related and you need to alter the tabular data ... why not just wrap the entire table in a form, and change GET
to POST
(unless you know that you're not going to be sending more than the max amount of data a GET
request can send).
(That's assuming, of course, that all of the data is going to the same place.)
<form method="POST" action="your_action">
<table>
<tr>
<td><input type="text" name="r1c1" value="" /></td>
<!-- ... snip ... -->
</tr>
<!-- ... repeat as needed ... -->
</table>
</form>
CGSize maxSize = CGSizeMake(lbl.frame.size.width, CGFLOAT_MAX);
CGSize requiredSize = [lbl sizeThatFits:maxSize];
CGFloat height=requiredSize.height
FileSaver.js should be able to help you here.
var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
Your error's occurring due to something like this:
>>> None + "hello world"
>>>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Python's None object is roughly equivalent to null, nil, etc. in other languages.
select myfield, CAST(myfield as varbinary(max)) ...
Yes and no.
The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()
).
Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.
You can use result.className = 'red';
, but you can also use result.classList.add('red');
. The .classList.add(str)
way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.
In Case of Arrays you can do it like this:
In .ts
file (Parent component) where you are updating your rawLapsData
do it like this:
rawLapsData = somevalue; // change detection will not happen
Solution:
rawLapsData = {...somevalue}; //change detection will happen
and ngOnChanges
will called in child component
do you mean empty or null, two different things,
if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null
Here's some examples:
decimal a = 1.994444M;
Math.Round(a, 2); //returns 1.99
decimal b = 1.995555M;
Math.Round(b, 2); //returns 2.00
You might also want to look at bankers rounding / round-to-even with the following overload:
Math.Round(a, 2, MidpointRounding.ToEven);
There's more information on it here.
queryItems.AllKeys.Contains(key)
Be aware that key may not be unique and that the comparison is usually case sensitive. If you want to just get the value of the first matching key and not bothered about case then use this:
public string GetQueryValue(string queryKey)
{
foreach (string key in QueryItems)
{
if(queryKey.Equals(key, StringComparison.OrdinalIgnoreCase))
return QueryItems.GetValues(key).First(); // There might be multiple keys of the same name, but just return the first match
}
return null;
}
It is not possible directly. You may as well write some preprocessor which can handle that.
If I understand it correctly then below are the things that can be helpful to achieve that:
Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)
If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.
Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.
JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".
Hope it helps.
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.
First, get the result of table2.
Next, unpivot it.
Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB
--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')
DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(
colName VARCHAR(255),
val VARCHAR(255)
)
INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
val
FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id
SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot
SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + '''
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL
PRINT @TSQL
result:
This may not be the answer you are looking for, but may help others whose jquery is not working properly, or working sometimes and not at other times.
This could be because your jquery has not yet loaded and you have started to interact with the page. Either put jquery on top in head (probably not a very great idea) or use a loader or spinner to stop the user from interacting with the page until the entire jquery has loaded.
newer MUI version:
<input
accept="image/*"
className={classes.input}
style={{ display: 'none' }}
id="raised-button-file"
multiple
type="file"
/>
<label htmlFor="raised-button-file">
<Button variant="raised" component="span" className={classes.button}>
Upload
</Button>
</label>
Every programming language has its own way of structuring the code.
whenever you write a block of code, it has to be organised in a way to be understood by everyone.
Usually used in conditional and classes and defining the definition.
It represents the parent, child and grandchild and further.
Example:
def example()
print "name"
print "my name"
example()
Here you can say example()
is a parent and others are children.
You can control radio button's size with css style:
style="height:35px; width:35px;"
This directly controls the radio button size.
<input type="radio" name="radio" value="value" style="height:35px; width:35px; vertical-align: middle;">
get_woocommerce_term_meta is depricated since Woo 3.6.0.
so change
$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );
into: ($value->term_id should be woo category id)
get_term_meta($value->term_id, 'thumbnail_id', true)
see docs for details: https://docs.woocommerce.com/wc-apidocs/function-get_woocommerce_term_meta.html
According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.
You can get around this limit with the deprecated syntax: ORDER BY 1 DESC
This syntax is not deprecated at all, it's E121-03 from SQL99.
You could use Jquery indeed or plain good old javascript:
var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";
You put this in a function that you call on a setTimeout until the desired opacity is reached
function extend(o, o1, o2){_x000D_
if( !(o instanceof Object) ) o = {};_x000D_
_x000D_
copy(o, o1);_x000D_
if( o2 )_x000D_
copy(o, o2)_x000D_
_x000D_
function isObject(obj) {_x000D_
var type = Object.prototype.toString.call(obj);_x000D_
return obj === Object(obj) && type != '[object Array]' && type != '[object Function]';_x000D_
};_x000D_
_x000D_
function copy(a,b){_x000D_
// copy o2 to o_x000D_
for( var key in b )_x000D_
if( b.hasOwnProperty(key) ){_x000D_
if( isObject(b[key]) ){_x000D_
if( !isObject(a[key]) )_x000D_
a[key] = Object.assign({}, b[key]); _x000D_
else copy(a[key], b[key])_x000D_
}_x000D_
else_x000D_
a[key] = b[key];_x000D_
}_x000D_
}_x000D_
_x000D_
return o;_x000D_
};_x000D_
_x000D_
_x000D_
var o1 = {a:{foo:1}, b:1},_x000D_
o2 = {a:{bar:2}, b:[1], c:()=>{}},_x000D_
newMerged = extend({}, o1, o2);_x000D_
_x000D_
console.log( newMerged )_x000D_
console.log( o1 )_x000D_
console.log( o2 )
_x000D_
Event.preventDefault- stops browser default behaviour. Now comes what is browser default behaviour. Assume you have a anchor tag and it has got a href attribute and this anchor tag is nested inside a div tag which has got a click event. Default behaviour of anchor tag is when clicked on the anchor tag it should navigate, but what event.preventDefault does is it stops the navigation in this case. But it never stops the bubbling of event or escalation of event i.e
<div class="container">
<a href="#" class="element">Click Me!</a>
</div>
$('.container').on('click', function(e) {
console.log('container was clicked');
});
$('.element').on('click', function(e) {
e.preventDefault(); // Now link won't go anywhere
console.log('element was clicked');
});
The result will be
"element was clicked"
"container was clicked"
Now event.StopPropation it stops bubbling of event or escalation of event. Now with above example
$('.container').on('click', function(e) {
console.log('container was clicked');
});
$('.element').on('click', function(e) {
e.preventDefault(); // Now link won't go anywhere
e.stopPropagation(); // Now the event won't bubble up
console.log('element was clicked');
});
Result will be
"element was clicked"
For more info refer this link https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/
This will work. It is a function that returns true, false, or possibly null.
const isObject = obj => obj && obj.constructor && obj.constructor === Object;_x000D_
_x000D_
console.log(isObject({})); // true_x000D_
console.log(isObject([])); // false_x000D_
console.log(isObject(new Function)); // false_x000D_
console.log(isObject(new Number(123))); // false_x000D_
console.log(isObject(null)); // null
_x000D_
You may be interested in the Unicode categories "Other, Control" and possibly "Other, Format" (unfortunately the latter seems to contain both unprintable and printable characters).
In Java regular expressions you can check for them using \p{Cc}
and \p{Cf}
respectively.
You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct()
you'll get an error).
Therefore you'd have to create an initialize()
function and call it in each method:
<?php
class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
My answer will focus on WHEN we can use while/for-else.
At the first glance, it seems there is no different when using
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
and
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
Because the print 'ELSE'
statement seems always executed in both cases (both when the while
loop finished or not run).
Then, it's only different when the statement print 'ELSE'
will not be executed.
It's when there is a break
inside the code block under while
In [17]: i = 0
In [18]: while i < 5:
print i
if i == 2:
break
i = i +1
else:
print 'ELSE'
print 'The next statement'
....:
0
1
2
The next statement
If differ to:
In [19]: i = 0
In [20]: while i < 5:
print i
if i == 2:
break
i = i +1
print 'ELSE'
print 'The next statement'
....:
0
1
2
ELSE
The next statement
return
is not in this category, because it does the same effect for two above cases.
exception raise also does not cause difference, because when it raises, where the next code will be executed is in exception handler (except block), the code in else
clause or right after the while
clause will not be executed.
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
There are several possibilities, what's best depends on the text you work on.
Two possibilities come to mind:
V
, S-V
,
...), select the text with cursor
movement and press d
dap
I think it's not http-proxy but proxy:
npm config set proxy="http://yourproxyhere"
You set an element's id by setting its corresponding property:
myPara.id = ID;
You mean like this?
class MyResourcePolicy : IResourcePolicy {
private string version;
public string Version {
get {
return this.version;
}
set {
this.version = value;
}
}
}
create a backup
git branch backup
reset to specified commit
git reset --soft <#root>
then add all files to staging
git add .
commit without updating the message
git commit --amend --no-edit
push new branch with squashed commits to repo
git push -f
This happened to me when I upgraded. I had to downgrade back.
react-redux ^5.0.6 ? ^7.1.3
Numbers have higher precedence than strings so of course the +
operators want to convert your strings into numbers before adding.
You could do:
print 'There are ' + CONVERT(varchar(10),@Number) +
' alias combinations did not match a record'
or use the (rather limited) formatting facilities of RAISERROR
:
RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT
Replace the dependency in the POM.xml file
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
By the dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
#include <cstdint>
#include <cstdlib>
#include <ctime>
using namespace std;
/* single precision float offers 24bit worth of linear distance from 1.0f to 0.0f */
float getval() {
/* rand() has min 16bit, but we need a 24bit random number. */
uint_least32_t r = (rand() & 0xffff) + ((rand() & 0x00ff) << 16);
/* 5.9604645E-8 is (1f - 0.99999994f), 0.99999994f is the first value less than 1f. */
return (double)r * 5.9604645E-8;
}
int main()
{
srand(time(NULL));
...
I couldn't post two answers, so here is the second solution. log2 random numbers, massive bias towards 0.0f but it's truly a random float 1.0f to 0.0f.
#include <cstdint>
#include <cstdlib>
#include <ctime>
using namespace std;
float getval () {
union UNION {
uint32_t i;
float f;
} r;
/* 3 because it's 0011, the first bit is the float's sign.
* Clearing the second bit eliminates values > 1.0f.
*/
r.i = (rand () & 0xffff) + ((rand () & 0x3fff) << 16);
return r.f;
}
int main ()
{
srand (time (NULL));
...
While the proposed solutions work, I was trying to implement with Full Calendar and it would require over 90 database calls for each view (as it loads current, previous, and next month), which, I wasn't too thrilled about.
I found an recursion library https://github.com/tplaner/When where you simply store the rules in the database and one query to pull all the relevant rules.
Hopefully this will help someone else, as I spent so many hours trying to find a good solution.
Edit: This Library is for PHP
How about this?
/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/
The default logging level is warning. Since you haven't changed the level, the root logger's level is still warning. That means that it will ignore any logging with a level that is lower than warning, including debug loggings.
This is explained in the tutorial:
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
The 'info' line doesn't print anything, because the level is higher than info.
To change the level, just set it in the root logger:
'root':{'handlers':('console', 'file'), 'level':'DEBUG'}
In other words, it's not enough to define a handler with level=DEBUG, the actual logging level must also be DEBUG in order to get it to output anything.
In Swift 2.0, the minElement
and maxElement
become methods of SequenceType
protocol, you should call them like:
let a = [1, 2, 3]
print(a.maxElement()) //3
print(a.minElement()) //1
Using maxElement
as a function like maxElement(a)
is unavailable now.
The syntax of Swift is in flux, so I can just confirm this in Xcode version7 beta6.
It may be modified in the future, so I suggest that you'd better check the doc before you use these methods.
define VERSION variable and import version into it.
import { VERSION } from '@angular/core';
Now you can use VERSION variable in your code to print version For example,
console.log(VERSION.full);
// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
**pagename/methodname** *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
function(result)
{
}
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
{
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json",
success: function(result)
{
if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
{
CallBackFunction(result);
}
},
error: function(result)
{
alert('error occured');
alert(result.responseText);
window.location.href="FrmError.aspx?Exception="+result.responseText;
},
async: true
});
}
//page name is Default.aspx & FunPubGetTasks method
///your code behind function
[System.Web.Services.WebMethod()]
public static object FunPubGetTasks(string a, string b)
{
//return Ienumerable or array
}
If you have zgrep
you can use
zgrep -a string file.tar.gz
First, you might need to edit your system's PATH
sudo vi /etc/paths
Add 2 following lines:
/opt/local/bin
/opt/local/sbin
Reboot your terminal
Tip: if you gonna use the slack cleaner https://github.com/kfei/slack-cleaner
You will need to generate a token: https://api.slack.com/custom-integrations/legacy-tokens
IMPORTANT NOTE: This will delete all users and config.
ALERT !!
ALERT !!
I don't suggest this answer until unless you want to delete data from all of the queues, including users and configs. Just Reset it !!!
rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app
Best way to do this, just call CallingFragmentName fragment = (CallingFragmentName) viewPager .getAdapter() .instantiateItem(viewPager, viewPager.getCurrentItem()); It will re-instantiate your calling Fragment, so that it will not throw null pointer exception and call any method of that fragment.
Put them in brackets []
:
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).
That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.
Another thing to consider from Bill Karwin:
There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.
Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.
And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:
varchar(32) Lorem ipsum dolor sit amet amet.
varchar(64) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
varchar(128) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
varchar(256) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
velit metus, sit amet tristique purus condimentum eleifend. Quis
que mollis magna vel massa malesuada bibendum. Proinde tincidunt
varchar(512) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
velit metus, sit amet tristique purus condimentum eleifend. Quis
que mollis magna vel massa malesuada bibendum. Proinde tincidunt
dolor tellus, sit amet porta neque varius vitae. Seduse molestie
lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
mollis diam pretium gravida. In facilisis vitae tortor id vulput
ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
varchar(1024) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
velit metus, sit amet tristique purus condimentum eleifend. Quis
que mollis magna vel massa malesuada bibendum. Proinde tincidunt
dolor tellus, sit amet porta neque varius vitae. Seduse molestie
lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
mollis diam pretium gravida. In facilisis vitae tortor id vulput
ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
nec tristique magna, vel tincidunt diam. Maecenas elementum semi
quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
proin fermentum pretium justo, ac malesuada eros et Pellentesque
vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit
There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers:
https://github.com/ilinsky/xmlhttprequest
This JS code converts XML into easy to use JavaScript objects:
http://www.terracoder.com/index.php/xml-objectifier
The JS code above can be included in the page to meet your no external library requirement.
var symbol = "MSFT";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
// http://www.terracoder.com convert XML to JSON
var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;
// Result text is escaped XML string, convert string to XML object then convert to JSON object
json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));
alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text);
}
}
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body> ' +
'<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
'<symbol>' + symbol + '</symbol> ' +
'</GetQuote> ' +
'</soap:Body> ' +
'</soap:Envelope>';
xmlhttp.send(xml);
// ...Include Google and Terracoder JS code here...
Two other options:
JavaScript SOAP client:
http://www.guru4.net/articoli/javascript-soap-client/en/
Generate JavaScript from a WSDL:
https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript
I believe this is what you want:
table.groupby('YEARMONTH').CLIENTCODE.nunique()
Example:
In [2]: table
Out[2]:
CLIENTCODE YEARMONTH
0 1 201301
1 1 201301
2 2 201301
3 1 201302
4 2 201302
5 2 201302
6 3 201302
In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]:
YEARMONTH
201301 2
201302 3
On Visual Studio 2015 Update 3, and with Git extension updated as of today (2016-10-24), the .gitignore generated by Visual Studio is:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
[Xx]64/
[Xx]86/
[Bb]uild/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Un-comment the next line if you do not want to checkin
# your web deploy settings because they may include unencrypted
# passwords
#*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config
# Windows Store app package directory
AppPackages/
BundleArtifacts/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# LightSwitch generated files
GeneratedArtifacts/
ModelManifest.xml
# Paket dependency manager
.paket/paket.exe
# FAKE - F# Make
.fake/
NAICS.com is coming out with an API that will add all kinds of key business data including street address. This would happen on the fly as your site's forms are processed. https://www.naics.com/business-intelligence-api/
Your question quite depends on age and education of your brother, but if he is a child/teenager, I would recommend to do some GUI programming or graphic programming first (with Canvas etc.). It looks good, and you have immediate results. Algorithms are boring, and too abstract for young people (before say 15 years old).
When I started programming on ZX Spectrum (I was like 12 years old), I liked to draw various things on the screen, and it was still interesting. I didn't learn about real algorithmic techniques until I was maybe 18. Don't be mislead that such "simple" programming is a wrong start; the interest of the person learning it is the most important part of it.
So, I would look into PyKDE, PyGTK, PyQt or Python + OpenGL (there are certainly some tutorials on the net, I know of some Czech ones but that won't help you :)).
Of course, if your brother is older and has education close to mathematics, you can head directly to algorithms and such.
I've tried a lot of things to let this work on Marshmallow and Lollipop. Finally i ended up moving the saved picture to the DCIM folder (new Google Photo app scan images only if they are inside this folder apparently)
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(System.currentTimeInMillis());
File storageDir = new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/");
if (!storageDir.exists())
storageDir.mkdirs();
File image = File.createTempFile(
timeStamp, /* prefix */
".jpeg", /* suffix */
storageDir /* directory */
);
return image;
}
And then the standard code for scanning files which you can find in the Google Developers site too.
public static void addPicToGallery(Context context, String photoPath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(photoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
Please remember that this folder could not be present in every device in the world and that starting from Marshmallow (API 23), you need to request the permission to WRITE_EXTERNAL_STORAGE to the user.
Hope this would help:
-> And that serial number is UDID
Use a SharedViewModel
proposed at the official ViewModel documentation
It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of master-detail fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item. This case is never trivial as both fragments need to define some interface description, and the owner activity must bind the two together. In addition, both fragments must handle the scenario where the other fragment is not yet created or visible.
This common pain point can be addressed by using ViewModel objects. These fragments can share a ViewModel using their activity scope to handle this communication
First implement fragment-ktx to instantiate your viewmodel more easily
dependencies {
implementation "androidx.fragment:fragment-ktx:1.2.2"
}
Then, you just need to put inside the viewmodel the data you will be sharing with the other fragment
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
Then, to finish up, just instantiate your viewModel in each fragment, and set the value of selected
from the fragment you want to set the data
class MasterFragment : Fragment() {
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
itemSelector.setOnClickListener { item ->
model.select(item)
}
}
}
And then, just listen for this value at your Fragment destination
class DetailFragment : Fragment() {
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
// Update the UI
})
}
}
You can also do it in the opposite way
Continued discussion & other solutions covered at How to sort an (associative) array by value? with the best solution (for my case) being by saml (quoted below).
Arrays can only have numeric indexes. You'd need to rewrite this as either an Object, or an Array of Objects.
var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});
If you like the status.push
method, you can sort it with:
status.sort(function(a,b) {
return a.val - b.val;
});
The comment in your code is wrong. INADDR_ANY
doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.
It is a very murky distinction, and in fact generally not a property of a language itself, but rather of the program you are using to execute code in that language.
However, most languages are used primarily in one form or the other, and yes, Java is essentially always compiled, while javascript is essentially always interpreted.
To compile source code is to run a program on it that generates a binary, executable file that, when run, has the behavior defined by the source. For instance, javac compiles human-readbale .java files into machine-readable .class files.
To interpret source code is run a program on it that produces the defined behavior right away, without generating an intermediary file. For instance, when your web browser loads stackoverflow.com, it interprets a bunch of javascript (which you can look at by viewing the page source) and produces lots of the nice effects these pages have - for instance, upvoting, or the little notifier bars across the top.
A simple workaround:
If a container has only one top level child, then you can specify alignment property for the child and give it any available value. it'll fill all the space in the container.
Container(color:Colors.white,height:200.0,width:200.0,
child:Container(
color: Colors.yellow,
alignment:Alignment.[any_available_option] // make the yellow child match the parent size
)
)
Another way:
Container(color:Colors.white,height:200.0,width:200.0,
child:Container(
color: Colors.yellow,
constraints: BoxConstraints.expand(height: 100.0), // height will be 100 dip and width will be match parent
)
)
public class Example extends JFrame {
public static final int WIDTH = 550;//Any Size
public static final int HEIGHT = 335;//Any Size
public Example(){
init();
}
private void init() {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
setSize(WIDTH, HEIGHT);
setLocation((int) (dimension.getWidth() / 2 - WIDTH / 2),
(int) (dimension.getHeight() / 2 - HEIGHT / 2));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
}
Just use memcpy.
If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.
strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.
Does this help?
from datetime import datetime
import calendar
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime
If someone has the same issue as I had - make sure that you don't install from the Ubuntu 14.04 repo onto a 12.04 machine - it gives this same error. Reinstalling from the proper repository fixed the issue.
Piece of cake:
*Anything can use an API. Some APIs have security provisions to require license keys, authentication, etc. which may prohibit complete use of the API in particular instances, but that's only because particular authentication/authorization steps fail. Any software that presents the right credentials (if required) can use the API.
**Technically, if an API is well-documented, you don't need an SDK to build your own software to use the API. But having an SDK generally makes the process much easier.
With appFuse framework, you can create an Spring MVC archetype with jpa support, etc ...
Take a look at it's quickStart guide to see how to create an archetype based on this Framework.
Foundational frameworks in AppFuse:
For example to create an appFuse light archetype :
mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes
-DarchetypeArtifactId=appfuse-light-struts-archetype -DarchetypeVersion=2.2.1
-DgroupId=com.mycompany -DartifactId=myproject
A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.
In data modelling terms, cardinality is how one table relates to another.
There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).
See Wikipedia on Cardinality (data modelling).
When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.
See Wikipedia on Cardinality (SQL statements).
A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed (if your program aborts for some reason in mid-session transaction, any uncommitted changes within are lost).
The session object registers transaction operations with session.add()
, but doesn't yet communicate them to the database until session.flush()
is called.
session.flush()
communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what session.commit()
does).
session.commit()
commits (persists) those changes to the database.
flush()
is always called as part of a call to commit()
(1).
When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds. By default, Session objects autoflush
their operations, but this can be disabled.
Hopefully this example will make this clearer:
#---
s = Session()
s.add(Foo('A')) # The Foo('A') object has been added to the session.
# It has not been committed to the database yet,
# but is returned as part of a query.
print 1, s.query(Foo).all()
s.commit()
#---
s2 = Session()
s2.autoflush = False
s2.add(Foo('B'))
print 2, s2.query(Foo).all() # The Foo('B') object is *not* returned
# as part of this query because it hasn't
# been flushed yet.
s2.flush() # Now, Foo('B') is in the same state as
# Foo('A') was above.
print 3, s2.query(Foo).all()
s2.rollback() # Foo('B') has not been committed, and rolling
# back the session's transaction removes it
# from the session.
print 4, s2.query(Foo).all()
#---
Output:
1 [<Foo('A')>]
2 [<Foo('A')>]
3 [<Foo('A')>, <Foo('B')>]
4 [<Foo('A')>]
I had some good results with
SELECT alphanumeric, integer FROM sorting_test ORDER BY CAST(alphanumeric AS UNSIGNED), alphanumeric ASC
To follow up on malat's response, you can avoid losing changes by creating a patch and reapply it at a later time.
git diff --no-prefix > patch.txt
patch -p0 < patch.txt
Store your patch outside the repository folder for safety.
The answer from Matt Fear was the most effective IMHO. The following is just a PowerShell script for those in windows to only remove files from their git repo that matches their exclusion list.
# Get files matching exclusionsfrom .gitignore
# Excluding comments and empty lines
$ignoreFiles = gc .gitignore | ?{$_ -notmatch "#"} | ?{$_ -match "\S"} | % {
$ignore = "*" + $_ + "*"
(gci -r -i $ignore).FullName
}
$ignoreFiles = $ignoreFiles| ?{$_ -match "\S"}
# Remove each of these file from Git
$ignoreFiles | % { git rm $_}
git add .
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/>
simply factories a java.util.Properties instance that you can inject.
In Spring 3.1 (not 3.0...) you can do something like this:
@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration {
@Autowired Environment environment;
@Bean public javax.sql.DataSource dataSource( ){
String user = this.environment.getProperty("ds.user");
...
}
}
In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:
@Value("${ds.user}") private String user;
If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:
@Configuration
public class MySpring3Configuration {
@Bean
public static PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer ppc = ...
ppc.setLocations(...);
return ppc;
}
@Bean
public class DataSource dataSource(
@Value("${ds.user}") String user,
@Value("${ds.pw}") String pw,
...) {
DataSource ds = ...
ds.setUser(user);
ds.setPassword(pw);
...
return ds;
}
}
Note that the PPC is defined using a static
bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor
- it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.
An alternative approach:
If
then
Example:
Instead of
# This comment
# is too long
use
Description: >
This comment
is too long
or
Comment: >
This comment is also too long
and newlines survive from parsing!
More advantages:
I had the same problem, so I wrote this my self. This solution is differentiated from other answers because it can deserialize in to multiple levels.
Just send JSON string in to deserializeToDictionary function it will return non strongly-typed Dictionary<string, object>
object.
Old code
private Dictionary<string, object> deserializeToDictionary(string jo)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
// if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
if (d.Value is JObject)
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
Ex: This will return Dictionary<string, object>
object of a Facebook JSON response.
Test
private void button1_Click(object sender, EventArgs e)
{
string responsestring = "{\"id\":\"721055828\",\"name\":\"Dasun Sameera Weerasinghe\",\"first_name\":\"Dasun\",\"middle_name\":\"Sameera\",\"last_name\":\"Weerasinghe\",\"username\":\"dasun\",\"gender\":\"male\",\"locale\":\"en_US\", hometown: {id: \"108388329191258\", name: \"Moratuwa, Sri Lanka\",}}";
Dictionary<string, object> values = deserializeToDictionary(responsestring);
}
Note: hometown further deserilize into a
Dictionary<string, object>
object.
Update
My old answer works great if there is no array on JSON string. This one further deserialize in to a List<object>
if an element is an array.
Just send a JSON string in to deserializeToDictionaryOrList function it will return non strongly-typed Dictionary<string, object>
object or List<object>
.
private static object deserializeToDictionaryOrList(string jo,bool isArray=false)
{
if (!isArray)
{
isArray = jo.Substring(0, 1) == "[";
}
if (!isArray)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value is JObject)
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else if (d.Value is JArray)
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString(), true));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}else
{
var values = JsonConvert.DeserializeObject<List<object>>(jo);
var values2 = new List<object>();
foreach (var d in values)
{
if (d is JObject)
{
values2.Add(deserializeToDictionary(d.ToString()));
}
else if (d is JArray)
{
values2.Add(deserializeToDictionary(d.ToString(), true));
}
else
{
values2.Add(d);
}
}
return values2;
}
}
There's an overload of String.Split for this:
"THExxQUICKxxBROWNxxFOX".Split(new [] {"xx"}, StringSplitOptions.None);
It's a custom html attribute but probably in this case is used by the Facebook React JS Library.
Take a look: http://facebook.github.io/react/
I am calling myScript1.ps1 from myScript2.ps1 .
Assuming both of the script are at the same location, first get the location of the script by using this command :
$PSScriptRoot
And, then, append the script name you want to call like this :
& "$PSScriptRoot\myScript1.ps1"
This should work.
/revive
ES6 Version using Class-y syntactic sugar
(slightly-modified: added start())
class Timer {_x000D_
constructor(callback, delay) {_x000D_
this.callback = callback_x000D_
this.remainingTime = delay_x000D_
this.startTime_x000D_
this.timerId_x000D_
}_x000D_
_x000D_
pause() {_x000D_
clearTimeout(this.timerId)_x000D_
this.remainingTime -= new Date() - this.startTime_x000D_
}_x000D_
_x000D_
resume() {_x000D_
this.startTime = new Date()_x000D_
clearTimeout(this.timerId)_x000D_
this.timerId = setTimeout(this.callback, this.remainingTime)_x000D_
}_x000D_
_x000D_
start() {_x000D_
this.timerId = setTimeout(this.callback, this.remainingTime)_x000D_
}_x000D_
}_x000D_
_x000D_
// supporting code_x000D_
const pauseButton = document.getElementById('timer-pause')_x000D_
const resumeButton = document.getElementById('timer-resume')_x000D_
const startButton = document.getElementById('timer-start')_x000D_
_x000D_
const timer = new Timer(() => {_x000D_
console.log('called');_x000D_
document.getElementById('change-me').classList.add('wow')_x000D_
}, 3000)_x000D_
_x000D_
pauseButton.addEventListener('click', timer.pause.bind(timer))_x000D_
resumeButton.addEventListener('click', timer.resume.bind(timer))_x000D_
startButton.addEventListener('click', timer.start.bind(timer))
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Traditional HTML Document. ZZz...</title>_x000D_
<style type="text/css">_x000D_
.wow { color: blue; font-family: Tahoma, sans-serif; font-size: 1em; }_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<h1>DOM & JavaScript</h1>_x000D_
_x000D_
<div id="change-me">I'm going to repaint my life, wait and see.</div>_x000D_
_x000D_
<button id="timer-start">Start!</button>_x000D_
<button id="timer-pause">Pause!</button>_x000D_
<button id="timer-resume">Resume!</button>_x000D_
</body>_x000D_
</html>
_x000D_
@Html.TextBoxFor(model => model.IssueDate, new { @class = "form-control", name = "inv_issue_date", id = "inv_issue_date", title = "Select Invoice Issue Date", placeholder = "dd/mm/yyyy", style = "text-align:center;" })
def random_int(min, max)
rand(max - min) + min
end
This thread has a good discussion and a useful solution:
function pause( iMilliseconds )
{
var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}
Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.
Why don't you just do this:
var ssizes = myStr.Split(" \t".ToCharArray());
It seems there is a method String.ToCharArray()
in .NET 4.0!
EDIT: As VMAtm has pointed out, the method already existed in .NET 2.0!
No need to get too complicated, try this one liner:
String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
You are looking for str.rsplit()
, with a limit:
print x.rsplit('-', 1)[0]
.rsplit()
searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition()
, which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition()
is the faster method as well; if you need to split more than once you can only use str.rsplit()
.
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
Use the overflow-y: scroll
property on the element that contains the elements.
The overflow-y
property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.
Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:
<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
you can only make circle from square using border-radius.
border-radius doesn't increase or reduce heights nor widths.
Your request is to use only image tag , it is basicly not possible if tag is not a square.
If you want to use a blank image and set another in bg, it is going to be painfull , one background for each image to set.
Cropping can only be done if a wrapper is there to do so. inthat case , you have many ways to do it
I don't like it either.
So use javascript:
Public Function GetJavaScriptResult(doc as HTMLDocument, jsString As String) As String
Dim el As IHTMLElement
Dim nd As HTMLDOMTextNode
Set el = doc.createElement("INPUT")
Do
el.ID = GenerateRandomAlphaString(100)
Loop Until Document.getElementById(el.ID) Is Nothing
el.Style.display = "none"
Set nd = Document.appendChild(el)
doc.parentWindow.ExecScript "document.getElementById('" & el.ID & "').value = " & jsString
GetJavaScriptResult = Document.getElementById(el.ID).Value
Document.removeChild nd
End Function
Function GenerateRandomAlphaString(Length As Long) As String
Dim i As Long
Dim Result As String
Randomize Timer
For i = 1 To Length
Result = Result & Chr(Int(Rnd(Timer) * 26 + 65 + Round(Rnd(Timer)) * 32))
Next i
GenerateRandomAlphaString = Result
End Function
Let me know if you have any problems with this; I've changed the context from a method to a function.
By the way, what version of IE are you using? I suspect you're on < IE8. If you upgrade to IE8 I presume it'll update shdocvw.dll to ieframe.dll and you will be able to use document.querySelector/All.
Edit
Comment response which isn't really a comment: Basically the way to do this in VBA is to traverse the child nodes. The problem is you don't get the correct return types. You could fix this by making your own classes that (separately) implement IHTMLElement and IHTMLElementCollection; but that's WAY too much of a pain for me to do it without getting paid :). If you're determined, go and read up on the Implements keyword for VB6/VBA.
Public Function getSubElementsByTagName(el As IHTMLElement, tagname As String) As Collection
Dim descendants As New Collection
Dim results As New Collection
Dim i As Long
getDescendants el, descendants
For i = 1 To descendants.Count
If descendants(i).tagname = tagname Then
results.Add descendants(i)
End If
Next i
getSubElementsByTagName = results
End Function
Public Function getDescendants(nd As IHTMLElement, ByRef descendants As Collection)
Dim i As Long
descendants.Add nd
For i = 1 To nd.Children.Length
getDescendants nd.Children.Item(i), descendants
Next i
End Function
On Windows you may try this:
Because 1
is numeric, but not integer (i.e. it's a floating point number), and 1:6000
is numeric and integer.
> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"
60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:
> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow
3.6 billion is easily representable in floating point, however:
> as.single(60000)*as.single(60000)
[1] 3.6e+09
To fix your for
code, convert to a floating point representation:
function (N)
{
for(i in as.single(1:N)) {
y <- i*i
}
}
As the other answers state, you need to select an active scheme to something that is not a simulator, i.e. a device that's connected to your mac.
If you have no device connected to the mac then selecting "Generic IOS Device" works also.
This is a pretty good source for info about Haskell and its uses:
It's compiler dependent. That said, in general using "
prioritizes headers in the current working directory over system headers. <>
usually is used for system headers. From to the specification (Section 6.10.2):
A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the
<
and>
delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read# include <h-char-sequence> new-line
with the identical contained sequence (including
>
characters, if any) from the original directive.
So on most compilers, using the ""
first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <>
starts the search with system headers.
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
By overriding Equals you're basically stating that you are the one who knows better how to compare two instances of a given type, so you're likely to be the best candidate to provide the best hash code.
This is an example of how ReSharper writes a GetHashCode() function for you:
public override int GetHashCode()
{
unchecked
{
var result = 0;
result = (result * 397) ^ m_someVar1;
result = (result * 397) ^ m_someVar2;
result = (result * 397) ^ m_someVar3;
result = (result * 397) ^ m_someVar4;
return result;
}
}
As you can see it just tries to guess a good hash code based on all the fields in the class, but since you know your object's domain or value ranges you could still provide a better one.
I solved this problem without installing any Samsung or Android SDK drivers or having to select MIDI or Image transfer options, as detailed in the many answers above spanning several years.
For me, on Windows 10, the problem was caused by the Windows 10 built-in app called Your Phone
. I only had to repair
the app in its Advanced Settings
. There might be an easier way to access the app's settings but I accessed them this way:
Your Phone
from the
listAdvanced Options
Repair
under Reset
optionsAfter this, when I reconnected and toggled USB Debugging
on my Android phone (Samsung A30), my phone prompted me for approval of the RSA key fingerprint, which allowed Chrome DevTools to finally recognize my phone.
In Swift 4:
let string:NSMutableAttributedString = {
let mutableString = NSMutableAttributedString(string: "firstsecondthird")
mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: NSRange(location: 0, length: 5))
mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green , range: NSRange(location: 5, length: 6))
mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: NSRange(location: 11, length: 5))
return mutableString
}()
print(string)
print(', '.join(names))
This, like it sounds, just takes all the elements of the list and joins them with ', '
.
In my case Product Clean and then restarting Xcode did resolve this problem...
The most fully-featured library to handle this as of 2019 seems to be natural-orderby.
const { orderBy } = require('natural-orderby')
const unordered = [
'123asd',
'19asd',
'12345asd',
'asd123',
'asd12'
]
const ordered = orderBy(unordered)
// [ '19asd',
// '123asd',
// '12345asd',
// 'asd12',
// 'asd123' ]
It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.
Surprisingly, it's also only 1.6kB when gzipped.
I think it will have a syntactic benefit, since you'll no longer be "faking" dynamically added properties by using a dictionary.
That, and interop with dynamic languages I would think.
I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):
<div class="form-group col-md-12">
<div ng-class="{'bg-info': (!transport_type)}" ng-click="transport_type=false">CARS</div>
<div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
<div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>
In python "else if" is spelled "elif".
Also, you need a colon after the elif
and the else
.
Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
If you are using @Configuation then instantiate below static bean. If not static @Configutation is instantiated very early and and the BeanPostProcessors responsible for resolving annotations like @Value, @Autowired etc, cannot act on it. Refer here
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.
For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).
Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory
import lxml.builder as lb
from lxml import etree
nstext = "new story"
story = lb.E.Asset(
lb.E.Attribute(nstext, name="Name", act="set"),
lb.E.Relation(lb.E.Asset(idref="Scope:767"),
name="Scope", act="set")
)
print 'story:\n', etree.tostring(story, pretty_print=True)
Output:
story:
<Asset>
<Attribute name="Name" act="set">new story</Attribute>
<Relation name="Scope" act="set">
<Asset idref="Scope:767"/>
</Relation>
</Asset>
If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx
... then this might work:
.mdf
and .ldf
files in your project directoryI know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)
Fiddle: https://jsfiddle.net/tqmfpwhv/1/
css based on OP information, media query at end is for med & lg view.
.vr-all {
padding:0px;
border-right:1px solid #CC0000;
}
.vr-xs {
padding:0px;
}
.vr-md {
padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
border-color: #CC0000;
border-style: solid;
border-bottom: 1px;
margin:0px;
padding:0px;
}
/* for medium and up */
@media(min-width:992px){
.vr-xs {
border-right:1px solid #CC0000;
}
}
html adjustments to OP provided code. Red border and Img links for example.
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
<h5>Rich Media Ad Production</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
<h5>Web Design & Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
<h5>Creative Design</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for for all viewports -->
<div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
<h5>Web Analytics</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
<h5>Search Engine Marketing</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
<h5>Quality Assurance</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
</div>
</div>
This is my function.
benefits :
/**
* Get real user ip
*
* Usage sample:
* GetRealUserIp();
* GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
*
* @param string $default default return value if no valid ip found
* @param int $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
*
* @return string real user ip
*/
function GetRealUserIp($default = NULL, $filter_options = 12582912) {
$HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
$HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
$HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
$REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');
$all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
foreach ($all_ips as $ip) {
if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
break;
}
return $ip?$ip:$default;
}
The big difference between Bootstrap 2 and Bootstrap 3 is that Bootstrap 3 is "mobile first".
That means the default styles are designed for mobile devices and in the case of Navbars, that means it's "collapsed" by default and "expands" when it reaches a certain minimum size.
Bootstrap 3's site actually has a "hint" as to what to do: http://getbootstrap.com/components/#navbar
Customize the collapsing point
Depending on the content in your navbar, you might need to change the point at which your navbar switches between collapsed and horizontal mode. Customize the @grid-float-breakpoint variable or add your own media query.
If you're going to re-compile your LESS, you'll find the noted LESS variable in the variables.less
file. It's currently set to "expand" @media (min-width: 768px)
which is a "small screen" (ie. a tablet) by Bootstrap 3 terms.
@grid-float-breakpoint: @screen-tablet;
If you want to keep the collapsed a little longer you can adjust it like such:
@grid-float-breakpoint: @screen-desktop;
(992px break-point)
or expand sooner
@grid-float-breakpoint: @screen-phone
(480px break-point)
If you want to have it expand later, and not deal with re-compiling the LESS, you'll have to overwrite the styles that get applied at the 768px
media query and have them return to the previous value. Then re-add them at the appropriate time.
I'm not sure if there's a better way to do it. Recompiling the Bootstrap LESS to your needs is the best (easiest) way. Otherwise, you'll have to find all the CSS media queries that affect your Navbar, overwrite them to default styles @ the 768px width and then revert them back at a higher min-width.
Recompiling the LESS will do all that magic for you just by changing the variable. Which is pretty much the point of LESS/SASS pre-compilers. =)
(note, I did look them all up, it's about 100 lines of code, which is annoy enough for me to drop the idea and just re-compile Bootstrap for a given project and avoid messing something up by accident)
I hope that helps!
Cheers!
I managed to create a simple console "hello world" with QT Creator
used creator 2.4.1 and QT 4.8.0 on windows 7
two ways to do this
Plain C++
do the following
or
QT Console
example: for QT console "hello world"
file - new file project 'project name '
other projects - QT Console Application
Targets select 'Desktop'
project management - next
code:
#include <QtCore/QCoreApplication>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<<" hello world";
return a.exec();
}
ctrl -R to run
compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)
hope this helps someone
As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...
I would rather allow users report on bad images. Image recognition development can take too much efforts and time and won't be as much as accurate as human eyes. It's much cheaper to outsource that moderation job.
Take a look at: Amazon Mechanical Turk
"The Amazon Mechanical Turk (MTurk) is one of the suite of Amazon Web Services, a crowdsourcing marketplace that enables computer programs to co-ordinate the use of human intelligence to perform tasks which computers are unable to do."
Try something like this:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
Dir.entries(folder)
example:
Dir.entries(".")
Source: http://ruby-doc.org/core/classes/Dir.html#method-c-entries
Just as a normal js object:
let myhash: IHash = {};
myhash["somestring"] = "value"; //set
let value = myhash["somestring"]; //get
There are two things you're doing with [indexer: string] : string
You can make a general dictionary with explicitly typed fields by using [key: string]: any;
e.g. age
must be number
, while name
must be a string - both are required. Any implicit field can be any type of value.
As an alternative, there is a Map
class:
let map = new Map<object, string>();
let key = new Object();
map.set(key, "value");
map.get(key); // return "value"
This allows you have any Object instance (not just number/string) as the key.
Although its relatively new so you may have to polyfill it if you target old systems.
ERBuilder can generate ER diagram from PostgreSQL databases (reverse engineer feature).
Below step to follow to generate an ER diagram:
• Click on Menu -> File -> reverse engineer
• Click on new connection
• Fill in PostgresSQL connection information
• Click on OK
• Click on next
• Select objects (tables, triggers, sequences…..) that you want to reverse engineer.
• Click on next.
You want to use DateTimeOffset class.
var date = new DateTimeOffset(2009, 9, 1, 0, 0, 0, 0, new TimeSpan(0L));
var stringDate = date.ToString("u");
sorry I missed your original formatting with the miliseconds
var stringDate = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
Like this... I used it to read Chinese characters...
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String
Do
a = reader.ReadLine
'
' Code here
'
Loop Until a Is Nothing
reader.Close()
Update August 2020
Original answer
ID3.NET implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files. There's also a NuGet package available.
You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.
If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:
var items = (from x in parameters
join y in myStrings on x.Source equals y
select x)
.ToList();
Percent encoding. Replace the hash with %23
.
if you just want any letters:
'a'*10 # gives 'aaaaaaaaaa'
if you want consecutive letters (up to 26):
''.join(['%c' % x for x in range(97, 97+10)]) # gives 'abcdefghij'
For OSX (and Linux), a simple solution is to use either os.popen or os.system and run the arp -a
command.
For example:
devices = []
for device in os.popen('arp -a'): devices.append(device)
This will give you a list of the devices on your local network.
As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.
Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.
A possible solution is to wrap the static in a proxy with an interface which can be mocked
public interface IFileProxy {
void Delete(string path);
}
public class FileProxy : IFileProxy {
public void Delete(string path) {
System.IO.File.Delete(path);
}
}
public class MyClass {
private IFileProxy _fileProxy;
public MyClass(IFileProxy fileProxy) {
_fileProxy = fileProxy;
}
public void DoSomethingAndDeleteFile(string path) {
// Do Something with file
// ...
// Delete
System.IO.File.Delete(path);
}
public void DoSomethingAndDeleteFileUsingProxy(string path) {
// Do Something with file
// ...
// Delete
_fileProxy.Delete(path);
}
}
The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)
Another possibility is to have a 'static proxy' with different implementations of the interface behind it
public static class FileServices {
static FileServices() {
Reset();
}
internal static IFileProxy FileProxy { private get; set; }
public static void Reset(){
FileProxy = new FileProxy();
}
public static void Delete(string path) {
FileProxy.Delete(path);
}
}
Our method now becomes
public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
// Do Something with file
// ...
// Delete
FileServices.Delete(path);
}
For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).
There is no built in option available with Windows. To constantly monitor logs you can use this free application BareTailPro.
For Java < 7 you can use if-else along with Exception:
try {
// common logic to handle both exceptions
} catch (Exception ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
}
else {
throw ex;
// or if you don't want to have to declare Exception use
// throw new RuntimeException(ex);
}
}
Edited and replaced Throwable with Exception.
To use BeginForm
, here's the way to use it:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
Make sure there is an namespace definition (xmlns
) for the namespace your control belong to.
xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>
Let's say you have a script script.sh
. To run it (using Git Bash), you do the following: [a] Add a "sh-bang" line on the first line (e.g. #!/bin/bash
) and then [b]:
# Use ./ (or any valid dir spec):
./script.sh
Note: chmod +x
does nothing to a script's executability on Git Bash. It won't hurt to run it, but it won't accomplish anything either.
An official answer would be from
You can also see from this lovely diagram why the branch predictor gets confused.
Each element in the original code is a random value
data[c] = std::rand() % 256;
so the predictor will change sides as the std::rand()
blow.
On the other hand, once it's sorted, the predictor will first move into a state of strongly not taken and when the values change to the high value the predictor will in three runs through change all the way from strongly not taken to strongly taken.
How to bring back “Browser mode” in IE11?
Easy way to bring back is just go to Emulation (ctrl +8)
and do change user agent string. (see attached image)
There's my solution cleaning up the unnecesary null values
DECLARE @cols AS NVARCHAR(MAX),
@maxcols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(CodigoFormaPago)
from PO_FormasPago
order by CodigoFormaPago
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @maxcols = STUFF((SELECT ',MAX(' + QUOTENAME(CodigoFormaPago) + ') as ' + QUOTENAME(CodigoFormaPago)
from PO_FormasPago
order by CodigoFormaPago
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT CodigoProducto, DenominacionProducto, ' + @maxcols + '
FROM
(
SELECT
CodigoProducto, DenominacionProducto,
' + @cols + ' from
(
SELECT
p.CodigoProducto as CodigoProducto,
p.DenominacionProducto as DenominacionProducto,
fpp.CantidadCuotas as CantidadCuotas,
fpp.IdFormaPago as IdFormaPago,
fp.CodigoFormaPago as CodigoFormaPago
FROM
PR_Producto p
LEFT JOIN PR_FormasPagoProducto fpp
ON fpp.IdProducto = p.IdProducto
LEFT JOIN PO_FormasPago fp
ON fpp.IdFormaPago = fp.IdFormaPago
) xp
pivot
(
MAX(CantidadCuotas)
for CodigoFormaPago in (' + @cols + ')
) p
) xx
GROUP BY CodigoProducto, DenominacionProducto'
t @query;
execute(@query);
For the date, you can use datetime.date.today()
or datetime.datetime.now().date()
.
For the time, you can use datetime.datetime.now().time()
.
However, why have separate fields for these in the first place? Why not use a single DateTimeField
?
You can always define helper functions on the model that return the .date()
or .time()
later if you only want one or the other.
No. Not necessarily.
If you need to place a DIV within a TD, be sure you're using the TD properly. If you don't care about tabular-data, and semantics, then you ultimately won't care about DIVs in TDs. I don't think there's a problem though - if you have to do it, you're fine.
According to the HTML Specification
A <div>
can be placed where flow content is expected1, which is the <td>
content model2.
With <button>
, you can use img tags, etc. where text is
<button type='submit'> text -- can be img etc. </button>
with <input>
type, you are limited to text
If you are going to find an index once then using "index" method is fine. However, if you are going to search your data more than once then I recommend using bisect module. Keep in mind that using bisect module data must be sorted. So you sort data once and then you can use bisect. Using bisect module on my machine is about 20 times faster than using index method.
Here is an example of code using Python 3.8 and above syntax:
import bisect
from timeit import timeit
def bisect_search(container, value):
return (
index
if (index := bisect.bisect_left(container, value)) < len(container)
and container[index] == value else -1
)
data = list(range(1000))
# value to search
value = 666
# times to test
ttt = 1000
t1 = timeit(lambda: data.index(value), number=ttt)
t2 = timeit(lambda: bisect_search(data, value), number=ttt)
print(f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")
Output:
t1=0.0400, t2=0.0020, diffs t1/t2=19.60
Android does not run X Windows, nor does it have many of the standard GNU libraries. So, since most native linux applications require one or both of these, most will not run.
In addition, even Java programs can be limited, because the version of Java that Android applications are written in is a subset of the standard Java library.
For your example, you'd add this:
interface JQuery{
printArea():void;
}
Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.
For PostgreSQL example:
UPDATE TableA AS a
SET param_from_table_a=FALSE -- param FROM TableA
FROM TableB AS b
WHERE b.id=a.param_id AND a.amount <> 0;
Another option that's pretty clean (No pun intended.):
git clean -ndX
Explanation:
$ git help clean
git-clean - Remove untracked files from the working tree
-n, --dry-run - Don't actually remove anything, just show what would be done.
-d - Remove untracked directories in addition to untracked files.
-X - Remove only files ignored by Git.
Note: This solution will not show ignored files that have already been removed.
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
By using os.system:
import os
os.system(r'"C:/Documents and Settings/flow_model/flow.exe"')
You should explore Json.Net, quite easy to use and allows Json objects to be deserialized in Dictionary directly.
example:
string json = @"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Console.WriteLine(values.Count);
// 2
Console.WriteLine(values["key1"]);
// value1
The systemd
way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|
You might be able to do something inline like
ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'
or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here
in an ExecStartPost
Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.
(May want to increase TimeoutStartSec from the default 90s as well)
I ran into the same problem and the way I was able to resolve it was add the dependency location of tools.jar
into the pom.xml
. Like so:
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.6.0_29\lib\tools.jar</systemPath>
</dependency>
Make sure you change the <systemPath>
to where ever your tools.jar file is located.
JavaScript Code
//this function is used to fire click event
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function showPdf(){
eventFire(document.getElementById('picToClick'), 'click');
}
HTML Code
<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
<button onclick="showPdf()">Click me</button>
Download and install latest stable CUDA driver (4.2) from here. On linux, nVidia-smi 295.41 gives you just what you want. use nvidia-smi
:
[root@localhost release]# nvidia-smi
Wed Sep 26 23:16:16 2012
+------------------------------------------------------+
| NVIDIA-SMI 3.295.41 Driver Version: 295.41 |
|-------------------------------+----------------------+----------------------+
| Nb. Name | Bus Id Disp. | Volatile ECC SB / DB |
| Fan Temp Power Usage /Cap | Memory Usage | GPU Util. Compute M. |
|===============================+======================+======================|
| 0. Tesla C2050 | 0000:05:00.0 On | 0 0 |
| 30% 62 C P0 N/A / N/A | 3% 70MB / 2687MB | 44% Default |
|-------------------------------+----------------------+----------------------|
| Compute processes: GPU Memory |
| GPU PID Process name Usage |
|=============================================================================|
| 0. 7336 ./align 61MB |
+-----------------------------------------------------------------------------+
EDIT: In latest NVIDIA drivers, this support is limited to Tesla Cards.
Chrome 46 and newer should be showing mixed content without any warning, just without the green lock in address bar.
Source: Simplifying the Page Security Icon in Chrome at Google Online Security Blog.
my solution was - just remove '*' character from the expression ^__^
<div ngFor="let talk in talks">
We can use Stack and push "i" into the stack every time we encounter the condition "arr[i]==value"
Check this:
static void getindex(int arr[], int value)
{
Stack<Integer>st= new Stack<Integer>();
int n= arr.length;
for(int i=n-1; i>=0 ;i--)
{
if(arr[i]==value)
{
st.push(i);
}
}
while(!st.isEmpty())
{
System.out.println(st.peek()+" ");
st.pop();
}
}
From http://www.peterbe.com/plog/uniqifiers-benchmark:
def f5(seq, idfun=None):
# order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
Yes there is:
ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.
By default, a batch file will display its command as it runs. The purpose of this first command which @echo off is to turn off this display. The command "echo off" turns off the display for the whole script, except for the "echo off" command itself. The "at" sign "@" in front makes the command apply to itself as well.
Just use a MaterialButton and the app:backgroundTint and android:textColor attributes:
<MaterialButton
app:backgroundTint="@color/my_color"
android:textColor="@android:color/white"/>
Yes, you can select the data, calculate the difference, and insert all values in the other table:
insert into #temp2 (Difference)
select previous - Present
from #TEMP1
So this is an older question, but for those still looking for an answer, the CSS property Box-Sizing is priceless here:
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box;
It means that you can set the width of the Div to a percentage, and any border you add to the div will be included within that percentage. So, for example, the following would add the 1px border to the inside of the width of the div:
div { box-sizing:border-box; width:50%; border-right:1px solid #000; }
If you'd like more info: http://css-tricks.com/box-sizing/
You need use patches.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
patches.Rectangle(
(0.1, 0.1),
0.5,
0.5,
fill=False # remove background
) )
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')
My solution is a wrapper around app.route:
def corsapp_route(path, origin=('127.0.0.1',), **options):
"""
Flask app alias with cors
:return:
"""
def inner(func):
def wrapper(*args, **kwargs):
if request.method == 'OPTIONS':
response = make_response()
response.headers.add("Access-Control-Allow-Origin", ', '.join(origin))
response.headers.add('Access-Control-Allow-Headers', ', '.join(origin))
response.headers.add('Access-Control-Allow-Methods', ', '.join(origin))
return response
else:
result = func(*args, **kwargs)
if 'Access-Control-Allow-Origin' not in result.headers:
result.headers.add("Access-Control-Allow-Origin", ', '.join(origin))
return result
wrapper.__name__ = func.__name__
if 'methods' in options:
if 'OPTIONS' in options['methods']:
return app.route(path, **options)(wrapper)
else:
options['methods'].append('OPTIONS')
return app.route(path, **options)(wrapper)
return wrapper
return inner
@corsapp_route('/', methods=['POST'], origin=['*'])
def hello_world():
...
this is the correct form:
comboBox1.Text = comboBox1.Items[0].ToString();
U r welcome
First we need to find a Button
:
Button mButton = (Button) findViewById(R.id.my_button);
After that, you must implement View.OnClickListener
and there you should find the TextView
and execute the method setText
:
mButton.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
mTextView.setText("Some Text");
}
});
Put the div in another div and set the parent div's style to position:relative;
Then on the child div set the following CSS properties: position:absolute; bottom:0;
You can use React Helmet:
import React from 'react'
import { Helmet } from 'react-helmet'
const TITLE = 'My Page Title'
class MyComponent extends React.PureComponent {
render () {
return (
<>
<Helmet>
<title>{ TITLE }</title>
</Helmet>
...
</>
)
}
}
I'm working with Nob Hill's Marketing team, I wanted to tell you I'll be happy to hear your questions, suggestion or anything else, please feel free to contact me.
We originally decided to create our tool from scratch because while there are other such products on the market, none of them do the job right. It’s quite easy to show you the differences between databases. It’s quite another to actually make one database like the other. Smooth migration, both of schema and data, has always been a challenge. Well, we have achieved it here.
We are so confident that it could provide you a smooth migration, than if it doesn’t – if the migration scripts it generates are not readable enough or won’t work for you, and we can’t fix it in five business days – you will get your own free copy!
You have to access to your class atributes.
To access to it atributes, you have to do:
person.id
person.name
where
person
is an instance of your class Person.
This can be done if the attibutes can be accessed, if not, you must use setters and getters...