Did research for this at school and as Justing already said. The specification is far from ready, so it wil probably take a while before HTML5 is being supported in editor. Though browsers are busy implementing the parts from the specification that are good enough to be used.
Best you can do is follow blogs, tutorials and other articles on the internet and experiment with developing in HTML5 yourself.
EDIT: Just found an Visual Studio 2008/2010 Plug-in here
Postgres has an inbuilt mechanism for the same, which in the same query returns the id or whatever you want the query to return. here is an example. Consider you have a table created which has 2 columns column1 and column2 and you want column1 to be returned after every insert.
# create table users_table(id serial not null primary key, name character varying);
CREATE TABLE
#insert into users_table(name) VALUES ('Jon Snow') RETURNING id;?
id
----
1
(1 row)
# insert into users_table(name) VALUES ('Arya Stark') RETURNING id;?
id
----
2
(1 row)
Or you could do this from NuGet Package Manager Console
Install-Package Microsoft.AspNet.WebApi -Version 5.0.0
And then you will be able to add the reference to System.Web.Http.WebHost 5.0
On Mac, there is no 3.7
directory or the directory 3.7
is owned by root
. So, I removed that directory, create a new directory by current user, and move it there. Then installation finishes without error.
sudo rm -rf /Library/Python/3.7
mkdir 3.7
sudo mv 3.7 /Library/Python
ll /Library/Python/
pip3 install numpy
You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:
git add a_text_file.txt
... do:
git commit -m "Initial commit."
... and those errors should go away.
I got a solution working in the end using Redemption, have a look at these questions...
My solution to find the first and last day of the current month:
def find_current_month_last_day(today: datetime) -> datetime:
if today.month == 2:
return today.replace(day=28)
if today.month in [4, 6, 9, 11]:
return today.replace(day=30)
return today.replace(day=31)
def current_month_first_and_last_days() -> tuple:
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
first_date = today.replace(day=1)
last_date = find_current_month_last_day(today)
return first_date, last_date
MySql have an application to import db from microsoft sql. Steps:
In 1.20
ALT+SHIFT+0 PC (Windows, Linux)
?+?+0 Mac
Pre-1.20
ALT+SHIFT+1 PC (Windows, Linux)
?+?+1 Mac
Changes editor split layout from horizontal to vertical
In 1.25 you can split editor into Grid
layout. Check View
=>Editor Layout
It is nicely presented in Release notes v1.25: VS Code grid editor layout
Briefly, with more detail below,
window
is the execution context and global object for that context's JavaScriptdocument
contains the DOM, initialized by parsing HTMLscreen
describes the physical display's full screenSee W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window
, and a window
has window.document
and window.screen
properties. The browser tab's window
is the global context, so document
and screen
refer to window.document
and window.screen
. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.
window
Each browser tab has its own top-level window
object. Each <iframe>
(and deprecated <frame>
) element has its own window
object too, nested within a parent window. Each of these windows gets its own separate global object. window.window
always refers to window
, but window.parent
and window.top
might refer to enclosing windows, giving access to other execution contexts. In addition to document
and screen
described below, window
properties include
setTimeout()
and setInterval()
binding event handlers to a timerlocation
giving the current URLhistory
with methods back()
and forward()
giving the tab's mutable historynavigator
describing the browser softwaredocument
Each window
object has a document
object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet
<body>
<p id="holyCow"> This is the first paragraph.</p>
</body>
the paragraph element can be referenced by any of the following:
window.holyCow
or window["holyCow"]
document.getElementById("holyCow")
document.querySelector("#holyCow")
document.body.firstChild
document.body.children[0]
screen
The window
object also has a screen
object with properties describing the physical display:
screen properties width
and height
are the full screen
screen properties availWidth
and availHeight
omit the toolbar
The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect()
method of any document
element will return an object with top
, left
, bottom
, and right
properties describing the location of the element in the viewport.
In 2018 and thenceforth we shall use [...Array(500)]
to that end.
You can make any dimension of list
list=[]
n= int(input())
for i in range(0,n) :
#num = input()
list.append(input().split())
print(list)
output:
The EASIEST way to change WITHOUT modifying the underlying data is:
as_labeller
function adding the back tick mark for each of the default values:# Necessary to put RH% into the facet labels
hum.names <- as_labeller(
c(`50` = "RH% 50", `60` = "RH% 60",`70` = "RH% 70",
`80` = "RH% 80",`90` = "RH% 90", `100` = "RH% 100"))
ggplot(dataframe, aes(x = Temperature.C, y = fit)) +
geom_line() +
facet_wrap(~Humidity.RH., nrow = 2, labeller = hum.names)
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
It sets how the database server sorts (compares pieces of text). in this case:
SQL_Latin1_General_CP1_CI_AS
breaks up into interesting parts:
latin1
makes the server treat strings using charset latin 1, basically asciiCP1
stands for Code Page 1252CI
case insensitive comparisons so 'ABC' would equal 'abc'AS
accent sensitive, so 'ü' does not equal 'u'P.S. For more detailed information be sure to read @solomon-rutzky's answer.
My way to show the copyright, That keeps on updating automatically
<p class="text-muted credit">Copyright ©
<?php
$copyYear = 2017; // Set your website start date
$curYear = date('Y'); // Keeps the second year updated
echo $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');
?>
</p>
It will output the results as
copyright @ 2017 //if $copyYear is 2017
copyright @ 2017-201x //if $copyYear is not equal to Current Year.
Lots of answers. May be this one will also help-
Intent intent = new Intent(activity, SignInActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
this.finish();
Kotlin version-
Intent(this, SignInActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}.also { startActivity(it) }
finish()
import java.io.*;
class Main
{
public static void main(String args[]) throws IOException
{
int n1,n2,n3,l;
n1=Integer.parseInt(args[0]);
n2=Integer.parseInt(args[1]);
n3=Integer.parseInt(args[2]);
if(n1>n2)
{
l=n1;
}
else
{
l=n2;
}
if(l<n3)
{
System.out.println("largest no is "+n3);
}
else
{
System.out.println("largest no is "+l);
}
}}
Consider above program, in this program I want to pass 3 no's from Command Line, to do so.
Step 1 : Right Click on Cup and Saucer icon, u'll see this window
Step 2: Click on Properties
Step 3: Click Run _> Arguments _> type three no's eg. 32 98 16 then click OK. Plz add space between two arguments. See here
Step 4: Run the Program by using F6.
My answer to this question might help, looks like it's similar to the one Diederik cooked up. You may also want to replace the call to NSLog()
with a static instance of your own custom logging class, that way you can add a priority flag for debug/warning/error messages, send messages to a file or database as well as the console, or pretty much whatever else you can think of.
#define DEBUG_MODE
#ifdef DEBUG_MODE
#define DebugLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self,
[[NSString stringWithUTF8String:__FILE__] lastPathComponent],
__LINE__,
[NSString stringWithFormat:(s),
##__VA_ARGS__] )
#else
#define DebugLog( s, ... )
#endif
So I'm myself new to React and I found a way to do it.
This solution does not require any extra packages.
In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file
1.1 create Root/.env
#.env file
REACT_APP_SECRET_NAME=secretvaluehere123
Important notes it MUST start with REACT_APP_
1.2 Access ENV variable
#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>
handleFetchData() { // access in API call
fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
.then((res) => res.json())
.then((data) => console.log(data))
}
1.3 Build Env Issue
So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.
CardView
extends FrameLayout, so it support foreground
attribute. Using foreground
attribute can also add border easily.
layout as follows:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/link_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="@drawable/bg_roundrect_ripple_light_border"
app:cardCornerRadius="23dp"
app:cardElevation="0dp">
</androidx.cardview.widget.CardView>
bg_roundrect_ripple_light_border.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/ripple_color_light">
<item>
<shape android:shape="rectangle">
<stroke
android:width="0.5dp"
android:color="#DDDDDD" />
<corners android:radius="23dp" />
</shape>
</item>
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<corners android:radius="23dp" />
<solid android:color="@color/background" />
</shape>
</item>
</ripple>
for me this works
unicode(data).encode('utf-8')
My objective is to check if the 'onEditButtonClick' is getting invoked when the user clicks the edit button and not checking just the console.log being printed.
You will need to first set up the test using the Angular TestBed
. This way you can actually grab the button and click it. What you will do is configure a module, just like you would an @NgModule
, just for the testing environment
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
describe('', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ],
declarations: [ TestComponent ],
providers: [ ]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
}));
});
Then you need to spy on the onEditButtonClick
method, click the button, and check that the method was called
it('should', async(() => {
spyOn(component, 'onEditButtonClick');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
fixture.whenStable().then(() => {
expect(component.onEditButtonClick).toHaveBeenCalled();
});
}));
Here we need to run an async
test as the button click contains asynchronous event handling, and need to wait for the event to process by calling fixture.whenStable()
It is now preferred to use fakeAsync/tick
combo as opposed to the async/whenStable
combo. The latter should be used if there is an XHR call made, as fakeAsync
does not support it. So instead of the above code, refactored, it would look like
it('should', fakeAsync(() => {
spyOn(component, 'onEditButtonClick');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
tick();
expect(component.onEditButtonClick).toHaveBeenCalled();
}));
Don't forget to import fakeAsync
and tick
.
If you're using display:table-row
etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:
<tr style="width:100%">
<td>Type</td>
<td style="float:right">Name</td>
</tr>
Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table
, thead
, tbody
, etc.)
Instead, add an outer element with display:table
, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats
with table elements. It'll cause so many headaches.
markup:
<div class="view-table">
<div class="view-row">
<div class="view-type">Type</div>
<div class="view-name">Name</div>
</div>
</div>
CSS:
.view-table
{
display:table;
width:100%;
}
.view-row,
{
display:table-row;
}
.view-row > div
{
display: table-cell;
}
.view-name
{
text-align:right;
}
Run As > Java Application
wont show up if the class that you want to run does not contain the main
method. Make sure that the class you trying to run has main
defined in it.
Simple:
st = "abcdefghij"
st = st[:-1]
There is also another way that shows how it is done with steps:
list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
This is also a way with user input:
list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
To make it take away the last word in a list:
list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)
Would the use of <caption>
be allowed?
<ul>
<caption> Title of List </caption>
<li> Item 1 </li>
<li> Item 2 </li>
</ul>
You are casting ClientID
to char* causing the function to assume its a null terinated char array, which it is not.
from cplusplus.com :
string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).
$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});
NavigationController.NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default);
NavigationController.NavigationBar.ShadowImage = new UIImage();
NavigationController.NavigationBar.Translucent = true;
Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.
See Wikipedia for more info.
In other words, use any colour from #000000 to #FFFFFF.
edit: Dear downvoters. Check the edit history for the question first.
I have come to the conclusion that this is not possible without any plugins.
Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}
Linux based Tomcat6 should have /etc/tomcat6/tomcat6.conf
# System-wide configuration file for tomcat6 services
# This will be sourced by tomcat6 and any secondary service
# Values will be overridden by service-specific configuration
# files in /etc/sysconfig
#
# Use this one to change default values for all services
# Change the service specific ones to affect only one service
# (see, for instance, /etc/sysconfig/tomcat6)
#
# Where your java installation lives
#JAVA_HOME="/usr/lib/jvm/java-1.5.0"
# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat6"
...
I had the same problem, but finally discovered that it was an issue with the way I was invoking the script from an ASP web user control. I was using ClientScript.RegisterStartupScript()
, but forgot to give the script a unique key (the second argument). With both scripts being assigned the same key, only the first box was actually being converted into a datepicker. So I decided to append the textbox's ID to the key to make it unique:
Page.ClientScript.RegisterStartupScript(this.GetType(), "DPSetup" + DPTextbox.ClientID, dpScript);
For reference, this is a Kotlin implementation of @danh32's solution:
private fun getWebviewScale (contentWidth : Int) : Int {
val dm = DisplayMetrics()
windowManager.defaultDisplay.getRealMetrics(dm)
val pixWidth = dm.widthPixels;
return (pixWidth.toFloat()/contentWidth.toFloat() * 100F)
.toInt()
}
In my case, width was determined by three images to be 300 pix so:
webview.setInitialScale(getWebviewScale(300))
It took me hours to find this post. Thanks!
Apart from adding users to docker group, to avoid typing sudo
repetitively, you can also create an alias for docker
commands like so:
alias docker-compose="sudo docker-compose"
alias docker="sudo docker"
The difference is obvious in console:
From Understanding Weak References, by Ethan Nicholas:
Weak references
A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:
WeakReference weakWidget = new WeakReference(widget);
and then elsewhere in the code you can use
weakWidget.get()
to get the actualWidget
object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) thatweakWidget.get()
suddenly starts returningnull
....
Soft references
A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are
WeakReferences
) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.
SoftReferences
aren't required to behave any differently thanWeakReferences
, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.
And Peter Kessler added in a comment:
The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.
Simple and effective solution: Instead of using the LoadXml()
method use the Load()
method
For example:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("sample.xml");
I had this problem because I changed the name of the class in a model, and it did not match the name of the file.
"Model class names use CamelCase. These are singular, and will map automatically to the plural database table name.
Model files go in app/models/#{singular_model_name}.rb."
https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e#model
I have a sample
import * as types from '../../helpers/ActionTypes';
var initialState = {
changedValues: {}
};
const quickEdit = (state = initialState, action) => {
switch (action.type) {
case types.PRODUCT_QUICKEDIT:
{
const item = action.item;
const changedValues = {
...state.changedValues,
[item.id]: item,
};
return {
...state,
loading: true,
changedValues: changedValues,
};
}
default:
{
return state;
}
}
};
export default quickEdit;
At its simplest, the difference is one of plurality:
I used to forget which one is which and end up having to look it up many times. To fix this problem, imagine rolling back as several rotations then hopefully the fact that rollback is plural will help you (and me!) remember which one is which. Backout sounds 'less plural' than rollback to me. Imagine backing out of a single parking space.
So, the mnemonic is:
I hope this helps!
For those looking for an inline example, here is one:
<audio controls style="width: 200px;">
<source src="http://somewhere.mp3" type="audio/mpeg">
</audio>
It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)
I faced the same problem, even if I was working on my home wifi connection, without any proxy requirements.
My project was created at c:\users\<>\Workspace\Project\
When I went to above location and ran
mvn clean install
I got below error:
[ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its de
endencies could not be resolved: Failed to read artifact descriptor for org.apa
he.maven.plugins:maven-clean-plugin:jar:2.5: Could not transfer artifact org.ap
che.maven.plugins:maven-clean-plugin:pom:2.5 from/to central (https://repo.mave
.apache.org/maven2)
It took me entire day to try ways and means to crack this, but the solution in my case, was damn simple.
I moved my project to non-user specific location, at E:\Workspace\Project\
This has done wonders for me!
.aar is a standard zip archive, the same one used in .jar. Just change the extension and, assuming it's not corrupt or anything, it should be fine.
If you needed to, you could extract it to your filesystem and then repackage it as a jar.
1) Rename it to .jar
2) Extract: jar xf filename.jar
3) Repackage: jar cf output.jar input-file(s)
Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests
emplace_back
shouldn't take an argument of type vector::value_type
, but instead variadic arguments that are forwarded to the constructor of the appended item.
template <class... Args> void emplace_back(Args&&... args);
It is possible to pass a value_type
which will be forwarded to the copy constructor.
Because it forwards the arguments, this means that if you don't have rvalue, this still means that the container will store a "copied" copy, not a moved copy.
std::vector<std::string> vec;
vec.emplace_back(std::string("Hello")); // moves
std::string s;
vec.emplace_back(s); //copies
But the above should be identical to what push_back
does. It is probably rather meant for use cases like:
std::vector<std::pair<std::string, std::string> > vec;
vec.emplace_back(std::string("Hello"), std::string("world"));
// should end up invoking this constructor:
//template<class U, class V> pair(U&& x, V&& y);
//without making any copies of the strings
If you delete an item from a collection, that collection has been changed and you can't continue to enumerate through it.
Instead, use a For loop, such as:
for(int i = dtPerson.Rows.Count-1; i >= 0; i--)
{
DataRow dr = dtPerson.Rows[i];
if (dr["name"] == "Joe")
dr.Delete();
}
dtPerson.AcceptChanges();
Note that you are iterating in reverse to avoid skipping a row after deleting the current index.
You can use sp_lock
(and sp_lock2
), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks
:
select
object_name(p.object_id) as TableName,
resource_type, resource_description
from
sys.dm_tran_locks l
join sys.partitions p on l.resource_associated_entity_id = p.hobt_id
If your listbox is connected to a LIST as the data source, listbox.Items.Clear() will not work.
I typically create a file named "DataAccess.cs" containing a separate class for code that uses or changes data pertaining to my form. The following is a code snippet from the DataAccess class that clears or removes all items in the list "exampleItems"
public List<ExampleItem> ClearExampleItems()
{
List<ExampleItem> exampleItems = new List<ExampleItem>();
exampleItems.Clear();
return examplelistItems;
}
ExampleItem is also in a separate class named "ExampleItem.cs"
using System;
namespace // The namespace is automatically added by Visual Studio
{
public class ExampleItem
{
public int ItemId { get; set; }
public string ItemType { get; set; }
public int ItemNumber { get; set; }
public string ItemDescription { get; set; }
public string FullExampleItem
{
get
{
return $"{ItemId} {ItemType} {ItemNumber} {ItemDescription}";
}
}
}
}
In the code for your Window Form, the following code fragments reference your listbox:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;
namespace // The namespace is automatically added by Visual Studio
{
public partial class YourFormName : Form
{
List<ExampleItem> exampleItems = new List<ExampleItem>();
public YourFormName()
{
InitializeComponent();
// Connect listbox to LIST
UpdateExampleItemsBinding();
}
private void UpdateUpdateItemsBinding()
{
ExampleItemsListBox.DataSource = exampleItems;
ExampleItemsListBox.DisplayMember = "FullExampleItem";
}
private void buttonClearListBox_Click(object sender, EventArgs e)
{
DataAccess db = new DataAccess();
exampleItems = db.ClearExampleItems();
UpdateExampleItemsBinding();
}
}
}
This solution specifically addresses a Windows Form listbox with the datasource connected to a list.
I do it in simpler way - first install jquery by npm in console: npm install jquery -S
and then in component file I just write: let $ = require('.../jquery.min.js')
and it works! Here full example from some my code:
import { Component, Input, ElementRef, OnInit } from '@angular/core';
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
@Component({
selector: 'departments-connections-graph',
templateUrl: './departmentsConnectionsGraph.template.html',
})
export class DepartmentsConnectionsGraph implements OnInit {
rootNode : any;
container: any;
constructor(rootNode: ElementRef) {
this.rootNode = rootNode;
}
ngOnInit() {
this.container = $(this.rootNode.nativeElement).find('.departments-connections-graph')[0];
console.log({ container : this.container});
...
}
}
In teplate I have for instance:
<div class="departments-connections-graph">something...</div>
EDIT
Alternatively instead of using:
let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
use
declare var $: any;
and in your index.html put:
<script src="assets/js/jquery-2.1.1.js"></script>
This will initialize jquery only once globaly - this is important for instance for use modal windows in bootstrap...
on macOS (/ OS X), if someone else is having trouble with the OS apparently leaking memory:
1) I'd add a /n after init. i.e. write( USB, "init\n", 5);
2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.
3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?
Edited to Add:
Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.
int tmp, serialLines;
cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);
cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
When you type "java -version", you see three version numbers - the java version (on mine, that's "1.6.0_07
"), the Java SE Runtime Environment version ("build 1.6.0_07-b06
"), and the HotSpot version (on mine, that's "build 10.0-b23, mixed mode"
). I suspect the "11.0" you are seeing is the HotSpot version.
Update: HotSpot is (or used to be, now they seem to use it to mean the whole VM) the just-in-time compiler that is built in to the Java Virtual Machine. God only knows why Sun gives it a separate version number.
using System.IO; //add this namespace also
string[] filePaths = Directory.GetFiles(@"c:\Maps\", "*.txt",
SearchOption.TopDirectoryOnly);
Thread.Sleep(50);
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread.Join
delete_all is a single SQL DELETE statement and nothing more. destroy_all calls destroy() on all matching results of :conditions (if you have one) which could be at least NUM_OF_RESULTS SQL statements.
If you have to do something drastic such as destroy_all() on large dataset, I would probably not do it from the app and handle it manually with care. If the dataset is small enough, you wouldn't hurt as much.
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
here you can find an implementation :
def __uniqueid__():
"""
generate unique id with length 17 to 21.
ensure uniqueness even with daylight savings events (clocks adjusted one-hour backward).
if you generate 1 million ids per second during 100 years, you will generate
2*25 (approx sec per year) * 10**6 (1 million id per sec) * 100 (years) = 5 * 10**9 unique ids.
with 17 digits (radix 16) id, you can represent 16**17 = 295147905179352825856 ids (around 2.9 * 10**20).
In fact, as we need far less than that, we agree that the format used to represent id (seed + timestamp reversed)
do not cover all numbers that could be represented with 35 digits (radix 16).
if you generate 1 million id per second with this algorithm, it will increase the seed by less than 2**12 per hour
so if a DST occurs and backward one hour, we need to ensure to generate unique id for twice times for the same period.
the seed must be at least 1 to 2**13 range. if we want to ensure uniqueness for two hours (100% contingency), we need
a seed for 1 to 2**14 range. that's what we have with this algorithm. You have to increment seed_range_bits if you
move your machine by airplane to another time zone or if you have a glucky wallet and use a computer that can generate
more than 1 million ids per second.
one word about predictability : This algorithm is absolutely NOT designed to generate unpredictable unique id.
you can add a sha-1 or sha-256 digest step at the end of this algorithm but you will loose uniqueness and enter to collision probability world.
hash algorithms ensure that for same id generated here, you will have the same hash but for two differents id (a pair of ids), it is
possible to have the same hash with a very little probability. You would certainly take an option on a bijective function that maps
35 digits (or more) number to 35 digits (or more) number based on cipher block and secret key. read paper on breaking PRNG algorithms
in order to be convinced that problems could occur as soon as you use random library :)
1 million id per second ?... on a Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz, you get :
>>> timeit.timeit(uniqueid,number=40000)
1.0114529132843018
an average of 40000 id/second
"""
mynow=datetime.now
sft=datetime.strftime
# store old datetime each time in order to check if we generate during same microsecond (glucky wallet !)
# or if daylight savings event occurs (when clocks are adjusted backward) [rarely detected at this level]
old_time=mynow() # fake init - on very speed machine it could increase your seed to seed + 1... but we have our contingency :)
# manage seed
seed_range_bits=14 # max range for seed
seed_max_value=2**seed_range_bits - 1 # seed could not exceed 2**nbbits - 1
# get random seed
seed=random.getrandbits(seed_range_bits)
current_seed=str(seed)
# producing new ids
while True:
# get current time
current_time=mynow()
if current_time <= old_time:
# previous id generated in the same microsecond or Daylight saving time event occurs (when clocks are adjusted backward)
seed = max(1,(seed + 1) % seed_max_value)
current_seed=str(seed)
# generate new id (concatenate seed and timestamp as numbers)
#newid=hex(int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])))[2:-1]
newid=int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed]))
# save current time
old_time=current_time
# return a new id
yield newid
""" you get a new id for each call of uniqueid() """
uniqueid=__uniqueid__().next
import unittest
class UniqueIdTest(unittest.TestCase):
def testGen(self):
for _ in range(3):
m=[uniqueid() for _ in range(10)]
self.assertEqual(len(m),len(set(m)),"duplicates found !")
hope it helps !
char *line = strdup("user name"); // don't do char *line = "user name"; see Note
char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " "); //sec_part points to "name"
Note: strtok
modifies the string, so don't hand it a pointer to string literal.
onCreate(Bundle)
is called when the activity first starts up. You can use it to perform one-time initialization such as creating the user interface. onCreate()
takes one parameter that is either null or some state information previously saved by the onSaveInstanceState
.
Angus Croll recently wrote an interesting blog post about this -
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
He goes through the pros and cons of the various methods then defines a new method 'toType' -
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
If you are using ubuntu
, you have to use the following steps to avoid this error(if there is no replication enabled):
vim /etc/mysql/my.cnf
bind-address = 127.0.0.1
using the # symbolUpdate
In Step 1, if you cannot find bind-address
in the my.cnf
file, look for it in /etc/mysql/mysql.conf.d/mysqld.cnf
file.
Update in case of MySQL replication enabled
Try to connect MySQL server on IP
for which MySQL server is bind in 'my.cnfinstead of
localhost or 127.0.0.1`.
There's no built-in command for it, so I usually just do something like this:
#!/bin/bash
# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {
# first revision as full text
echo
read r
svn log -r$r $url@HEAD
svn cat -r$r $url@HEAD
echo
# remaining revisions as differences to previous revision
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
Then, you can call it with:
history_of_file $1
See full gist here and live example here.
#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }
<div id="hero">
<div class="container">
<div class="row-fluid">
<script src="https://www.youtube.com/iframe_api"></script>
<center>
<div class="videoWrapper">
<div id="player"></div>
</div>
</center>
<script>
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId:'xxxxxxxxxxx',playerVars: { controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
} );
resizeHeroVideo();
}
</script>
</div>
</div>
</div>
var player = null;
$( document ).ready(function() {
resizeHeroVideo();
} );
$(window).resize(function() {
resizeHeroVideo();
});
function resizeHeroVideo() {
var content = $('#hero');
var contentH = viewportSize.getHeight();
contentH -= 158;
content.css('height',contentH);
if(player != null) {
var iframe = $('.videoWrapper iframe');
var iframeH = contentH - 150;
if (isMobile) {
iframeH = 163;
}
iframe.css('height',iframeH);
var iframeW = iframeH/9 * 16;
iframe.css('width',iframeW);
}
}
resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.
I had the same trouble. The reason is that your file name in migrations folder does not match with name of migration in your database (see migrations table). They should be the same.
You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Collection.update({
_id: parentDocumentId
}, {
$pull: {
subDocument: {
_id: SubDocumentId
}
}
});
This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.
Read more about pull here.
If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options
for your host or to put these lines in their virtual host configuration file.
This is where I found it:
C:\Users\<USER>\AppData\Local\Android\sdk\platform-tools
I had to put the complete path into the file explorer. I couldn't just click down to it because the directories are hidden.
I found this path listed in Android studio:
Tools > Android > SDK Manager > SDK Tools
Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.
The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.
Here is a good article about fluid vs. flex.
float
stores floating-point values, that is, values that have potential decimal placesint
only stores integral values, that is, whole numbersSo while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float
.
Dissecting them both a little further:
In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.
In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:
M × 2E
(There is more to it, but this should suffice for the purpose of this discussion)
The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.
Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float
is around 3.4 × 1038 whereas int
only allows values up to 2.1 × 109.
But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int
can store), that at the larger end of float
's numeric range the numbers are spaced wider apart (since there cannot be more unique float
numbers than there are unique int
numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float
of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float
is using there.
Similarly, you can also represent very small numbers (between 0 and 1) in a float
but regardless of whether the numbers are very large or very small, float
only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float
cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...
If you are using Kotlin for Android development then you can add TextChangedListener()
using this code:
myTextField.addTextChangedListener(object : TextWatcher{
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
text()
and node()
are node tests, in XPath terminology (compare).
Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child
axis is assumed by default.
There are all kinds of node tests:
node()
matches any node (the least specific node test of them all)text()
matches text nodes onlycomment()
matches comment nodes*
matches any element nodefoo
matches any element node named "foo"
processing-instruction()
matches PI nodes (they look like <?name value?>
).*
also matches attribute nodes, but only along the attribute
axis. @*
is a shorthand for attribute::*
. Attributes are not part of the child
axis, that's why a normal *
does not select them.This XML document:
<produce>
<item>apple</item>
<item>banana</item>
<item>pepper</item>
</produce>
represents the following DOM (simplified):
root node element node (name="produce") text node (value="\n ") element node (name="item") text node (value="apple") text node (value="\n ") element node (name="item") text node (value="banana") text node (value="\n ") element node (name="item") text node (value="pepper") text node (value="\n")
So with XPath:
/
selects the root node/produce
selects a child element of the root node if it has the name "produce"
(This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.) /produce/node()
selects any type of child node beneath /produce/
(i.e. all 7 children)/produce/text()
selects the 4 (!) whitespace-only text nodes/produce/item[1]
selects the first child element named "item"
/produce/item[1]/text()
selects all child text nodes (there's only one - "apple" - in this case)And so on.
So, your questions
/produce/item/text()
(3 nodes selected)//department/manager
(1 node selected)Notes
child
axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
/produce/item[1]/text()
and string(/produce/item[1])
will be the same.Probably there's something wrong with the input values for X and/or T. The function from the question works ok:
import numpy as np
from math import e
def sigmoid(X, T):
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])
print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))
Result:
[[15 16]
[ 5 10]]
[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]
[[ 0.99999969 0.99999989]
[ 0.99330715 0.9999546 ]]
Probably it's the dtype of your input arrays. Changing X to:
X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)
Gives:
Traceback (most recent call last):
File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
print sigmoid(X, T)
File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp
Same problem - easy fix for me.
To find the underlying problem I navigated to the actual swagger.json file which gave me the real error
/swagger/v1/swagger.json
The actual error displayed from this Url was
NotSupportedException: Ambiguous HTTP method for action ... Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
The point being
Actions require an explicit HttpMethod
I then decorated my controller methods with [HttpGet]
[Route("GetFlatRows")]
[HttpGet]
public IActionResult GetFlatRows()
{
Problem solved
Simple and with little changes. And also hide load more when entire list is loaded.
jsFiddle here.
$(document).ready(function () {
// Load the first 3 list items from another HTML file
//$('#myList').load('externalList.html li:lt(3)');
$('#myList li:lt(3)').show();
$('#showLess').hide();
var items = 25;
var shown = 3;
$('#loadMore').click(function () {
$('#showLess').show();
shown = $('#myList li:visible').size()+5;
if(shown< items) {$('#myList li:lt('+shown+')').show();}
else {$('#myList li:lt('+items+')').show();
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
$('#myList li').not(':lt(3)').hide();
});
});
it is varchar right? So it then doesn't matter if you use 50 or 25, better be safe and use 50, that said I believe the longest I have seen is about 19 or so. Last names are longer
I had this error, was able to overcome it by using :
patch -p1 < example.patch
I took it from here: https://www.drupal.org/node/1129120
You could add [asc] or [desc] at the end of the order by to get the earliest or latest records
For example, this will give you the latest records first
ORDER BY stamp DESC
Append the LIMIT
clause after ORDER BY
for me the fix was to add the injected class as inner class in the one annotated with @ConfigurationProperites, because I think you need @Component to inject properties.
When "waiting for lock on repository", delete the repository file: .hg/wlock
(or it may be in
).hg/store/lock
When deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true).
Code to display current date in element input or datepicker with ID="mydate"
Don't forget add reference to jquery-ui-*.js
$(document).ready(function () {
var dateNewFormat, onlyDate, today = new Date();
dateNewFormat = today.getFullYear() + '-' + (today.getMonth() + 1);
onlyDate = today.getDate();
if (onlyDate.toString().length == 2) {
dateNewFormat += '-' + onlyDate;
}
else {
dateNewFormat += '-0' + onlyDate;
}
$('#mydate').val(dateNewFormat);
});
you should give permission on your db
grant execute on (packageName or tableName) to user;
Try this :
DGV.AutoResizeColumns();
DGV.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;
Simply supplying the HTML of elements you want to add to a jQuery constructor $()
will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append()
method.
For example:
var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);
You could then populate this table programmatically, if you wished.
This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement
and then setting attributes like cellSpacing
and className
via JS.
Try finding out the details of this error in the "Build Results" view where the error is shown. On the right side of the line with the error message there is an icon with several lines. This will show you some helpful details.
This way I found out for me it was a duplicate iPhone developer certificate in my keychain - one of which had been expired. Maybe search for "iphone" in your keychain (select "All Items" category first).
If you want to create a small dots, just use icon from font awesome.
fa fa-circle
One level up, I have used:
str_replace(basename(__DIR__) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';
or for php < 5.3:
str_replace(basename(dirname(__FILE__)) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';
bool stop = false;
for (int i = 0; (i < 1000) && !stop; i++)
{
for (int j = 0; (j < 1000) && !stop; j++)
{
if (condition)
stop = true;
}
}
You can do that in this way:
ORDER BY `products`.`product_category_id` DESC ,`naam` ASC
Have a look at ORDER BY
Optimization
Changing the value of sys.stdout does change the destination of all calls to print. If you use an alternative way to change the destination of print, you will get the same result.
Your bug is somewhere else:
I found an answer to my own question raised by @mehrdad's answer below. To query the browser path from Windows in a generic way @mehrdad gives a nice short code that uses the Windows Registry, but did not include quite enough context to get it working.
import os
import winreg
import shlex
def try_find_chrome_path():
result = None
if winreg:
for subkey in ['ChromeHTML\\shell\\open\\command', 'Applications\\chrome.exe\\shell\\open\\command']:
try: result = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, subkey)
except WindowsError: pass
if result is not None:
result_split = shlex.split(result, False, True)
result = result_split[0] if result_split else None
if os.path.isfile(result):
break
result = None
else:
expected = "google-chrome" + (".exe" if os.name == 'nt' else "")
for parent in os.environ.get('PATH', '').split(os.pathsep):
path = os.path.join(parent, expected)
if os.path.isfile(path):
result = path
break
return result
print(try_find_chrome_path())
Thanks for the answer @mehrdad !!
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
It's probably a permissions issue but you need to make sure to try these steps to troubleshoot:
sa
and add the net use
and net use /delete
commands before and afterRemember to undo any changes (especially running as sa
). If nothing else works, you can try to change the bulk load into a scheduled task, running on the database server or another server that has bcp installed.
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
-The tag is Empty and it contains Attribute only. -The tag does not have 'Closing' tag.
So,
<img src='stackoverflow.png'>
<img src='stackoverflow.png' />
both are correct in HTML5 also.
I suggest sty. It's similar to colorama, but less verbose and it supports 8bit and 24bit colors. You can also extend the color register with your own colors.
Examples:
from sty import fg, bg, ef, rs
foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs
# Add custom colors:
from sty import Style, RgbFg
fg.orange = Style(RgbFg(255, 150, 50))
buf = fg.orange + 'Yay, Im orange.' + fg.rs
print(foo, bar, baz, qux, qui, buf, sep='\n')
Demo:
I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY
You were close... after your code of
WindowState = FormWindowState.Maximized;
THEN, set the form's min/max size capacity to the value once its sized out.
MinimumSize = this.Size;
MaximumSize = this.Size;
do this:
<Text>
{ "Hi~ \n this is a test message." }
<Text/>
_x000D_
You can explicitly have a join like this:
$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');
But you need to use the namespace of the class Join from doctrine:
use Doctrine\ORM\Query\Expr\Join;
Or if you prefere like that:
$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');
Otherwise, Join class won't be detected and your script will crash...
Here the constructor of the innerJoin method:
public function innerJoin($join, $alias, $conditionType = null, $condition = null);
You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class
EDIT
Think it should be:
$qb->select('c')
->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
->where('c.username = :username')
->andWhere('p.phone = :phone');
$qb->setParameters(array(
'username' => $username,
'phone' => $phone->getPhone(),
));
Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.
Well, even the SELECT COUNT(*) FROM Table
will be fairly inefficient, especially on large tables, since SQL Server really can't do anything but do a full table scan (clustered index scan).
Sometimes, it's good enough to know an approximate number of rows from the database, and in such a case, a statement like this might suffice:
SELECT
SUM(used_page_count) * 8 AS SizeKB,
SUM(row_count) AS [RowCount],
OBJECT_NAME(OBJECT_ID) AS TableName
FROM
sys.dm_db_partition_stats
WHERE
OBJECT_ID = OBJECT_ID('YourTableNameHere')
AND (index_id = 0 OR index_id = 1)
GROUP BY
OBJECT_ID
This will inspect the dynamic management view and extract the number of rows and the table size from it, given a specific table. It does so by summing up the entries for the heap (index_id = 0) or the clustered index (index_id = 1).
It's quick, it's easy to use, but it's not guaranteed to be 100% accurate or up to date. But in many cases, this is "good enough" (and put much less burden on the server).
Maybe that would work for you, too? Of course, to use it in EF, you'd have to wrap this up in a stored proc or use a straight "Execute SQL query" call.
Marc
Try this,
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
System.out.println("Yes option");
} else {
System.out.println("No Option");
}
No, but you can provide your own counter.
The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator
to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
Here's a less broken datetime
-based solution to convert from datetime object to posix timestamp:
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return (future - datetime.datetime(1970, 1, 1)).total_seconds()
See more details at Converting datetime.date to UTC timestamp in Python.
^
matches position just before the first character of the string$
matches position just after the last character of the string.
matches a single character. Does not matter what character it is, except newline*
matches preceding match zero or more timesSo, ^.*$
means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.
Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones
and Matthew's last name is Jones
. The pattern ^Matt.*Jones$
will match Matthew's last name is Jones
. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.
Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.
Just make sure the label is associated with the input.
<fieldset>
<legend>What metasyntactic variables do you like?</legend>
<input type="checkbox" name="foo" value="bar" id="foo_bar">
<label for="foo_bar">Bar</label>
<input type="checkbox" name="foo" value="baz" id="foo_baz">
<label for="foo_baz">Baz</label>
</fieldset>
DECLARE @DATE DATETIME
SET @DATE = '2013-08-04'
SELECT DATEPART(WEEK, @DATE) -
DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,@DATE), 0))+ 1 AS WEEK_OF_MONTH
ConfirmDialog('Are you sure');_x000D_
_x000D_
function ConfirmDialog(message) {_x000D_
$('<div></div>').appendTo('body')_x000D_
.html('<div><h6>' + message + '?</h6></div>')_x000D_
.dialog({_x000D_
modal: true,_x000D_
title: 'Delete message',_x000D_
zIndex: 10000,_x000D_
autoOpen: true,_x000D_
width: 'auto',_x000D_
resizable: false,_x000D_
buttons: {_x000D_
Yes: function() {_x000D_
// $(obj).removeAttr('onclick'); _x000D_
// $(obj).parents('.Parent').remove();_x000D_
_x000D_
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');_x000D_
_x000D_
$(this).dialog("close");_x000D_
},_x000D_
No: function() {_x000D_
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');_x000D_
_x000D_
$(this).dialog("close");_x000D_
}_x000D_
},_x000D_
close: function(event, ui) {_x000D_
$(this).remove();_x000D_
}_x000D_
});_x000D_
};
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
_x000D_
Maybe you are asking for:
Character.toChars(65) // returns ['A']
More info: Character.toChars(int codePoint)
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
You may also have a look on Runtyper - a tool that performs type checking of operands in ===
(and other operations).
For your example, if you have strict comparison x === y
and x = 123, y = "123"
, it will automatically check typeof x, typeof y
and show warning in console:
Strict compare of different types: 123 (number) === "123" (string)
This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.
http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/
I know this is a late answer but still it would help someone in need of a solution. I recommend to use OnRowCommand for delete operation along with DataKeyNames, keep OnRowDeleting function to avoid exception.
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true"
AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting" OnRowCommand="Gridview1_RowCommand" DataKeyNames="ID">
Include DataKeyNames="ID" in the gridView and specify the same in link button.
<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("ID")%>'>Delete</asp:LinkButton>
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int ID = Convert.ToInt32(e.CommandArgument);
//now perform the delete operation using ID value
}
}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Leave it blank
}
If this is helpful, give me +
Try setting the height of the html element to 100% as well.
html,
body {
height: 100%;
}
Body looks to its parent (HTML) for how to scale the dynamic property, so the HTML element needs to have its height set as well.
However the content of body will probably need to change dynamically. Setting min-height to 100% will accomplish this goal.
html {
height: 100%;
}
body {
min-height: 100%;
}
Try this one:
console.log("Session: %j", session);
If the object could be converted into JSON, that will work.
grep -v
is your friend:
grep --help | grep invert
-v, --invert-match select non-matching lines
Also check out the related -L
(the complement of -l
).
-L, --files-without-match only print FILE names containing no match
I just installed Drony, is not shareware and it does no require root on cellphone with Android 3.x or above
https://play.google.com/store/apps/details?id=org.sandroproxy.drony
It intercepts the requests and are shown on a LOG
No. Mostly because it's of a rather niche need, and there are too many possible variations. (Is it "KB", "Kb" or "Ko"? Is a megabyte 1024 * 1024 bytes, or 1024 * 1000 bytes? -- yes, some places use that!)
Put them both to display:inline
.
I'm not sure what format you're looking for in your difference but here's how to do it using DateTime
$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;
Short answer: It's just not worth it.
Longer answer: It's just not worth it, even if sequential element order and optimal performance aren't required.
Long answer: It's just not worth it...
for (var property in array)
will cause array
to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for
loop.for (... in ...)
is not guaranteed to return the object properties in sequential order, as one might expect.hasOwnProperty()
and !isNaN()
checks to filter the object properties is an additional overhead causing it to perform even slower and negates the key reason for using it in the first place, i.e. because of the more concise format.For these reasons an acceptable trade-off between performance and convenience doesn't even exist. There's really no benefit unless the intent is to handle the array as an object and perform operations on the object properties of the array.
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
Try something like this:
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
As an expansion/enhancement to the brilliant addition made by @rodowi above regarding being able to overwrite a row:
process.stdout.write("Downloading " + data.length + " bytes\r");
Should you not want the terminal cursor to be located at the first character, as I saw in my code, the consider doing the following:
let dots = ''
process.stdout.write(`Loading `)
let tmrID = setInterval(() => {
dots += '.'
process.stdout.write(`\rLoading ${dots}`)
}, 1000)
setTimeout(() => {
clearInterval(tmrID)
console.log(`\rLoaded in [3500 ms]`)
}, 3500)
By placing the \r
in front of the next print statement the cursor is reset just before the replacing string overwrites the previous.
My answer is a mod of some prior answers from @JoeMills and @user.
Get a cURL
command to log into server:
Modify cURL command to be able to save session cookie after login
-H 'Cookie: <somestuff>'
curl
at beginning -c login_cookie.txt
'login_cookie.txt'
in the same folderCall a new web page using this new cookie that requires you to be logged in
curl -b login_cookie.txt <url_that_requires_log_in>
I have tried this on Ubuntu 20.04 and it works like a charm.
The way to do it without projection:
StudentsGrades.OrderBy(student => student.Name).
ThenBy(student => student.Grade);
Use the Linux split command:
split -l 20 file.txt new
Split the file "file.txt" into files beginning with the name "new" each containing 20 lines of text each.
Type man split
at the Unix prompt for more information. However you will have to first remove the header from file.txt (using the tail
command, for example) and then add it back on to each of the split files.
Here is what I use in my .NET Projects for my .gitignore
file.
[Oo]bj/
[Bb]in/
*.suo
*.user
/TestResults
*.vspscc
*.vssscc
This is pretty much an all MS approach, that uses the built in Visual Studio tester, and a project that may have some TFS bindings in there too.
span
element is display:inline;
by default you need to make it inline-block
or block
Change your CSS to be like this
span.first_title {
margin-top: 20px;
margin-left: 12px;
font-weight: bold;
font-size:24px;
color: #221461;
/*The change*/
display:inline-block; /*or display:block;*/
}
.style1 {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Works in:
In addition you can try this for an ie solution
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom:1;
Credit to this article by Chris Coyier http://css-tricks.com/perfect-full-page-background-image/
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")
the second parameter is the desired output length
"0" is the padding char
Dynamic programming problems can be solved using either bottom-up or top-down approaches.
Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.
But you can also have bottom-up and top-down approaches using recursion as shown below.
Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.
int n = 5;
fibBottomUp(1, 1, 2, n);
private int fibBottomUp(int i, int j, int count, int n) {
if (count > n) return 1;
if (count == n) return i + j;
return fibBottomUp(j, i + j, count + 1, n);
}
Top-Down: Start with the final condition and recursively get the result of its sub-problems.
int n = 5;
fibTopDown(n);
private int fibTopDown(int n) {
if (n <= 1) return 1;
return fibTopDown(n - 1) + fibTopDown(n - 2);
}
The accepted answer crashes on filenames with space. I'm at this point not sure how to update the alias command, so I'll put the improved version here:
git ls-files -z -o --exclude-standard | xargs -0 git add
You are right that greediness is an issue:
--A--Z--A--Z--
^^^^^^^^^^
A.*Z
If you want to match both A--Z
, you'd have to use A.*?Z
(the ?
makes the *
"reluctant", or lazy).
There are sometimes better ways to do this, though, e.g.
A[^Z]*+Z
This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.
In your case, the regex would be:
/(\[[^\]]++\])/
Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:
/(\[[^\]]+\])/
* Zero or more, greedy
*? Zero or more, reluctant
*+ Zero or more, possessive
+ One or more, greedy
+? One or more, reluctant
++ One or more, possessive
? Zero or one, greedy
?? Zero or one, reluctant
?+ Zero or one, possessive
Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m}
constructs.
Examples in Java:
System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!")); // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"
System.out.println("xxxxxx".replaceAll("x{3,5}", "Y")); // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"
For CentOS users,
I've got same issue on CentOS7 and setting net.ipv4.ip_forward to 1 solves the issue. Please, refer to Docker Networking Disabled: WARNING: IPv4 forwarding is disabled. Networking will not work for more details.
Here is an example that I used:
def volume(self):
return round(pi * self.radius ** 2 * self.height, 2)
def surface_area(self):
return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)
Nothing new but caching your jQuery collections will have a small perf boost
$(function() {
var $typeSelector = $('#type');
var $toggleArea = $('#row_dim');
$typeSelector.change(function(){
if ($typeSelector.val() === 'parcel') {
$toggleArea.show();
}
else {
$toggleArea.hide();
}
});
});
And in vanilla JS for super speed:
(function() {
var typeSelector = document.getElementById('type');
var toggleArea = document.getElementById('row_dim');
typeSelector.onchange = function() {
toggleArea.style.display = typeSelector.value === 'parcel'
? 'block'
: 'none';
};
});
I used them a fair bit when I was in school, but not so much since.
In theory they are useful when you want the loop body to execute once before the exit condition check. The problem is that for the few instances where I don't want the check first, typically I want the exit check in the middle of the loop body rather than at the very end. In that case, I prefer to use the well-known for (;;)
with an if (condition) exit;
somewhere in the body.
In fact, if I'm a bit shaky on the loop exit condition, sometimes I find it useful to start writing the loop as a for (;;) {}
with an exit statement where needed, and then when I'm done I can see if it can be "cleaned up" by moving initilizations, exit conditions, and/or increment code inside the for
's parentheses.
In my case it was simply an error in the web.config.
I had:
<endpoint address="http://localhost/WebService/WebOnlineService.asmx"
It should have been:
<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"
The port number (:10593) was missing from the address.
like so:
long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } };
var rowCount = arr.GetLength(0);
var colCount = arr.GetLength(1);
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < colCount; col++)
Console.Write(String.Format("{0}\t", arr[row,col]));
Console.WriteLine();
}
Thanks for your replies. I have already solved my problem. Suppose I have my pages under http://www.yoursite.com/html, the following .htaccess rules apply.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*).html\ HTTP/
RewriteRule .* http://localhost/html/%1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*)\ HTTP/
RewriteRule .* %1.html [L]
</IfModule>
Assuming you don't have extraneous whitespace:
with open('file') as f:
w, h = [int(x) for x in next(f).split()] # read first line
array = []
for line in f: # read rest of lines
array.append([int(x) for x in line.split()])
You could condense the last for loop into a nested list comprehension:
with open('file') as f:
w, h = [int(x) for x in next(f).split()]
array = [[int(x) for x in line.split()] for line in f]
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.
See the source here if you're curious, it's actually quite readable: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and Adagrad use slots too.
These variables must be initialized before you can train a model.
The normal way to initialize variables is to call tf.initialize_all_variables()
which adds ops to initialize the variables present in the graph when it is called.
(Aside: unlike its name suggests, initialize_all_variables() does not initialize anything, it only add ops that will initialize the variables when run.)
What you must do is call initialize_all_variables() after you have added the optimizer:
...build your model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables. These will include
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()
# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
sess.run(train_op)
Actually AllocConsole with SetStdHandle in a GUI application might be a safer approach. The problem with the "console hijacking" already mentioned, is that the console might not be a foreground window at all, (esp. considering the influx of new window managers in Vista/Windows 7) among other things.
This is no easy feat.
The following link is to a working demo:
Link Updated according to lanoxx's comment
http://jsfiddle.net/C8Dtf/366/
Just remember to add these:
<script type="text/javascript" charset="utf-8" src="http://datatables.net/release-datatables/media/js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="http://datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="http://datatables.net/release-datatables/extras/FixedColumns/media/js/FixedColumns.js"></script>
i don't see any other way of achieving this. Especially not by using css only.
This is a lot to go through. Hope this helps :)
There's no guarantee that SQL Server won't attempt to perform the CONVERT
to numeric(20,0)
before it runs the filter in the WHERE
clause.
And, even if it did, ISNUMERIC
isn't adequate, since it recognises £
and 1d4
as being numeric, neither of which can be converted to numeric(20,0)
.(*)
Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)
For your filter, probably use account_code not like '%[^0-9]%'
instead of ISNUMERIC
.
(*) ISNUMERIC
answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x
is a specific target datatype.
There is many good answer already posted. I'm adding few new points and summarizing it.
HashMap
and Hashtable
both are used to store data in key and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap
HashMap
is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code. HashMap
allows one null key and multiple null values. HashMap
is a new class introduced in JDK 1.2. HashMap
is fast. HashMap
as synchronized by calling this codeMap m = Collections.synchronizedMap(HashMap);
HashMap
is traversed by Iterator. HashMap
is fail-fast. HashMap
inherits AbstractMap class. Hashtable
Hashtable
is synchronized. It is thread-safe and can be shared with many threads. Hashtable
doesn't allow any null key or value. Hashtable
is a legacy class. Hashtable
is slow. Hashtable
is internally synchronized and can't be unsynchronized. Hashtable
is traversed by Enumerator and Iterator. Hashtable
is not fail-fast. Hashtable
inherits Dictionary class.Further reading What is difference between HashMap and Hashtable in Java?
Just another option, which I wrote:
Not sure if it'll help, but I've found it useful in several projects - looks like it'll do what you need.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.
The problem is insufficient memory to load context.
Try to set VM options:
-da -Xmx2048m -Xms1024m -XX:MaxPermSize=2048m
Multicast sender that broadcasts to a multicast group:
#!/usr/bin/env python
import socket
import struct
def main():
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.sendto('Hello World!', (MCAST_GRP, MCAST_PORT))
if __name__ == '__main__':
main()
Multicast receiver that reads from a multicast group and prints hex data to the console:
#!/usr/bin/env python
import socket
import binascii
def main():
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except AttributeError:
pass
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
sock.bind((MCAST_GRP, MCAST_PORT))
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))
while 1:
try:
data, addr = sock.recvfrom(1024)
except socket.error, e:
print 'Expection'
hexdata = binascii.hexlify(data)
print 'Data = %s' % hexdata
if __name__ == '__main__':
main()
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
It is not possible to change the Array Size. But you can copy the element of one array into another array by creating an Array of bigger size.
It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full
public class ResizingArrayStack1 {
private String[] s;
private int size = 0;
private int index = 0;
public void ResizingArrayStack1(int size) {
this.size = size;
s = new String[size];
}
public void push(String element) {
if (index == s.length) {
resize(2 * s.length);
}
s[index] = element;
index++;
}
private void resize(int capacity) {
String[] copy = new String[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
s = copy;
}
}
public static void main(String[] args) {
ResizingArrayStack1 rs = new ResizingArrayStack1();
rs.push("a");
rs.push("b");
rs.push("c");
rs.push("d");
}
}
Try below:
try:
raise ValueError("Original message. ")
except Exception as err:
message = 'My custom error message. '
# Change the order below to "(message + str(err),)" if custom message is needed first.
err.args = (str(err) + message,)
raise
Output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
1 try:
----> 2 raise ValueError("Original message")
3 except Exception as err:
4 message = 'My custom error message.'
5 err.args = (str(err) + ". " + message,)
ValueError: Original message. My custom error message.
TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.
If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.
As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT
header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/chainedcert.pem; # server certificate
ssl_certificate_key /path/to/key; # server key
ssl_client_certificate /path/to/ca.pem; # client CA
ssl_verify_client on;
proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;
location / {
proxy_pass http://localhost:3000;
}
}
Another java 8 lambda option :
String[] array2 = Arrays.stream(array).map(String::trim).toArray(String[]::new);
And the ugly but optimized version without new array creation
Arrays.stream(array).map(String::trim).toArray(unused -> array);
Original "array" is modified.
In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.
<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="{Binding ColorSet}"/>
</Style>
</DataGrid.RowStyle>
And in my Employee Class
public class Employee {
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string ColorSet { get; set; }
public Employee() { }
public Employee(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
if (Age > 50)
{
ColorSet = "Green";
}
else if (Age > 100)
{
ColorSet = "Red";
}
else
{
ColorSet = "White";
}
}
}
This way every Row of the DataGrid has the BackGround Color of the ColorSet
Property of my Object.
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
Atom is still in beta (v0.123 as I'm writing this) but it's moving fast. Way faster than Sublime. New builds are released on a weekly basis, sometimes even few of them in the same week. In its short life span, it had more releases than Sublime which takes months to release a new feature or a bug fix. Here's an updated take on things looking back on the path Atom has taken since the launch of the beta:
Sublime has better performance than Atom. Simply because it's written in C++. Atom on the other hand is a web based desktop app built on top of Chromium, and while they take performance close to heart, it will be really hard or even impossible to reach the same speed and responsiveness. Last July Atom began using React and it gave it a nice performance boost but you can still feel the difference. Apart from that, if Atom’s performance issues will not push users away - Sublime better speed up the release cycle, brush up its small UX tweaks, and consider letting in more contributors because this is where Atom is winning.
Atom's package ecosystem is also growing really fast, it might not be as big as Sublime's at the moment but I have a feeling that with GitHub at it's back it will keep growing even faster. It probably has the majority of IDE like plug-ins you can think of. A major difference right now is that it can't handle files bigger than 2MB so it's something to keep in mind.
The one thing you'll notice first is that the Sublime minimap is gone! Other than that, the first impression is that Atom looks almost the same as Sublime. I wrote a more in depth comparison about it in this blog post.
No easy straightforward way to port your Sublime configurations, packages and such as far as I know.
You can wrap the label around the input:
**<label for="a"><input type="checkbox" id="a">a</label>**
This worked for me.
Just an extra comment on something that is often overlooked. Sometimes not using a surrogate key has benefits in the child tables. Let's say we have a design that allows you to run multiple companies within the one database (maybe it's a hosted solution, or whatever).
Let's say we have these tables and columns:
Company:
CompanyId (primary key)
CostCenter:
CompanyId (primary key, foreign key to Company)
CostCentre (primary key)
CostElement
CompanyId (primary key, foreign key to Company)
CostElement (primary key)
Invoice:
InvoiceId (primary key)
CompanyId (primary key, in foreign key to CostCentre, in foreign key to CostElement)
CostCentre (in foreign key to CostCentre)
CostElement (in foreign key to CostElement)
In case that last bit doesn't make sense, Invoice.CompanyId
is part of two foreign keys, one to the CostCentre table and one to the CostElement table. The primary key is (InvoiceId, CompanyId).
In this model, it's not possible to screw-up and reference a CostElement from one company and a CostCentre from another company. If a surrogate key was used on the CostElement and CostCentre tables, it would be.
The fewer chances to screw up, the better.
<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div class="content">
I would like to display a loading bar before the entire page is loaded.
</div>
$(function() {
$(".preload").fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
});?
.content {display:none;}
.preload {
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
}
?
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
Sometimes you, also, need to clean this folder: C:\Windows\Temp\Temporary ASP.NET
Megabyte means 2^20 bytes. I know that technically that doesn't mesh with the SI units, and that some folks have come up with a new terminology to mean 2^20. None of that matters. Efforts to change the language to "clarify" things are doomed to failure.
Hard-drive manufacturers use it to mean 1,000,000 bytes, because that's what it means in SI so they figure technically they aren't lying (while actually they are). That falls under lies, damn lies, and marketing.
The secret event that keeps angular ngModel synchronous is the event call input. Hence the best answer to your question should be:
<input type="text" [(ngModel)]="mymodel" (input)="valuechange($event)" />
{{mymodel}}
Check out this answer on SuperUser:
In short: Reinstall both IIS and WAS.
In details -
Step 1
Go to "Add remove programs" "Turn windows features on or off" Remove both IIS and WAS (Windows Process Activation Service) Restart the PC Step 2
Go to "Add remove programs" "Turn windows features on or off" Turn on both IIS and WAS (Windows Process Activation Service) Note: Reinstalling IIS alone won't help. You have to reinstall both IIS and WAS
This approach fixed the problem for me.
Review java.lang.Thread
.
To start or restart (once a thread is stopped, you can't restart that same thread, but it doesn't matter; just create a new Thread
instance):
// Create your Runnable instance
Task task = new Task(...);
// Start a thread and run your Runnable
Thread t = new Thread(task);
To stop it, have a method on your Task
instance that sets a flag to tell the run
method to exit; returning from run
exits the thread. If your calling code needs to know the thread really has stopped before it returns, you can use join
:
// Tell Task to stop
task.setStopFlag(true);
// Wait for it to do so
t.join();
Regarding restarting: Even though a Thread
can't be restarted, you can reuse your Runnable
instance with a new thread if it has state and such you want to keep; that comes to the same thing. Just make sure your Runnable
is designed to allow multiple calls to run
.
Do you have the required permission set in your Manifest?
<uses-permission android:name="android.permission.WAKE_LOCK" />
Removing CocoaPods from a project is possible, but not currently automated by the CLI. First thing, if the only issue you have is not being able to use an xcworkspace
you can use CocoaPods with just xcodeproj
s by using the --no-integrate
flag which will produce the Pods.xcodeproj
but not a workspace. Then you can add this xcodeproj
as a subproject to your main xcodeproj
.
If you really want to remove all CocoaPods integration you need to do a few things:
NOTE editing some of these things if done incorrectly could break your main project. I strongly encourage you to check your projects into source control just in case. Also these instructions are for CocoaPods version 0.39.0
, they could change with new versions.
Podfile
Podfile.lock
and your Pods
directory)xcworkspace
xcodeproj
file, delete the references to Pods.xcconfig
and libPods.a
(in the Frameworks
group)Build Phases
delete the Copy Pods Resources
, Embed Pods Frameworks
and Check Pods Manifest.lock
phases.After those steps you should be set with a single xcodeproj
that existed before you integrated CocoaPods. If I missed anything let me know and I will edit this.
Also we're always looking for suggestions for how to improve CocoaPods so if you have an issues please submit them in our issue tracker so we can come up with a way to fix them!
EDIT
As shown by Jack Wu in the comments there is a third party CocoaPods plugin that can automate these steps for you. It can be found here. Note that it is a third party plugin and might not always be updated when CocoaPods is. Also note that it is made by a CocoaPods core team member so that problem won't be a problem.
Try this int maxAge = context.Persons.Max(p => p.Age);
And make sure you have using System.Linq;
at the top of your file
In my case, I was using a service in a sub module (NOT the root AppModule), and the HttpClientModule was imported only in the module.
So I have to modify the default scope of the service, by changing 'providedIn' to 'any' in the @Injectable decorator.
By default, if you using angular-cli to generate the service, the 'providedIn' was set to 'root'.
Hope this helps.
Try marginTop
in place of margin-top
, eg:
$("#ActionBox").css("marginTop", foo);
I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"
Apparently the differences between these date formats are as follow:
DT_DATE A date structure that consists of year, month, day, and hour.
DT_DBDATE A date structure that consists of year, month, and day.
DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction
By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.
The following solution to a struct is inspired by the namedtuple implementation and some of the previous answers. However, unlike the namedtuple it is mutable, in it's values, but like the c-style struct immutable in the names/attributes, which a normal class or dict isn't.
_class_template = """\
class {typename}:
def __init__(self, *args, **kwargs):
fields = {field_names!r}
for x in fields:
setattr(self, x, None)
for name, value in zip(fields, args):
setattr(self, name, value)
for name, value in kwargs.items():
setattr(self, name, value)
def __repr__(self):
return str(vars(self))
def __setattr__(self, name, value):
if name not in {field_names!r}:
raise KeyError("invalid name: %s" % name)
object.__setattr__(self, name, value)
"""
def struct(typename, field_names):
class_definition = _class_template.format(
typename = typename,
field_names = field_names)
namespace = dict(__name__='struct_%s' % typename)
exec(class_definition, namespace)
result = namespace[typename]
result._source = class_definition
return result
Usage:
Person = struct('Person', ['firstname','lastname'])
generic = Person()
michael = Person('Michael')
jones = Person(lastname = 'Jones')
In [168]: michael.middlename = 'ben'
Traceback (most recent call last):
File "<ipython-input-168-b31c393c0d67>", line 1, in <module>
michael.middlename = 'ben'
File "<string>", line 19, in __setattr__
KeyError: 'invalid name: middlename'
The functions with an s
take string parameters. The others take file
streams.
This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7
You may also check Unsupported major.minor version 51.0
declare @sexo as char(1)
select @sexo='F'
select * from pessoa
where isnull(Sexo,0) =isnull(@Sexo,0)
I wrote this code snippet and it works fine:
<a href="#" class="clickable">Blah</a>
<input id="textbox">
<script type="text/javascript">
$(document).ready(function(){
$("a.clickable").click(function(event){
event.preventDefault();
$("input#textbox").val($(this).html());
});
});
</script>
Maybe you forgot to give a class name "clickable" to your links?
if you're using ckeditor 4.x you can try
config.allowedContent = true;
if you're using ckeditor 3.x you may be having this issue.
try putting the following line in config.js
config.ignoreEmptyParagraph = false;
a string is essentially a sequence of characters and so the slicing operation works on it. What you are doing is in fact:
-> get an slice of 'a' from start to end in steps of 1 backward.
The rest are almost correct, except they should order by Date DESC
SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;
Most commonly, you'd use:
import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding
Python provides other distributions if you need.
If you have numpy
imported already, you can used its equivalent:
import numpy as np
np.random.uniform(a, b) # range [a, b)
Again, if you need another distribution, numpy
provides the same distributions as python, as well as many additional ones.
One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.
user@debian:~$ xauth list
debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xauth add debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xterm
source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su
You have to use Kendo UI DropDownList select
method (documentation in here).
Basically you should:
// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");
If you know the index you can use:
// selects by index
dropdownlist.select(1);
If not, use:
// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
return dataItem.symbol === "test";
});
JSFiddle example here
// Try this to download any file. laravel 5.*
// you need to use facade "use Illuminate\Http\Response;"
public function getDownload()
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path(). "/download/info.pdf";
return response()->download($file);
}
let dictionary = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]
let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]
EDIT:
The sorted array from the above code contains keys only, while values have to be retrieved from the original dictionary. However, 'Dictionary'
is also a 'CollectionType'
of (key, value) pairs and we can use the global 'sorted'
function to get a sorted array containg both keys and values, like this:
let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]
EDIT2: The monthly changing Swift syntax currently prefers
let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]
The global sorted
is deprecated.
The first push should be a:
git push -u origin branchname
That would make sure:
origin
',simple
'Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.
var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"};
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
Try this, note that you don't need to specify the end index in substring
.
var characters = member.substr(member.length -2);
You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.
Just do the following for executing a POST request:
var requestify = require('requestify');
requestify.post('http://example.com', {
hello: 'world'
})
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
response.getBody();
});
Valerio is almost right with his solution, but there is some logical mistake.
you must firstly check wether angle2 is bigger than angle, before adding 360 at a negative.
otherwise you always have a bigger value than angle
So the correct solution is:
var west = calculateMin(data.longitudes);
var east = calculateMax(data.longitudes);
var angle = east - west;
var north = calculateMax(data.latitudes);
var south = calculateMin(data.latitudes);
var angle2 = north - south;
var zoomfactor;
var delta = 0;
var horizontal = false;
if(angle2 > angle) {
angle = angle2;
delta = 3;
}
if (angle < 0) {
angle += 360;
}
zoomfactor = Math.floor(Math.log(960 * 360 / angle / GLOBE_WIDTH) / Math.LN2) - 2 - delta;
Delta is there, because i have a bigger width than height.
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
Using coalesce() converts null to 0:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;
#!/bin/bash
for i in $(seq 1 2 10)
do
echo "skip by 2 value $i"
done
try this one
public void writeFile(String arg1,String arg2) {_x000D_
try {_x000D_
if (!dir.exists()) {_x000D_
_x000D_
if (dir.mkdirs()) {_x000D_
_x000D_
Toast.makeText(getBaseContext(), "Directory created",_x000D_
Toast.LENGTH_SHORT).show();_x000D_
} else {_x000D_
Toast.makeText(getBaseContext(),_x000D_
"Error writng file " + filename, Toast.LENGTH_LONG)_x000D_
.show();_x000D_
}_x000D_
}_x000D_
_x000D_
else {_x000D_
_x000D_
File file = new File(dir, filename);_x000D_
if (!file.exists()) {_x000D_
file.createNewFile();_x000D_
}_x000D_
_x000D_
FileWriter fileWritter = new FileWriter(file, true);_x000D_
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);_x000D_
bufferWritter.write(arg1 + "\n");_x000D_
bufferWritter.close();_x000D_
_x000D_
} catch (Exception e) {_x000D_
e.printStackTrace();_x000D_
Toast.makeText(getBaseContext(),_x000D_
"Error writng file " + e.toString(), Toast.LENGTH_LONG)_x000D_
.show();_x000D_
}_x000D_
_x000D_
}
_x000D_
That's another solution (Spring Security 3):
public String getLoggedUser() throws Exception {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return (!name.equals("anonymousUser")) ? name : null;
}