Plot twist!
You can have orphaned distributed transactions holding exclusive locks and you will not see them if your script assumes there is a session associated with the transaction (there isn't!). Run the script below to identify these transactions:
;WITH ORPHANED_TRAN AS (
SELECT
dat.name,
dat.transaction_uow,
ddt.database_transaction_begin_time,
ddt.database_transaction_log_bytes_reserved,
ddt.database_transaction_log_bytes_used
FROM
sys.dm_tran_database_transactions ddt,
sys.dm_tran_active_transactions dat,
sys.dm_tran_locks dtl
WHERE
ddt.transaction_id = dat.transaction_id AND
dat.transaction_id = dtl.request_owner_id AND
dtl.request_session_id = -2 AND
dtl.request_mode = 'X'
)
SELECT DISTINCT * FROM ORPHANED_TRAN
Once you have identified the transaction, use the transaction_uow column to find it in MSDTC and decide whether to abort or commit it. If the transaction is marked as In Doubt (with a question mark next to it) you will probably want to abort it.
You can also kill the Unit Of Work (UOW) by specifying the transaction_uow in the KILL command:
KILL '<transaction_uow>'
References:
https://www.mssqltips.com/sqlservertip/4142/how-to-kill-a-blocking-negative-spid-in-sql-server/
here's how I promote all worksheet names to global names. YMMV
For Each wsh In ActiveWorkbook.Worksheets
For Each n In wsh.Names
' Get unqualified range name
Dim s As String
s = Split(n.Name, "!")(UBound(Split(n.Name, "!")))
' Add to "Workbook" scope
n.RefersToRange.Name = s
' Remove from "Worksheet" scope
Call n.Delete
Next n
Next wsh
you can try implementing this ForkJoinWorkerThreadFactory and inject it to Fork-Join class.
public ForkJoinPool(int parallelism,
ForkJoinWorkerThreadFactory factory,
UncaughtExceptionHandler handler,
boolean asyncMode) {
this(checkParallelism(parallelism),
checkFactory(factory),
handler,
asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
"ForkJoinPool-" + nextPoolId() + "-worker-");
checkPermission();
}
you can use this constructor of Fork-Join pool to do this.
notes:-- 1. if you use this, take into consideration that based on your implementation of new threads, scheduling from JVM will be affected, which generally schedules fork-join threads to different cores(treated as a computational thread). 2. task scheduling by fork-join to threads won't get affected. 3. Haven't really figured out how parallel stream is picking threads from fork-join(couldn't find proper documentation on it), so try using a different threadNaming factory so as to make sure, if threads in parallel stream are being picked from customThreadFactory that you provide. 4. commonThreadPool won't use this customThreadFactory.
I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )
For me this was a case that the Script path wouldn't load - I had incorrectly linked it. Check your script files - even if no path error is reported - actually load.
This is easy. Just grab your computer's IP address with IPconfig at the command prompt. Then, hit the service using the IP address rather than localhost. You don't need to do anything to Fiddler to make this work, it will just work by itself.
To hide the menu for a particular fragment:
setHasOptionsMenu(true); //Inside of onCreate in FRAGMENT:
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_search).setVisible(false);
}
th
elements in the table header or footer differs from number of columns in the table body or defined using columns
option.th
element in the table header.columnDefs.targets
option.th
elements in the table header or footer matches number of columns defined in the columns
option.colspan
attribute in the table header, make sure you have at least two header rows and one unique th
element for each column. See Complex header for more information.columnDefs.targets
option, make sure that zero-based column index refers to existing columns.See jQuery DataTables: Common JavaScript console errors - TypeError: Cannot read property ‘style’ of undefined for more information.
It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:
action="javascript:simpleCart.checkout()"
And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout()
as a static method of the simpleCart
class; but maybe checkout()
is actually an instance member, and not static. It depends how he defined checkout()
.
By the way, simpleCart
is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart
.
Here is some sample code that illustrates defining checkout()
as an instance member. This was the correct way to do it, prior to ECMA-6:
function SimpleCart() {
...
}
SimpleCart.prototype.checkout = function() { ... };
Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype
, just once, while the following technique defines the member on this
and does so repeatedly, with every instantiation.
function SimpleCart() {
...
this.checkout = function() { ... };
}
And here is an instance definition in ECMA-6, using an official class
:
class SimpleCart {
constructor() { ... }
...
checkout() { ... }
}
Compare to a static definition in ECMA-6. The difference is just one word:
class SimpleCart {
constructor() { ... }
...
static checkout() { ... }
}
And here is a static definition the old way, pre-ECMA-6. Note that the checkout()
method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.
function SimpleCart() {
...
}
SimpleCart.checkout = function() { ... };
Because of the way it is defined, a static function will have a different concept of what the keyword this
references. Note that instance member functions are called using the this
keyword:
this.checkout();
Static member functions are called using the class name:
SimpleCart.checkout();
The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this
because this
would refer to the global scope (which is window
).
action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing
There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:
// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();
// In HTML
action="javascript:SimpleCart.checkout(1234);"
// In Javascript
SimpleCart.checkout = function(myIndex) {
var myThis = SimpleCart.registry[myIndex];
myThis.checkout();
}
You could also store the index as an attribute on the element.
But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener()
and use the .bind()
capability.
One way to achieve this is using a position:fixed
container for the background image and place it outside of the .jumbotron
. Make the bg
container the same height as the .jumbotron
and center the background image:
background: url('/assets/example/...jpg') no-repeat center center;
CSS
.bg {
background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
position: fixed;
width: 100%;
height: 350px; /*same height as jumbotron */
top:0;
left:0;
z-index: -1;
}
.jumbotron {
margin-bottom: 0px;
height: 350px;
color: white;
text-shadow: black 0.3em 0.3em 0.3em;
background:transparent;
}
Then use jQuery to decrease the height of the .jumbtron
as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.
JavaScript
var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
var scrolled = $(window).scrollTop();
$('.bg').css('height', (jumboHeight-scrolled) + 'px');
}
$(window).scroll(function(e){
parallax();
});
Demo
Most of the answers on this thread won't work if you use AppendLine
like below:
var builder = new StringBuilder();
builder.AppendLine("One,");
builder.Length--; // Won't work
Console.Write(builder.ToString());
builder = new StringBuilder();
builder.AppendLine("One,");
builder.Length += -1; // Won't work
Console.Write(builder.ToString());
builder = new StringBuilder();
builder.AppendLine("One,");
Console.Write(builder.TrimEnd(',')); // Won't work
WHY??? @(&**(&@!!
The issue is simple but took me a while to figure it out: Because there are 2 more invisible characters at the end CR
and LF
(Carriage Return and Line Feed). Therefore, you need to take away 3 last characters:
var builder = new StringBuilder();
builder.AppendLine("One,");
builder.Length -= 3; // This will work
Console.WriteLine(builder.ToString());
In Conclusion
Use Length--
or Length -= 1
if the last method you called was Append
. Use Length =- 3
if you the last method you called AppendLine
.
Use DATE_ADD function
DATE_ADD(datecolumn, INTERVAL 30 MINUTE);
Others have pointed out that INNER JOIN
helps human readability, and that's a top priority, I agree.
Let me try to explain why the join syntax is more readable.
A basic SELECT
query is this:
SELECT stuff
FROM tables
WHERE conditions
The SELECT
clause tells us what we're getting back; the FROM
clause tells us where we're getting it from, and the WHERE
clause tells us which ones we're getting.
JOIN
is a statement about the tables, how they are bound together (conceptually, actually, into a single table).
Any query elements that control the tables - where we're getting stuff from - semantically belong to the FROM
clause (and of course, that's where JOIN
elements go). Putting joining-elements into the WHERE
clause conflates the which and the where-from, that's why the JOIN
syntax is preferred.
Below is a working example code.
Please note you need to add a reference to Newtonsoft.Json.Linq
string url = "https://yourAPIurl";
WebRequest myReq = WebRequest.Create(url);
string credentials = "xxxxxxxxxxxxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
CredentialCache mycache = new CredentialCache();
myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
var json = "[" + content + "]"; // change this to array
var objects = JArray.Parse(json); // parse as array
foreach (JObject o in objects.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = p.Value.ToString();
Console.Write(name + ": " + value);
}
}
Console.ReadLine();
Reference: TheDeveloperBlog.com
One last thing is to check for Event Listeners > "scroll" and test deleting them.
Even if you delete the Javascript that created them, the listeners will stick around and prevent scrolling.
use np.random.randint()
as np.random.random_integers()
is deprecated
random_matrix = np.random.randint(min_val,max_val,(<num_rows>,<num_cols>))
Obligatory: SHA1 is broken, you can compute SHA1 collisions for 45,000 USD. You should use sha256
:
var getSHA256ofJSON = function(input){
return crypto.createHash('sha256').update(JSON.stringify(input)).digest('hex')
}
To answer your question and make a SHA1 hash:
const INSECURE_ALGORITHM = 'sha1'
var getInsecureSHA1ofJSON = function(input){
return crypto.createHash(INSECURE_ALGORITHM).update(JSON.stringify(input)).digest('hex')
}
Then:
getSHA256ofJSON('whatever')
or
getSHA256ofJSON(['whatever'])
or
getSHA256ofJSON({'this':'too'})
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
I just used:
th:nth-child(4) {
width: 10%;
}
Replace 4 with the position of the header that you need to adjust the width for.The examples in the documentation used:
td, th {
width: 25%;
}
So I just modified it to get what I wanted.
I had the same problem. Unfortunately I was in wrong catalog level.
I tried to: git push -u origin master
-> there was a error
Then I tried: git pull --rebase
-> there still was a problem
Finally i change directory cd your_directory
Then I tried again ( git push
) and it works!
Communicating between different JavaScript execution context was supported even before HTML5 if the documents was of the same origin. If not or you have no reference to the other Window
object, then you could use the new postMessage API introduced with HTML5. I elaborated a bit on both approaches in this stackoverflow answer.
IN Android Studio 2.3
Here you can change your new Password or User
Use entrySet()
to iterate through Map
and need to access value and key:
Map<String, Person> hm = new HashMap<String, Person>();
hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));
Set<Map.Entry<String, Person>> set = hm.entrySet();
for (Map.Entry<String, Person> me : set) {
System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());
}
If you want just to iterate over keys
of map you can use keySet()
for(String key: map.keySet()) {
Person value = map.get(key);
}
If you just want to iterate over values
of map you can use values()
for(Person person: map.values()) {
}
Once you've done this
group p by p.SomeId into pg
you no longer have access to the range variables used in the initial from
. That is, you can no longer talk about p
or bp
, you can only talk about pg
.
Now, pg
is a group and so contains more than one product. All the products in a given pg
group have the same SomeId
(since that's what you grouped by), but I don't know if that means they all have the same BaseProductId
.
To get a base product name, you have to pick a particular product in the pg
group (As you are doing with SomeId
and CountryCode
), and then join to BaseProducts
.
var result = from p in Products
group p by p.SomeId into pg
// join *after* group
join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id
select new ProductPriceMinMax {
SomeId = pg.FirstOrDefault().SomeId,
CountryCode = pg.FirstOrDefault().CountryCode,
MinPrice = pg.Min(m => m.Price),
MaxPrice = pg.Max(m => m.Price),
BaseProductName = bp.Name // now there is a 'bp' in scope
};
That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.
Made an app with two labels in IB and the following:
@IBOutlet var label1: UILabel!
@IBOutlet var label2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label1.textColor = UIColor.redColor() // in Swift 3 it's UIColor.red
label2.textColor = label1.textColor
}
label2 color changed as expected, so your line works. Try println(otherLabel.textColor)
right before you set myLabel.textColor to see if the color's what you expect.
svn revert deletedDirectory
Here's the documentation for the svn revert
command.
If deletedDirectory
was deleted using rmdir
and not svn rm
, you'll need to do
svn update deletedDirectory
instead.
Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
Try something like this:
IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);
Not sure if it'll resize after being launched though, so maybe it's not what you want
You could use strftime
, but struct tm
doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);
Along with top ranked answer you may use a bit simpliest approach. Apache commons FieldUtils
class already has particular method that can do the stuff. Please, take a look at FieldUtils.removeFinalModifier
method. You should specify target field instance and accessibility forcing flag (if you play with non-public fields). More info you can find here.
# setting ----------------
commonMode=false
if [[ $something == 'COMMON' ]]; then
commonMode=true
fi
# using ----------------
if $commonMode; then
echo 'YES, Common Mode'
else
echo 'NO, no Common Mode'
fi
$commonMode && echo 'commonMode is ON ++++++'
$commonMode || echo 'commonMode is OFF xxxxxx'
A better trick, so you don't lose the value of the button is
function showwait() {
document.getElementById('WAIT').style['display']='inline';
document.getElementById('BUTTONS').style['display']='none';
}
wrap code to show in a div
id=WAIT style="display:none"> text to display (end div)
wrap code to hide in a div
id=BUTTONS style="display:inline"> ... buttons or whatever to hide with
onclick="showwait();"
(end div)
Turns out... we had to also chmod 755 the parent directory, user, in addition to xxx.
One hack is to (mis)use the ping command:
ping 127.0.0.1 -n 6 > nul
Explanation:
ping
is a system utility that sends ping requests. ping
is available on all versions of Windows.127.0.0.1
is the IP address of localhost. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.-n 6
specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.> nul
suppress the output of ping
, by redirecting it to nul
.Edit your config file normally located at '~/.ssh/config', and at the beggining of the file, add the below lines
Host *
User your_login_user
StrictHostKeyChecking no
IdentityFile ~/my_path/id_rsa.pub
User set to your_login_user
says that this settings belongs to your_login_user
StrictHostKeyChecking set to no will avoid the prompt
IdentityFile is path to RSA key
This works for me and my scripts, good luck to you.
Adding to Rob?'s answer: in case you want to print rather large numbers, using thousand separators can be a great help (note the comma).
>>> f'{a*1000:,.2f}'
'10,123.40'
Spark gives 5 types of Storage level
MEMORY_ONLY
MEMORY_ONLY_SER
MEMORY_AND_DISK
MEMORY_AND_DISK_SER
DISK_ONLY
cache()
will use MEMORY_ONLY
. If you want to use something else, use persist(StorageLevel.<*type*>)
.
By default persist()
will
store the data in the JVM heap as unserialized objects.
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" CssClass="CoolButtons"/>
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btnEdit = (Button)sender;
GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
//Get the gridview Row Details
}
And Same As for Delete button
You can easily use the MODE argument:
MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions
If the mode argument is omitted, the value of the default_week_format system variable is used:
MySQL :: MySQL 5.1 Reference Manual :: 5.1.4 Server System Variables
UPDATE 7/3/2014: As of now, jquery-latest.js
is no longer being updated.
From the jQuery blog:
We know that http://code.jquery.com/jquery-latest.js is abused because of the CDN statistics showing it’s the most popular file. That wouldn’t be the case if it was only being used by developers to make a local copy.
We have decided to stop updating this file, as well as the minified copy, keeping both files at version 1.11.1 forever.
The Google CDN team has joined us in this effort to prevent inadvertent web breakage and no longer updates the file at http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js. That file will stay locked at version 1.11.1 as well.
The following, now moot, answer is preserved here for historical reasons.
Don't do this. Seriously, don't.
Linking to major versions of jQuery does work, but it's a bad idea -- whole new features get added and deprecated with each decimal update. If you update jQuery automatically without testing your code COMPLETELY, you risk an unexpected surprise if the API for some critical method has changed.
Here's what you should be doing: write your code using the latest version of jQuery. Test it, debug it, publish it when it's ready for production.
Then, when a new version of jQuery rolls out, ask yourself: Do I need this new version in my code? For instance, is there some critical browser compatibility that didn't exist before, or will it speed up my code in most browsers?
If the answer is "no", don't bother updating your code to the latest jQuery version. Doing so might even add NEW errors to your code which didn't exist before. No responsible developer would automatically include new code from another site without testing it thoroughly.
There's simply no good reason to ALWAYS be using the latest version of jQuery. The old versions are still available on the CDNs, and if they work for your purposes, then why bother replacing them?
A secondary, but possibly more important, issue is caching. Many people link to jQuery on a CDN because many other sites do, and your users have a good chance of having that version already cached.
The problem is, caching only works if you provide a full version number. If you provide a partial version number, far-future caching doesn't happen -- because if it did, some users would get different minor versions of jQuery from the same URL. (Say that the link to 1.7 points to 1.7.1 one day and 1.7.2 the next day. How will the browser make sure it's getting the latest version today? Answer: no caching.)
In fact here's a breakdown of several options and their expiration settings...
http://code.jquery.com/jquery-latest.min.js (no cache)
http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js (1 hour)
http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js (1 hour)
http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js (1 year)
So, by linking to jQuery this way, you're actually eliminating one of the major reasons to use a CDN in the first place.
http://code.jquery.com/jquery-latest.min.js may not always give you the version you expect, either. As of this writing, it links to the latest version of jQuery 1.x, even though jQuery 2.x has been released as well. This is because jQuery 1.x is compatible with older browsers including IE 6/7/8, and jQuery 2.x is not. If you want the latest version of jQuery 2.x, then (for now) you need to specify that explicitly.
The two versions have the same API, so there is no perceptual difference for compatible browsers. However, jQuery 1.x is a larger download than 2.x.
I'd rather tab indentation not work than breaking tabbing between form items.
If you want to indent to put in code in the Markdown box, use Ctrl+K (or ?K on a Mac).
In terms of actually stopping the action, jQuery (which Stack Overflow uses) will stop an event from bubbling when you return false from an event callback. This makes life easier for working with multiple browsers.
Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:
import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;
verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());
The problem is that your <label>
is inside of an <h2>
tag, and header tags have a margin
set by the default stylesheet.
There are lots of things I have seen make a model diverge.
Too high of a learning rate. You can often tell if this is the case if the loss begins to increase and then diverges to infinity.
I am not to familiar with the DNNClassifier but I am guessing it uses the categorical cross entropy cost function. This involves taking the log of the prediction which diverges as the prediction approaches zero. That is why people usually add a small epsilon value to the prediction to prevent this divergence. I am guessing the DNNClassifier probably does this or uses the tensorflow opp for it. Probably not the issue.
Other numerical stability issues can exist such as division by zero where adding the epsilon can help. Another less obvious one if the square root who's derivative can diverge if not properly simplified when dealing with finite precision numbers. Yet again I doubt this is the issue in the case of the DNNClassifier.
You may have an issue with the input data. Try calling assert not np.any(np.isnan(x))
on the input data to make sure you are not introducing the nan. Also make sure all of the target values are valid. Finally, make sure the data is properly normalized. You probably want to have the pixels in the range [-1, 1] and not [0, 255].
The labels must be in the domain of the loss function, so if using a logarithmic-based loss function all labels must be non-negative (as noted by evan pu and the comments below).
I did a little investigation and the solution that works for me was a mix of a few solutions founded in this post.
I'm basically compiling this solution and I'm posting what works for me. In my case, I'm don't want to use any token from .net core.
public async Task ResetPassword(string userId, string password)
{
var user = await _userManager.FindByIdAsync(userId);
var hashPassword= _userManager.PasswordHasher.HashPassword(user, password);
user.PasswordHash = passwordHash;
await _userManager.UpdateAsync(user);
}
It's a little trickier to do what you're trying to do than I'd prefer, but that's because you don't really directly bind a DataGrid
to a DataTable
.
When you bind DataGrid.ItemsSource
to a DataTable
, you're really binding it to the default DataView
, not to the table itself. This is why, for instance, you don't have to do anything to make a DataGrid
sort rows when you click on a column header - that functionality's baked into DataView
, and DataGrid
knows how to access it (through the IBindingList
interface).
The DataView
implements IEnumerable<DataRowView>
(more or less), and the DataGrid
fills its items by iterating over this. This means that when you've bound DataGrid.ItemsSource
to a DataTable
, its SelectedItem
property will be a DataRowView
, not a DataRow
.
If you know all this, it's pretty straightforward to build a wrapper class that lets you expose properties that you can bind to. There are three key properties:
Table
, the DataTable
,Row
, a two-way bindable property of type DataRowView
, and SearchText
, a string property that, when it's set, will find the first matching DataRowView
in the table's default view, set the Row
property, and raise PropertyChanged
.It looks like this:
public class DataTableWrapper : INotifyPropertyChanged
{
private DataRowView _Row;
private string _SearchText;
public DataTableWrapper()
{
// using a parameterless constructor lets you create it directly in XAML
DataTable t = new DataTable();
t.Columns.Add("id", typeof (int));
t.Columns.Add("text", typeof (string));
// let's acquire some sample data
t.Rows.Add(new object[] { 1, "Tower"});
t.Rows.Add(new object[] { 2, "Luxor" });
t.Rows.Add(new object[] { 3, "American" });
t.Rows.Add(new object[] { 4, "Festival" });
t.Rows.Add(new object[] { 5, "Worldwide" });
t.Rows.Add(new object[] { 6, "Continental" });
t.Rows.Add(new object[] { 7, "Imperial" });
Table = t;
}
// you should have this defined as a code snippet if you work with WPF
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
// SelectedItem gets bound to this two-way
public DataRowView Row
{
get { return _Row; }
set
{
if (_Row != value)
{
_Row = value;
OnPropertyChanged("Row");
}
}
}
// the search TextBox is bound two-way to this
public string SearchText
{
get { return _SearchText; }
set
{
if (_SearchText != value)
{
_SearchText = value;
Row = Table.DefaultView.OfType<DataRowView>()
.Where(x => x.Row.Field<string>("text").Contains(_SearchText))
.FirstOrDefault();
}
}
}
public DataTable Table { get; private set; }
}
And here's XAML that uses it:
<Window x:Class="DataGridSelectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:DataGridSelectionDemo="clr-namespace:DataGridSelectionDemo"
Title="DataGrid selection demo"
Height="350"
Width="525">
<Window.DataContext>
<DataGridSelectionDemo:DataTableWrapper />
</Window.DataContext>
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label>Text</Label>
<TextBox Grid.Column="1"
Text="{Binding SearchText, Mode=TwoWay}" />
</Grid>
<dg:DataGrid DockPanel.Dock="Top"
ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}" />
</DockPanel>
</Window>
The best way I have found is:
class SingletonClass {
private static _instance:SingletonClass = new SingletonClass();
private _score:number = 0;
constructor() {
if(SingletonClass._instance){
throw new Error("Error: Instantiation failed: Use SingletonClass.getInstance() instead of new.");
}
SingletonClass._instance = this;
}
public static getInstance():SingletonClass
{
return SingletonClass._instance;
}
public setScore(value:number):void
{
this._score = value;
}
public getScore():number
{
return this._score;
}
public addPoints(value:number):void
{
this._score += value;
}
public removePoints(value:number):void
{
this._score -= value;
}
}
Here is how you use it:
var scoreManager = SingletonClass.getInstance();
scoreManager.setScore(10);
scoreManager.addPoints(1);
scoreManager.removePoints(2);
console.log( scoreManager.getScore() );
https://codebelt.github.io/blog/typescript/typescript-singleton-pattern/
Try to use Hibernate.getClass(obj)
You do not need the latex2exp
package to do what you wanted to do. The following code would do the trick.
ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) +
geom_point() +
labs(title=expression("Fuel Efficiency"~(alpha*Omega)),
color=expression(alpha*Omega), x=expression(Delta~price))
Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*")
works, so I suggest giving it a try.
More comments asked about getting ? Price
and I find the most straightforward way to achieve that is expression(Delta~price))
. If you need to add something before the Greek letter, you can also do this:
expression(Indicative~Delta~price)
which gets you:
If you want to make sure that the library is loaded if and only if the program lunar-calendar-gtk
is launched, you can apply this:
You set the environment variable per command by prefixing the command with it:
$ LD_PRELOAD="liblunar-calendar-preload.so" printenv "LD_PRELOAD"
liblunar-calendar-preload.so
$ printenv "LD_PRELOAD"
$
You can then choose to put this in a shell script and make lunar-calendar-gtk
a symlink to this shell script, replaceing the original referencee. This effectively makes sure that the library is loaded everytime the original application is executed.
You will have to rename the original lunar-calendar-gtk
to something else, which might not be too intriguing as it possibly may cause issues with uninstallation and upgrading. However, I found it useful with a former version of Skype.
You might find it very useful to sample Redis keys and group them by type. Salvatore has written a tool called redis-sampler that issues about 10000 RANDOMKEY
commands followed by a TYPE
on retrieved keys. In a matter of seconds, or minutes, you should get a fairly accurate view of the distribution of key types.
I've written an extension (unfortunately not anywhere open-source because it's work related), that adds a bit of introspection of key names via regexs that give you an idea of what kinds of application keys (according to whatever naming structure you're using), are stored in Redis. Combined with the more general output of redis-sampler, this should give you an extremely good idea of what's going on.
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
For those who (unlike OP) are using the express lib:
http.get('*',function(req,res){
res.redirect('http://exmple.com'+req.url)
})
Just remove the width from both divs.
A div
is a block level element and will use all available space (unless you start floating or positioning them) so the outer div will automatically be 100% wide and the inner div will use all remaining space after setting the left margin.
I have added an example with a textarea
on jsfiddle.
Updated example with an input.
Following are few libraries to create PDF with Java:
I have used iText for genarating PDF's with a little bit of pain in the past.
Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.
The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is because you specified http://file://
The http://
at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.
Note
If you link to something like
<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>
The above represents a link to a file called k:/yourfile.pdf
on the k: drive on the machine on which you are viewing the URL.
You can do this, for example the below creates a link to C:\temp\test.pdf
<a href="file:///C:/Temp/test.pdf">test.pdf</a>
By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.
Most people do not have a K:/ drive.
But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).
You could try
<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is a malformed
Below works for first tr
of the table under thead
table thead tr:first-child {
background: #f2f2f2;
}
And this works for the first tr
of thead
and tbody
both:
table thead tbody tr:first-child {
background: #f2f2f2;
}
May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
}
Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.
Well Object.assign gives you the possibility to do something close albeit a bit more like composition with ES6 classes.
class Animal {
constructor(){
Object.assign(this, new Shark())
Object.assign(this, new Clock())
}
}
class Shark {
// only what's in constructor will be on the object, ence the weird this.bite = this.bite.
constructor(){ this.color = "black"; this.bite = this.bite }
bite(){ console.log("bite") }
eat(){ console.log('eat') }
}
class Clock{
constructor(){ this.tick = this.tick; }
tick(){ console.log("tick"); }
}
let animal = new Animal();
animal.bite();
console.log(animal.color);
animal.tick();
I've not seen this used anywhere but it's actually quite useful. You can use function shark(){}
instead of class but there are advantages of using class instead.
I believe the only thing different with inheritance with extend
keyword is that the function don't live only on the prototype
but also the object itself.
Thus now when you do new Shark()
the shark
created has a bite
method, while only its prototype has a eat
method
You can use getContentAsString
method to get the response data as string.
String payload = "....";
String apiToTest = "....";
MvcResult mvcResult = mockMvc.
perform(post(apiToTest).
content(payload).
contentType(MediaType.APPLICATION_JSON)).
andReturn();
String responseData = mvcResult.getResponse().getContentAsString();
You can refer this link for test application.
Use wordwrap()
to truncate the string without breaking words if the string is longer than 50 characters, and just add ...
at the end:
$str = $input;
if( strlen( $input) > 50) {
$str = explode( "\n", wordwrap( $input, 50));
$str = $str[0] . '...';
}
echo $str;
Otherwise, using solutions that do substr( $input, 0, 50);
will break words.
I found the answer is git reset --merge
- it clears the conflicted cherry-pick attempt.
There is now another solution for React and React Native in late/2019:
<input>
<Debounce ms={500}>
<List/>
</Debounce>
It's a component, easy to use, tiny and widley supported
import React from 'react';
import Debounce from 'react-debounce-component';
class App extends React.Component {
constructor (props) {
super(props);
this.state = {value: 'Hello'}
}
render () {
return (
<div>
<input value={this.state.value} onChange={(event) => {this.setState({value: event.target.value})}}/>
<Debounce ms={1000}>
<div>{this.state.value}</div>
</Debounce>
</div>
);
}
}
export default App;
*I'm the creator of this component
FOR SPECIFIC NUM:
SELECT COUNT(1) FROM YOUR_TABLE WHERE NUM = 1
FOR ALL NUM:
SELECT NUM, COUNT(1) FROM YOUR_TABLE GROUP BY NUM
I would not use Group as column name since it is reserved word. However following SQL would work.
SELECT a.Person, a.Group, a.Age FROM [TABLE_NAME] a
INNER JOIN
(
SELECT `Group`, MAX(Age) AS oldest FROM [TABLE_NAME]
GROUP BY `Group`
) b ON a.Group = b.Group AND a.Age = b.oldest
If you do not need to modify the substring, then you can use QStringRef
. The QStringRef
class is a read only wrapper around an existing QString
that references a substring within the existing string. This gives much better performance than creating a new QString
object to contain the sub-string. E.g.
QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"
If you do need to modify the substring, then left()
, mid()
and right()
will do what you need...
QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"
Visual Basic Version:
Private Sub setRegisterForWebBrowser()
Dim appName = Process.GetCurrentProcess().ProcessName + ".exe"
SetIE8KeyforWebBrowserControl(appName)
End Sub
Private Sub SetIE8KeyforWebBrowserControl(appName As String)
'ref: http://stackoverflow.com/questions/17922308/use-latest-version-of-ie-in-webbrowser-control
Dim Regkey As RegistryKey = Nothing
Dim lgValue As Long = 8000
Dim strValue As Long = lgValue.ToString()
Try
'For 64 bit Machine
If (Environment.Is64BitOperatingSystem) Then
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", True)
Else 'For 32 bit Machine
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", True)
End If
'If the path Is Not correct Or
'If user't have priviledges to access registry
If (Regkey Is Nothing) Then
MessageBox.Show("Application Settings Failed - Address Not found")
Return
End If
Dim FindAppkey As String = Convert.ToString(Regkey.GetValue(appName))
'Check if key Is already present
If (FindAppkey = strValue) Then
MessageBox.Show("Required Application Settings Present")
Regkey.Close()
Return
End If
'If key Is Not present add the key , Kev value 8000-Decimal
If (String.IsNullOrEmpty(FindAppkey)) Then
' Regkey.SetValue(appName, BitConverter.GetBytes(&H1F40), RegistryValueKind.DWord)
Regkey.SetValue(appName, lgValue, RegistryValueKind.DWord)
'check for the key after adding
FindAppkey = Convert.ToString(Regkey.GetValue(appName))
End If
If (FindAppkey = strValue) Then
MessageBox.Show("Registre de l'application appliquée avec succès")
Else
MessageBox.Show("Échec du paramètrage du registre, Ref: " + FindAppkey)
End If
Catch ex As Exception
MessageBox.Show("Application Settings Failed")
MessageBox.Show(ex.Message)
Finally
'Close the Registry
If (Not Regkey Is Nothing) Then
Regkey.Close()
End If
End Try
End Sub
Wrap it in double quotes
alter user "dell-sys" with password 'Pass@133';
Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys"
then you will have to issue exact the same whenever you refer to that user.
I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.
If you happen to be an iOS developer
:
Check how many simulators that you have downloaded as they take up a lot of space:
Go to: ~/Library/Developer/Xcode/iOS DeviceSupport
Also delete old archived apps:
Go to: ~/Library/Developer/Xcode/Archives
I cleared 100GB doing this.
For files in a directory, you can use things like:
if exist *.csv echo "csv file found"
or
if not exist *.csv goto nofile
You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.
So it could relate to the current directory (get it from Directory.GetCurrentDirectory()
) or to the application executable path (eg. Application.ExecutablePath
comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location
) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath()
with one element of the Environment.SpecialFolder
enumeration).
Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!
In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.
I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.
Calculate the Distance between Two Points in javascript
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
For more details refer this: Reference Link
If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content"
. Have overflow hidden on this new inner-div, but keep overflow visible on the green box.
The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.
<div id="1" background: #efe; padding: 5px; width: 125px">
<div id="content" style="overflow: hidden;">
</div>
<div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
<div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
</div>
</div>
If you use "hg remove b"
against a file with "A" status, which means it has been added but not commited, Mercurial will respond:
not removing b: file has been marked for add (use forget to undo)
This response is a very clear explication of the difference between remove and forget.
My understanding is that "hg forget"
is for undoing an added but not committed file so that it is not tracked by version control; while "hg remove"
is for taking out a committed file from version control.
This thread has a example for using hg remove
against files of 7 different types of status.
change
public static final String URL = "http://api-Location";
to
public static final String URL = "https://api-Location"
it's happen because i'm using 000webhostapp app
This is for the icon in the browser (most of the sites omit the type):
<link rel="icon" type="image/vnd.microsoft.icon"
href="http://example.com/favicon.ico" />
or
<link rel="icon" type="image/png"
href="http://example.com/image.png" />
or
<link rel="apple-touch-icon"
href="http://example.com//apple-touch-icon.png">
for the shortcut icon:
<link rel="shortcut icon"
href="http://example.com/favicon.ico" />
Place them in the <head></head>
section.
Edit may 2019 some additional examples from MDN
You can use not only now()
, also current_timestamp()
and localtimestamp()
.
The main reason of incorrect display timestamp is inserting NOW() with single quotes! It didn't work for me in MySQL Workbench because of this IDE add single quotes for mysql functions and i didn't recognize it at once )
Don't use functions with single quotes like in MySQL Workbench. It doesn't work.
the error explain all things, the idea is confused between gradle and maven.
try to create new project with two gradle modules, you can build spring application with gradle as maven.
see this example from spring guides
I had some problems with the insertion process just like you, so here is the code how I have solved the problem:
void add_by_position(int data, int pos)
{
link *node = new link;
link *linker = head;
node->data = data;
for (int i = 0; i < pos; i++){
linker = linker->next;
}
node->next = linker;
linker = head;
for (int i = 0; i < pos - 1; i++){
linker = linker->next;
}
linker->next = node;
boundaries++;
}
One-liner for your problem:
data = [json.loads(line) for line in open('tweets.json', 'r')]
Use Not IsNull(Fields!W_O_Count.Value)
I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick
event handler for the radio buttons:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var ex1 = document.getElementById('example1');
var ex2 = document.getElementById('example2');
var ex3 = document.getElementById('example3');
ex1.onclick = handler;
ex2.onclick = handler;
ex3.onclick = handler;
}
function handler() {
alert('clicked');
}
</script>
</head>
<body>
<input type="radio" name="example1" id="example1" value="Example 1" />
<label for="example1">Example 1</label>
<input type="radio" name="example2" id="example2" value="Example 2" />
<label for="example1">Example 2</label>
<input type="radio" name="example3" id="example3" value="Example 3" />
<label for="example1">Example 3</label>
</body>
</html>
With Guava, you can use Iterables.concat(Iterable<T> ...)
, it creates a live view of all the iterables, concatenated into one (if you change the iterables, the concatenated version also changes). Then wrap the concatenated iterable with Iterables.unmodifiableIterable(Iterable<T>)
(I hadn't seen the read-only requirement earlier).
From the Iterables.concat( .. )
JavaDocs:
Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary. The returned iterable's iterator supports
remove()
when the corresponding input iterator supports it.
While this doesn't explicitly say that this is a live view, the last sentence implies that it is (supporting the Iterator.remove()
method only if the backing iterator supports it is not possible unless using a live view)
Sample Code:
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
Iterables.unmodifiableIterable(
Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9999999]
Edit:
By Request from Damian, here's a similar method that returns a live Collection View
public final class CollectionsX {
static class JoinedCollectionView<E> implements Collection<E> {
private final Collection<? extends E>[] items;
public JoinedCollectionView(final Collection<? extends E>[] items) {
this.items = items;
}
@Override
public boolean addAll(final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
for (final Collection<? extends E> coll : items) {
coll.clear();
}
}
@Override
public boolean contains(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
@Override
public Iterator<E> iterator() {
return Iterables.concat(items).iterator();
}
@Override
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
int ct = 0;
for (final Collection<? extends E> coll : items) {
ct += coll.size();
}
return ct;
}
@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a live aggregated collection view of the collections passed in.
* <p>
* All methods except {@link Collection#size()}, {@link Collection#clear()},
* {@link Collection#isEmpty()} and {@link Iterable#iterator()}
* throw {@link UnsupportedOperationException} in the returned Collection.
* <p>
* None of the above methods is thread safe (nor would there be an easy way
* of making them).
*/
public static <T> Collection<T> combine(
final Collection<? extends T>... items) {
return new JoinedCollectionView<T>(items);
}
private CollectionsX() {
}
}
You can find more information about the date pipe here, such as formats.
If you want to use it in your component, you can simply do
pipe = new DatePipe('en-US'); // Use your own locale
Now, you can simply use its transform method, which will be
const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');
The easiest way is to just learn how to do DOM traversing and manipulation with the plain DOM api (you would probably call this: normal JavaScript).
This can however be a pain for some things. (which is why libraries were invented in the first place).
Googling for "javascript DOM traversing/manipulation" should present you with plenty of helpful (and some less helpful) resources.
The articles on this website are pretty good: http://www.htmlgoodies.com/primers/jsp/
And as Nosredna points out in the comments: be sure to test in all browsers, because now jQuery won't be handling the inconsistencies for you.
You do not need jQuery just to do this! All you need is a tiny and very light vanilla Javascript and a css class (as in all the answers above) :
First define a CSS class in your stylesheet called current.
Second add the following pure JavaScript either in your existing JavaScript file or in a separate js script file (but add script tage link to it in the head of the pages) or event just add it in a script tag just before the closing body tag, it will still work in all these cases.
function highlightCurrent() {
const curPage = document.URL;
const links = document.getElementsByTagName('a');
for (let link of links) {
if (link.href == curPage) {
link.classList.add("current");
}
}
}
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
highlightCurrent()
}
};
The 'href' attribute of current link should be the absolute path as given by document.URL (console.log it to make sure it is the same)
Try this:
var my_condition = true;
var lastSel = $("#my_select option:selected");
$("#my_select").change(function(){
if(my_condition)
{
lastSel.prop("selected", true);
}
});
$("#my_select").click(function(){
lastSel = $("#my_select option:selected");
});
Don't abuse form elements where <a> elements will suffice.
<style>
/* or put this in your stylesheet */
.button {
display: inline-block;
padding: 3px 5px;
border: 1px solid #000;
background: #eee;
}
</style>
<!-- instead of abusing a button or input element -->
<a href="url" class="button">text</a>
You can try this
File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
startActivity(intent);
"^.*$"
literally just means select everything
"^" // anchors to the beginning of the line
".*" // zero or more of any character
"$" // anchors to end of line
First of all, beware of finding old examples. You've found one that uses XmlTextWriter
, which is deprecated as of .NET 2.0. XmlWriter.Create
should be used instead.
Here's an example of serializing an object into an XML column:
public void SerializeToXmlColumn(object obj)
{
using (var outputStream = new MemoryStream())
{
using (var writer = XmlWriter.Create(outputStream))
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(writer, obj);
}
outputStream.Position = 0;
using (var conn = new SqlConnection(Settings.Default.ConnectionString))
{
conn.Open();
const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
{
using (var reader = XmlReader.Create(outputStream))
{
var xml = new SqlXml(reader);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@Data", xml);
cmd.ExecuteNonQuery();
}
}
}
}
}
You will have to do it in two steps:
UPDATE MyTable SET MyNullableColumn = 0
WHERE MyNullableColumn IS NULL
ALTER TABLE MyTable
ALTER COLUMN MyNullableColumn MyNullableColumnDatatype NOT NULL
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
You can solve your problem with help of Attribute routing
Controller
[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }
URI in jquery
api/category/1
Route Configuration
using System.Web.Http;
namespace WebApplication
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
}
and your default routing is working as default convention-based routing
Controller
public string Get(int id)
{
return "object of id id";
}
URI in Jquery
/api/records/1
Route Configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Review article for more information Attribute routing and onvention-based routing here & this
if your project maven based, you can also try updating your project maven config by selecting project. Right click project> Maven>Update Project option. it will update your project config.
just use php composer.phar require
For example :
php composer.phar require doctrine/mongodb-odm-bundle 3.0
Also available with install.
https://getcomposer.org/doc/03-cli.md#require https://getcomposer.org/doc/03-cli.md#install
For List<List<List<x>>>
and so on, use
list.SelectMany(x => x.SelectMany(y => y)).ToList();
This has been posted in a comment, but it does deserves a separate reply in my opinion.
In Swift 4:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed colour
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
// Set the label
label.attributedText = attributedString
In Swift 3:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed color
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
// Set the label
label.attributedText = attributedString
Enjoy.
You're looking for the /Y
switch.
Just to add to the other answers, there are still noteworthy differences here, specifically when dealing with <svg>
elements.
I have used both .childNodes
and .children
and have preferred working with the HTMLCollection
delivered by the .children
getter.
Today however, I ran into issues with IE/Edge failing when using .children
on an <svg>
.
While .children
is supported in IE on basic HTML elements, it isn't supported on document/document fragments, or SVG elements.
For me, I was able to simply grab the needed elements via .childNodes[n]
because I don't have extraneous text nodes to worry about. You may be able to do the same, but as mentioned elsewhere above, don't forget that you may run into unexpected elements.
Hope this is helpful to someone scratching their head trying to figure out why .children
works elsewhere in their js on modern IE and fails on document or SVG elements.
I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple>
and how it handles multiple values from this example at w3schools.
<form action="/action_page.php">
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
For PHP use:
<select name="cars[]" multiple>
Live example from above at w3schools.com
From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.
Hope this helps anyone looking for a more 'standard' way of handling this issue.
You can use the following command: jar xf rt.jar
Where X
stands for extraction and the f
would be any options that indicate that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
Just add wrap the link text in a 'p' tag or something similar and add margin and padding to that element, this way it wont affect the settings that MiffTheFox gave you, i.e.
<li> <a href="#"> <p>Link Text </p> </a> </li>
$resource("../rest/api"}).get();
returns an object.
$resource("../rest/api").query();
returns an array.
You must use :
return $resource('../rest/api.php?method=getTask&q=*').query();
When you have replace: true
you get the following piece of DOM:
<div ng-controller="Ctrl" class="ng-scope">
<div class="ng-binding">hello</div>
</div>
whereas, with replace: false
you get this:
<div ng-controller="Ctrl" class="ng-scope">
<my-dir>
<div class="ng-binding">hello</div>
</my-dir>
</div>
So the replace
property in directives refer to whether the element to which the directive is being applied (<my-dir>
in that case) should remain (replace: false
) and the directive's template should be appended as its child,
OR
the element to which the directive is being applied should be replaced (replace: true
) by the directive's template.
In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:
.directive('myDir', function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<div>{{title}}<div ng-transclude></div></div>'
};
});
In that case if in the directive's template you have an element (or elements) with attribute ng-transclude
, its content will be replaced by the element's (to which the directive is being applied) original content.
See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview
See this to read more about translusion.
I noticed that this question was not marked as answered after 2 years - I think the closest answer is Richards, but it can be simplified quite a lot to this:
list1.Concat(list2)
.ToLookup(p => p.Name)
.Select(g => g.Aggregate((p1, p2) => new Person
{
Name = p1.Name,
Value = p1.Value,
Change = p2.Value - p1.Value
}));
Although this won't error in the case where you have duplicate names in either set.
Some other answers have suggested using unioning - this is definitely not the way to go as it will only get you a distinct list, without doing the combining.
For this error, I copied the latest libstdc++.so.6.0.17 from other server, and removed the soft link and recreated it.
1. Copy the the libstdc++.so.6.0.15 or latest from other server to the affected system.
In my case SUSE linux 11 SP3 had latest.
2. rm libstdc++.so.6
3. ln -s libstdc++.so.6.0.17 libstdc++.so.6 (under /usr/lib64 directory).
nJoy
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
I commented out the line with the following setting
$cfg['Servers'][1]['table_uiprefs']
Its not really an elegant solution, but it worked for my needs. (Just getting a basic PMA for running queries etc without UI customization).
Please do this only if you do not care about UI Prefs. If not, other people have answered this question very well.
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
This is a fast solution with a temporary object.
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }],_x000D_
empid = [1, 4, 5],_x000D_
object = {},_x000D_
result;_x000D_
_x000D_
records.forEach(function (a) {_x000D_
object[a.empid] = a;_x000D_
});_x000D_
_x000D_
result = empid.map(function (a) {_x000D_
return object[a];_x000D_
});_x000D_
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
_x000D_
In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:
let response = {status: 200, data: []};
and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..
let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};
and assigning of the fake data:
response.data = fakeData;
Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:
$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie
$cfg['Servers'][$i]['user'] = 'root'; // MySQL user
$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password
Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:
$cfg['Servers'][$i]['AllowRoot'] = TRUE; // true = allow root login
This way you have your root password set.
java.sql.Timestamp
is a subclass of java.util.Date
. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat
and creating Joda DateTime
should be straightforward from this point on.
I've seen a few different approaches to this, but I use a generic utility method as such:
public static T DeepClone<T>(this T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
Notes:
[Serializable]
for this to work. Your source file must include the following code:
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
res.sendFile( __dirname + "/public/" + "index1.html" );
where __dirname
will manage the name of the directory that the currently executing script ( server.js
) resides in.
In my case, it was because the fixed element was being shown by using an animation. As stated in this link:
in Safari 9.1, having a position:fixed-element inside an animated element, may cause the position:fixed-element to not appear.
make sure the database you want to import to is created, then you can import the dump with
sudo -u postgres -i psql testdatabase < db-structure.sql
If you want to overwrite the whole database, first drop the database
# be sure you drop the right database !!!
#sudo -u postgres -i psql -c "drop database testdatabase;"
and then recreate it with
sudo -u postgres -i psql -c "create database testdatabase;"
This query will list all of the tables in all of the databases and schemas (uncomment the line(s) in the WHERE
clause to filter for specific databases, schemas, or tables), with the privileges shown in order so that it's easy to see if a specific privilege is granted or not:
SELECT grantee
,table_catalog
,table_schema
,table_name
,string_agg(privilege_type, ', ' ORDER BY privilege_type) AS privileges
FROM information_schema.role_table_grants
WHERE grantee != 'postgres'
-- and table_catalog = 'somedatabase' /* uncomment line to filter database */
-- and table_schema = 'someschema' /* uncomment line to filter schema */
-- and table_name = 'sometable' /* uncomment line to filter table */
GROUP BY 1, 2, 3, 4;
Sample output:
grantee |table_catalog |table_schema |table_name |privileges |
--------|----------------|--------------|---------------|---------------|
PUBLIC |adventure_works |pg_catalog |pg_sequence |SELECT |
PUBLIC |adventure_works |pg_catalog |pg_sequences |SELECT |
PUBLIC |adventure_works |pg_catalog |pg_settings |SELECT, UPDATE |
...
Something like this?
SELECT yourtable.id, rev, content
FROM yourtable
INNER JOIN (
SELECT id, max(rev) as maxrev
FROM yourtable
GROUP BY id
) AS child ON (yourtable.id = child.id) AND (yourtable.rev = maxrev)
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
When you use setcookie
, you can either set the expiration time to 0
or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).
If you are using underscoreJs then you can simply use _.isEqual function and it compares all keys and values at each and every level of hierarchy like below example.
var object = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};
var object1 = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};
console.log(_.isEqual(object, object1));//return true
If all the keys and values for those keys are same in both the objects then it will return true, otherwise return false.
In Java 9 you have the even more elegant solution of using immutable lists via the new convenience factory method List.of
:
List<String> immutableList = List.of("one","two","three");
(shamelessly copied from here )
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
Get second, third, fourth......Nth highest salary using following query
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP N salary FROM employees ORDER BY salary DESC)
Replace N by you number i.e. N=2 for second highest salary, N=3 for third highest salary and so on. So for second highest salary use
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP 2 salary FROM employees ORDER BY salary DESC)
If you are on mac machine and had installed nginx using
brew install nginx
then
brew services list
is the command for you. This will return a list of services installed via brew and their corresponding status.
There is no need to unpack the JAR (if one of the class names is known or is looked up e.g. using 7zip), so on Windows the following would be sufficient:
javap -cp log4j-core-2.5.jar -verbose org.apache.logging.log4j.core.Logger | findstr major
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
int
, when holding numbers.int
is too small, use a long
long
is too small, use BigInteger
Collection
, handling null
, ...) use Integer
/Long
insteadOne, albeit a clumsy option to rearrange the columns when the column order must absolutely be changed, and foreign keys are in use, is to first dump the entire database with data, then dump just the schema (pg_dump -s databasename > databasename_schema.sql
). Next edit the schema file to rearrange the columns as you would like, then recreate the database from the schema, and finally restore the data into the newly created database.
It seems no clear document talking on the Gemfile.lock
format. Maybe it's because Gemfile.lock
is just used by bundle internally.
However, since Gemfile.lock
is a snapshot of Gemfile
, which means all its information should come from Gemfile
(or from default value if not specified in Gemfile
).
For GEM
, it lists all the dependencies you introduce directly or indirectly in the Gemfile
. remote
under GEM
tells where to get the gems, which is specified by source in Gemfile
.
If a gem is not fetch from remote
, PATH
tells the location to find it. PATH
's info comes from path in Gemfile
when you declare a dependency.
And PLATFORM
is from here.
For DEPENDENCIES
, it's the snapshot of dependencies resolved by bundle.
<?php
$to1 = '[email protected]';
$subject = 'Tester subject';
// To send HTML mail, the Content-type header must be set
$headers .= "Reply-To: The Sender <[email protected]>\r\n";
$headers .= "Return-Path: The Sender <[email protected]>\r\n";
$headers .= "From: [email protected]" ."\r\n" .
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>
You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation
They use JQuery validation.
jquery.validate.js
jquery.validate.min.js
jquery-1.7.1.min.js
And you'll get the source code there.
<form id="registration-form" class="form-horizontal">
<h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
<div class="form-control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">User Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="username" id="username"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="password" id="password">
</div>
</div>
<div class="form-control-group">
<label class="control-label" for="name"> Retype Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message">Your Address</label>
<div class="controls">
<textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
<input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success btn-large">Register</button>
<button type="reset" class="btn">Cancel</button></div>
</form>
And The JQuery :
<script src="assets/js/jquery-1.7.1.min.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<script src="script.js"></script>
<script>
addEventListener('load', prettyPrint, false);
$(document).ready(function(){
$('pre').addClass('prettyprint linenums');
});
Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/
Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/
happy coding.
You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...
<input type="text" id="@strElementID" class="@strCSSClass" />
If strCSSClass is null then the class attribute won't render at all.
SSSHHH...don't tell. :)
I got same error before,
type this query in your database CREATE SEQUENCE hibernate_sequence START WITH 1 INCREMENT BY 1 NOCYCLE;
that's work for me, good luck ~
Add following @IBInspectables in UIView extension
extension UIView {
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set(newValue) {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(CGColor: color)
}
return nil
}
set(newValue) {
layer.borderColor = newValue?.CGColor
}
}
}
And then you should be able to set borderColor and borderWidth attributes directly from Attribute inspector. See attached image
As of C# 6 you can declare and initialise a 'read-only auto-property' in one line:
double FuelConsumption { get; } = 2;
You can set the value from the constructor but not other methods.
If you are using conda
or pip
to install modules you can use
pip list
or
conda list
to display all the modules. This will display all the modules in the terminal itself and is much faster than
>>> help('modules')
Disabling pyright worked perfectly for me on VS.
You can implement your own modulus function to do that for you:
double dmod(double x, double y) {
return x - (int)(x/y) * y;
}
Then you can simply use dmod(6.3, 2)
to get the remainder, 0.3
.
The WHERE
clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY
. It must come before the GROUP BY
in the query, and acts as a filter before things are SUM
med, which is how most of the answers here work.
You should also be aware of the optional HAVING
clause which must come after the GROUP BY
. This can be used to filter on the resulting properties of groups after GROUP
ing - for instance HAVING SUM(Amount) > 0
The documentation says
The output format of the date/time types can be set to one of the four styles ISO 8601, SQL (Ingres), traditional POSTGRES (Unix date format), or German. The default is the ISO format.
So this particular format can be controlled with postgres
date time output, eg:
t=# select now();
now
-------------------------------
2017-11-29 09:15:25.348342+00
(1 row)
t=# set datestyle to DMY, SQL;
SET
t=# select now();
now
-------------------------------
29/11/2017 09:15:31.28477 UTC
(1 row)
t=# select now()::date;
now
------------
29/11/2017
(1 row)
Mind that as @Craig mentioned in his answer, changing datestyle
will also (and in first turn) change the way postgres parses date.
I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:
class Container extends React.Component {
constructor(props) {
super(props)
this.setRef = this.setRef.bind(this)
}
setRef(node) {
this.childRef = node
}
render() {
return <Child setRef={ this.setRef }/>
}
}
const Child = ({ setRef }) => (
<div ref={ setRef }>
</div>
)
Here's an example of doing this with a modal:
class Container extends React.Component {
constructor(props) {
super(props)
this.state = {
modalOpen: false
}
this.open = this.open.bind(this)
this.close = this.close.bind(this)
this.setModal = this.setModal.bind(this)
}
open() {
this.setState({ open: true })
}
close(event) {
if (!this.modal.contains(event.target)) {
this.setState({ open: false })
}
}
setModal(node) {
this.modal = node
}
render() {
let { modalOpen } = this.state
return (
<div>
<button onClick={ this.open }>Open</button>
{
modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
}
</div>
)
}
}
const Modal = ({ close, setModal }) => (
<div className='modal' onClick={ close }>
<div className='modal-window' ref={ setModal }>
</div>
</div>
)
I had this problem and all I had to do is return true
from touchend and the warning went away.
Try binding your DataGridView
to the DefaultView
of the DataTable
:
dataGridView1.DataSource = table.DefaultView;
What worked for me:
ThirdParty
.ThirdParty
folder both DocumentFormat.OpenXML.dll
and WindowsBase.dll
ThirdParty
dir as reference for both the DLLs No, you can't do this using Javascript alone. Client-side Javascript cannot read the contents of a directory the way I think you're asking about.
However, if you're able to add an index page to (or configure your web server to show an index page for) the images directory and you're serving the Javascript from the same server then you could make an AJAX call to fetch the index and then parse it.
i.e.
1) Enable indexes in Apache for the relevant directory on yoursite.com:
http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/
2) Then fetch / parse it with jQuery. You'll have to work out how best to scrape the page and there's almost certainly a more efficient way of fetching the entire list, but an example:
$.ajax({
url: "http://yoursite.com/images/",
success: function(data){
$(data).find("td > a").each(function(){
// will loop through
alert("Found a file: " + $(this).attr("href"));
});
}
});
String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
String[] value_split = rat_values.split("\\|");
for (String string : value_split) {
System.out.println(string);
}
Do same as you did in file1.c In file2.c:
#include <stdio.h>
extern int i; /*This declare that i is an int variable which is defined in some other file*/
int main(void)
{
/* your code*/
If you use int i; in file2.c under main() then i will be treated as local auto variable not the same as defined in file1.c
Try the following:
<script type="text/javascript">
// Use any event to append the code
$(document).ready(function()
{
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://scriptlocation/das.js";
// Use any selector
$("head").append(s);
});
As for your last question, here's the problem illustrated with a simple example:
Let's say that your list contains 5 elements: list = [1, 2, 3, 4, 5]
and your list of items to remove (i.e. the indices) is indices_to_remove = [0, 2, 4]
. In the first iteration of the loop you remove the item at index 0, so your list becomes list = [2, 3, 4, 5]
. In the second iteration, you remove the item at index 2, so your list becomes list = [2, 3, 5]
(as you can see, this removes the wrong element). Finally, in the third iteration, you try to remove the element at index 4, but the list only contains three elements, so you get an out of bounds exception.
Now that you see what the problem is, hopefully you will be able to come up with a solution. Good luck!
Log location:
${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log
Get log as a text and save to workspace:
cat ${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log >> log.txt
In my case, this error popped up not because of duplicate values, but because I attempted to join a shorter Series to a Dataframe: both had the same index, but the Series had fewer rows (missing the top few). The following worked for my purposes:
df.head()
SensA
date
2018-04-03 13:54:47.274 -0.45
2018-04-03 13:55:46.484 -0.42
2018-04-03 13:56:56.235 -0.37
2018-04-03 13:57:57.207 -0.34
2018-04-03 13:59:34.636 -0.33
series.head()
date
2018-04-03 14:09:36.577 62.2
2018-04-03 14:10:28.138 63.5
2018-04-03 14:11:27.400 63.1
2018-04-03 14:12:39.623 62.6
2018-04-03 14:13:27.310 62.5
Name: SensA_rrT, dtype: float64
df = series.to_frame().combine_first(df)
df.head(10)
SensA SensA_rrT
date
2018-04-03 13:54:47.274 -0.45 NaN
2018-04-03 13:55:46.484 -0.42 NaN
2018-04-03 13:56:56.235 -0.37 NaN
2018-04-03 13:57:57.207 -0.34 NaN
2018-04-03 13:59:34.636 -0.33 NaN
2018-04-03 14:00:34.565 -0.33 NaN
2018-04-03 14:01:19.994 -0.37 NaN
2018-04-03 14:02:29.636 -0.34 NaN
2018-04-03 14:03:31.599 -0.32 NaN
2018-04-03 14:04:30.779 -0.33 NaN
2018-04-03 14:05:31.733 -0.35 NaN
2018-04-03 14:06:33.290 -0.38 NaN
2018-04-03 14:07:37.459 -0.39 NaN
2018-04-03 14:08:36.361 -0.36 NaN
2018-04-03 14:09:36.577 -0.37 62.2
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
If you have a form action and an input type="submit"
inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
List<Person> list = new ArrayList<Person>();
Criteria criteria = this.getSessionFactory().getCurrentSession().createCriteria(Person.class);
for (final Object o : criteria.list()) {
list.add((Person) o);
}
You can use Guava's Strings.repeat method:
String existingString = ...
existingString += Strings.repeat("foo", n);
I was searching after a toggling method that does the same, except for an inital value of null
or undefined
, where it should become false
.
Here it is:
booly = !(booly != false)
Today 2020.12.04 I perform tests on MacOs HighSierra 10.13.6 on Chrome v86, Safari v13.1.2 and Firefox v83 for chosen solutions.
For all browsers
length
(B) is fastest for small arrays, and in Firefox for big too and for Chrome and Safari is fastpush
(A) is fastest for big arrays on Chrome and Safari, and fast for Firefox and small arraysI perform 2 tests cases:
Below snippet presents differences between solutions A, B, C, D, E, F
PS: Answer B was deleted - but actually it was the first answer which use this technique so if you have access to see it please click on "undelete".
// https://stackoverflow.com/a/6254088/860099
function A(a,o) {
a.push(o);
return a;
}
// https://stackoverflow.com/a/47506893/860099
function B(a,o) {
a[a.length] = o;
return a;
}
// https://stackoverflow.com/a/6254088/860099
function C(a,o) {
return a.concat(o);
}
// https://stackoverflow.com/a/50933891/860099
function D(a,o) {
return [...a,o];
}
// https://stackoverflow.com/a/42428064/860099
function E(a,o) {
const frozenObj = Object.freeze(o);
return Object.freeze(a.concat(frozenObj));
}
// https://stackoverflow.com/a/6254088/860099
function F(a,o) {
a.unshift(o);
return a;
}
// -------
// TEST
// -------
[A,B,C,D,E,F].map(f=> {
console.log(`${f.name} ${JSON.stringify(f([1,2],{}))}`)
})
_x000D_
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
GameBoard is control of type DataGridView; The image should be type of PNG with transparent alpha channel background;
Image test = Properties.Resources.checker_black;
PictureBox b = new PictureBox();
b.Parent = GameBoard;
b.Image = test;
b.Width = test.Width*2;
b.Height = test.Height*2;
b.Location = new Point(0, 90);
b.BackColor = Color.Transparent;
b.BringToFront();
Just add background-attachment to your code
body {
background-position: center;
background-image: url(../images/images5.jpg);
background-attachment: fixed;
}
Have you tried using dictionary comprehension with dictionary mapping:
a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}
c = {**a, **b}
# c = {"a": 1, "b": 2, "c": 3, "d": 4}
Another way of doing is by Using dict(iterable, **kwarg)
c = dict(a, **b)
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
In Python 3.9 you can add two dict using union | operator
# use the merging operator |
c = a | b
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
SO in fact that you are using excel means that you can use the SpreadSheet Compare from Microsoft. It is available from Office 2013. Yes i know this question is older then 6 years. But who knows maybe someone need this information today.
using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
namespace Encription
{
class CryptorEngine
{
public static string Encrypt(string ToEncrypt, bool useHasing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);
//System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string Key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
hashmd5.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tDes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string cypherString, bool useHasing)
{
byte[] keyArray;
byte[] toDecryptArray = Convert.FromBase64String(cypherString);
//byte[] toEncryptArray = Convert.FromBase64String(cypherString);
//System.Configuration.AppSettingsReader settingReader = new AppSettingsReader();
string key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateDecryptor();
try
{
byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
tDes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<IF>
<CONDITIONS>
<CONDITION field="time" from="5pm" to="9pm"></CONDITION>
</CONDITIONS>
<RESULTS><...some actions defined.../></RESULTS>
<ELSE>
<RESULTS><...some other actions defined.../></RESULTS>
</ELSE>
</IF>
Here's my take on it. This will allow you to have multiple conditions.
I know this is old, but it is actually very possible.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server
in "SFTP Server" (note this path might be different in your system)
Save and connect
Default options are read from the following files in the given order:
/etc/mysql/my.cnf
/etc/my.cnf
~/.my.cnf
I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
You would have to tune it according to your environment.
Sometimes it's more useful to increase the size of the backlog (acceptCount) instead of the maximum number of threads.
Say, instead of
<Connector ... maxThreads="500" acceptCount="50"
you use
<Connector ... maxThreads="300" acceptCount="150"
you can get much better performance in some cases, cause there would be less threads disputing the resources and the backlog queue would be consumed faster.
In any case, though, you have to do some benchmarks to really know what is best.
console.log(typeof json_data !== 'undefined'
? json_data.length : 'There is no spoon.');
...or more simply...
console.log(json_data ? json_data.length : 'json_data is null or undefined');
XAML ListBox Scroller - Windows 10(UWP)
<Style TargetType="ListBox">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Visible"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible"/>
</Style>
http://rusanu.com/2006/01/30/how-long-should-i-expect-alter-databse-set-enable_broker-to-run/
alter database [<dbname>] set enable_broker with rollback immediate;
Stored Procedure for find text in SP.. {Dinesh Baskaran} Trendy Global Systems pvt ltd
create Procedure [dbo].[TextFinder]
(@Text varchar(500),@Type varchar(2)=NULL)
AS
BEGIN
SELECT DISTINCT o.name AS ObjectName,
CASE o.xtype
WHEN 'C' THEN 'CHECK constraint '
WHEN 'D' THEN 'Default or DEFAULT constraint'
WHEN 'F' THEN 'FOREIGN KEY constraint'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY or UNIQUE constraint'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure'
WHEN 'S' THEN 'System table'
WHEN 'TF' THEN 'Table function'
WHEN 'TR' THEN 'Trigger'
WHEN 'U' THEN 'User table'
WHEN 'V' THEN 'View'
WHEN 'X' THEN 'Extended stored procedure'
ELSE o.xtype
END AS ObjectType,
ISNULL( p.Name, '[db]') AS Location
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
LEFT JOIN sysobjects p ON o.Parent_obj=p.id
WHERE c.text LIKE '%' + @Text + '%' and
o.xtype = case when @Type IS NULL then o.xtype else @Type end
ORDER BY Location, ObjectName
END
If someone is looking for a PHP solution see "PHP_MySQL_wrapper":
$db = new MySQL_wrapper(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect();
// this sample gets column names from first row of file
//$db->createTableFromCSV('test_files/countrylist.csv', 'csv_to_table_test');
// this sample generates column names
$db->createTableFromCSV('test_files/countrylist1.csv', 'csv_to_table_test_no_column_names', ',', '"', '\\', 0, array(), 'generate', '\r\n');
/** Create table from CSV file and imports CSV data to Table with possibility to update rows while import.
* @param string $file - CSV File path
* @param string $table - Table name
* @param string $delimiter - COLUMNS TERMINATED BY (Default: ',')
* @param string $enclosure - OPTIONALLY ENCLOSED BY (Default: '"')
* @param string $escape - ESCAPED BY (Default: '\')
* @param integer $ignore - Number of ignored rows (Default: 1)
* @param array $update - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
* @param string $getColumnsFrom - Get Columns Names from (file or generate) - this is important if there is update while inserting (Default: file)
* @param string $newLine - New line delimiter (Default: \n)
* @return number of inserted rows or false
*/
// function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = '\r\n')
$db->close();
You can disable the app using enable maintenance mode from the admin panel.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
You're looking for calls to sys.exit()
in the script. The argument to that method is returned to the environment as the exit code.
It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.
You can change the port number:
Open the server tab in eclipse -> right click open click on open---->you can change the port number.
Run the application with http://localhost:8080/Applicationname
it will give output and also check http://localhost:8080/Applicationname/index.jsp
Modified from Mr ChuckBevitt
Working solution:
string CSVFilePathName = APP_PATH + "Facilities.csv";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols-1; i++)
dt.Columns.Add(Fields[i].ToLower(), typeof(string));
DataRow Row;
for (int i = 0; i < Lines.GetLength(0)-1; i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols-1; f++)
Row[f] = Fields[f];
dt.Rows.Add(Row);
}
You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use
if (count % 5 == 4)
The port 8005 is used as service port. You can send a shutdown command (a configurable password) to that port. It will not "speak" HTTP, so you cannot use your browser to connect.
The default port for delivering web-content is 8080.
But there may be other applications listen to that port. So your tomcat may not start, if the port is not available.
You asked "How do you know, if tomcat server is installed on your PC?". The answer to that question is: You can't
You can't determine, if it is installed, because it may be only extracted from a ZIP archive or packaged within another application (Like JBoss AS (I think)).
There is another option to do the type check.
For example:
n = 14
if type(n)==int:
return "this is an int"
If we have parameter like below in our POM XML
<version>${project.version}.${svn.version}</version>
<packaging>war</packaging>
I run maven command line as follows :
mvn clean install package -Dproject.version=10 -Dsvn.version=1
<v-layout justify-center>
<v-card-actions>
<v-btn primary>
<span>SignUp</span>
</v-btn>`enter code here`
</v-card-actions>
</v-layout>
As dfsq said i just had to use removeClass("hide")
instead of toggle()
You can try
document.getElementById("textboxid").readOnly = true;
Actually, you could still use the round function:
>>> print round(1123.456789, -1)
1120.0
This would round to the closest multiple of 10. To 100 would be -2 as the second argument and so forth.
You have a couple of options here, I think.
One would be to use a BackgroundWorker. This is a common helper for multithreading in applications. It exposes a DoWork event which is handled on a background thread from the Thread Pool and a RunWorkerCompleted event which is invoked back on the main thread when the background thread completes. It also has the benefit of try/catching the code running on the background thread so that an unhandled exception doesn't kill the application.
If you don't want to go that route, you can use the WPF dispatcher object to invoke an action to update the GUI back onto the main thread. Random reference:
http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher
There are many other options around too, but these are the two most common that come to mind.
You Can try This To Run Command Then cmd
Exits
Process.Start("cmd", "/c YourCode")
You Can try This To Run The Command And Let cmd
Wait For More Commands
Process.Start("cmd", "/k YourCode")
In MySQL, certain words like SELECT
, INSERT
, DELETE
etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("
`
"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
You have two options.
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`
) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT); ERROR 1064 (42000): You have an error in your SQL syntax. near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key
in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^
Use the WScript.Shell instead, because it has a waitOnReturn
option:
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn
(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
You can open the background page's console if you click on the "background.html" link in the extensions list.
To access the background page that corresponds to your extensions open Settings / Extensions
or open a new tab and enter chrome://extensions
. You will see something like this screenshot.
Under your extension click on the link background page
. This opens a new window.
For the context menu sample the window has the title: _generated_background_page.html
.
I would suggest using the JSONParser
class. It's very easy to use.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws IOException {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (Exception ex) {
Log.d("Networking", ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Then in your application, create an instance of this class. You may want to pass the constructor 'GET' or 'POST' if desired.
public JSONParser jsonParser = new JSONParser();
try {
// Building Parameters ( you can pass as many parameters as you want)
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("age", 25));
// Getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(YOUR_URL, "POST", params);
} catch (JSONException e) {
e.printStackTrace();
}
pt_kill
has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel
for a hint of how to come close with cron
.
Swift 4 - you can manage height with HEIGHT_VIEW,Just add this cods, Its working
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let HEIGHT_VIEW = 60
tableView.tableFooterView?.frame.size = CGSize(width: tblView.frame.width, height: CGFloat(HEIGHT_VIEW))
tableView.tableHeaderView?.frame.size = CGSize(width:tblView.frame.width, height: CGFloat(HEIGHT_VIEW))
}