If you have tow classes Product
and Customer
and we want to remove duplicate items from their list
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string CustomerName { get; set; }
}
You must define a generic class in the form below
public class ItemEqualityComparer<T> : IEqualityComparer<T> where T : class
{
private readonly PropertyInfo _propertyInfo;
public ItemEqualityComparer(string keyItem)
{
_propertyInfo = typeof(T).GetProperty(keyItem, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
}
public bool Equals(T x, T y)
{
var xValue = _propertyInfo?.GetValue(x, null);
var yValue = _propertyInfo?.GetValue(y, null);
return xValue != null && yValue != null && xValue.Equals(yValue);
}
public int GetHashCode(T obj)
{
var propertyValue = _propertyInfo.GetValue(obj, null);
return propertyValue == null ? 0 : propertyValue.GetHashCode();
}
}
then, You can remove duplicate items in your list.
var products = new List<Product>
{
new Product{ProductName = "product 1" ,Id = 1,},
new Product{ProductName = "product 2" ,Id = 2,},
new Product{ProductName = "product 2" ,Id = 4,},
new Product{ProductName = "product 2" ,Id = 4,},
};
var productList = products.Distinct(new ItemEqualityComparer<Product>(nameof(Product.Id))).ToList();
var customers = new List<Customer>
{
new Customer{CustomerName = "Customer 1" ,Id = 5,},
new Customer{CustomerName = "Customer 2" ,Id = 5,},
new Customer{CustomerName = "Customer 2" ,Id = 5,},
new Customer{CustomerName = "Customer 2" ,Id = 5,},
};
var customerList = customers.Distinct(new ItemEqualityComparer<Customer>(nameof(Customer.Id))).ToList();
this code remove duplicate items by Id
if you want remove duplicate items by other property, you can change nameof(YourClass.DuplicateProperty)
same nameof(Customer.CustomerName)
then remove duplicate items by CustomerName
Property.
itoa
or itof
functions because they are non-standard and therefore not portable.Use string streams
#include <sstream> //include this to use string streams
#include <string>
int main()
{
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
}
Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout
std::ostringstream ostr;
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
You can use stream manipulators, such as std::endl
, std::hex
and functions std::setw()
, std::setprecision()
etc. with string streams in exactly the same manner as with cout
Do not confuse std::ostringstream
with std::ostrstream
. The latter is deprecated
Use boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.
Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
}
The most lightweight option, inherited from C, is the functions atoi
(for integers (alphabetical to integer)) and atof
(for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *
) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.
#include <cstdlib> //the standard C library header
#include <string>
int main()
{
std::string si = "12";
std::string sf = "1.2";
int i = atoi(si.c_str()); //the c_str() function "converts"
double f = atof(sf.c_str()); //std::string to const char*
}
Use string streams (this time input string stream, istringstream
). Again, istringstream is used just like cin
. Again, do not confuse istringstream
with istrstream
. The latter is deprecated.
#include <sstream>
#include <string>
int main()
{
std::string inputString = "1234 12.3 44";
std::istringstream istr(inputString);
int i1, i2;
float f;
istr >> i1 >> f >> i2;
//i1 is 1234, f is 12.3, i2 is 44
}
Use boost lexical cast.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
std::string sf = "42.2";
std::string si = "42";
float f = boost::lexical_cast<float>(sf); //f is 42.2
int i = boost::lexical_cast<int>(si); //i is 42
}
In case of a bad input, lexical_cast
throws an exception of type boost::bad_lexical_cast
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
In your component.ts
import { Component } from '@angular/core';
@Component({
...
})
export class AppComponent {
...
goToSpecificUrl(url): void {
window.location.href=url;
}
gotoGoogle() : void {
window.location.href='https://www.google.com';
}
}
In your component.html
<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>
<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**
The easiest would be to locate the bootstrap file (bootstrap.css OR bootstrap.min.css) and read through the docblock, you'll see something like this
Bootstrap v3.3.6 (http://getbootstrap.com)
On Red Hat this worked for me:
export TERM=xterm
further info here: http://www.cloudfarm.it/fix-error-opening-terminal-xterm-256color-unknown-terminal-type/
There was a recent thread about this subject on the node.js mailing list. The short answer is no, it's currently not possible auto-reload required files, but several people have developed patches that add this feature.
For anyone looking to activate a views tap gesture recognizer without having direct access to the gesture recognizer... when returning to a page I had to fill bubbles that were previously filled by tapping. I kept track of those bubbles tags (bubs) ...
func fillBubs(bubs: [Int]) {
for bub in bubs {
let bubble = view.viewWithTag(bub)
if bubble == nil {continue}
for g in bubble!.gestureRecognizers! {
let tap = g as! UITapGestureRecognizer
handleBub(tap)
}
}
}
@objc func handleBub(_ sender: UITapGestureRecognizer? = nil) {
let bubble = sender?.view!
bubble?.layer.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
}
Well, I faced a similar problem but on unit tests.
Using SharpTestsEx you can check if a property existis. I use this testing my controllers, because since the JSON object is dynamic, someone can change the name and forget to change it in the javascript or something, so testing for all properties when writing the controller should increase my safety.
Example:
dynamic testedObject = new ExpandoObject();
testedObject.MyName = "I am a testing object";
Now, using SharTestsEx:
Executing.This(delegate {var unused = testedObject.MyName; }).Should().NotThrow();
Executing.This(delegate {var unused = testedObject.NotExistingProperty; }).Should().Throw();
Using this, i test all existing properties using "Should().NotThrow()".
It's probably out of topic, but can be usefull for someone.
If you're looking for a file to use in httpd-ssl.conf as a value for SSLCertificateKeyFile, a PEM file should work just fine.
See this SO question/answer for more details on the SSL options in that file.
All of the instances installed should show up in the Services Snap-In in the Microsoft Management Console. To get the instance names, go to Start | Run | type Services.msc and look for all entries with "Sql Server (Instance Name)".
$(function () {
$("#txtSearch").keyup(function (event) {
var txt = $("#txtSearch").val()
if (txt.length > 3) {
$("span.hilightable").each(function (i, v) {
v.innerHTML = v.innerText.replace(txt, "<hilight>" + txt + "</hilight>");
});
}
});
});
Jfiddle here
You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options. For more info visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));
Do not use Math.Pow
When i use
for (int i = 0; i < 10e7; i++)
{
var x3 = x * x * x;
var y3 = y * y * y;
}
It only takes 230 ms whereas the following takes incredible 7050 ms:
for (int i = 0; i < 10e7; i++)
{
var x3 = Math.Pow(x, 3);
var y3 = Math.Pow(x, 3);
}
That introduces a new dependency of having an extra context for starters, but going forward the user database tables change (3 times in the past 2 years) but the API is consistent. For example the users
table is now called AspNetUsers
in Identity Framework, and the names of several primary key fields kept changing, so the code in several answers will no longer work as-is.
Another problem is that the underlying OWIN access to the database will use a separate context, so changes from separate SQL access can produce invalid results (e.g. not seeing changes made to the database). Again the solution is to work with the supplied API and not try to work-around it.
The correct way to access the current user object in ASP.Net identity (as at this date) is:
var user = UserManager.FindById(User.Identity.GetUserId());
or, if you have an async action, something like:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
FindById
requires you have the following using statement so that the non-async UserManager
methods are available (they are extension methods for UserManager, so if you do not include this you will only see FindByIdAsync
):
using Microsoft.AspNet.Identity;
If you are not in a controller at all (e.g. you are using IOC injection), then the user id is retrieved in full from:
System.Web.HttpContext.Current.User.Identity.GetUserId();
If you are not in the standard Account controller you will need to add the following (as an example) to your controller:
/// <summary>
/// Application DB context
/// </summary>
protected ApplicationDbContext ApplicationDbContext { get; set; }
/// <summary>
/// User manager - attached to application DB context
/// </summary>
protected UserManager<ApplicationUser> UserManager { get; set; }
this.ApplicationDbContext = new ApplicationDbContext();
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
Update March 2015
Note: The most recent update to Identity framework changes one of the underlying classes used for authentication. You can now access it from the Owin Context of the current HttpContent.
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
When using EF and Identity Framework with Azure, over a remote database connection (e.g. local host testing to Azure database), you can randomly hit the dreaded “error: 19 - Physical connection is not usable”. As the cause is buried away inside Identity Framework, where you cannot add retries (or what appears to be a missing .Include(x->someTable)
), you need to implement a custom SqlAzureExecutionStrategy
in your project.
It's also cleaner to use @JoinTable
when an Entity could be the child in several parent/child relationships with different types of parents. To follow up with Behrang's example, imagine a Task can be the child of Project, Person, Department, Study, and Process.
Should the task
table have 5 nullable
foreign key fields? I think not...
Set the parent div as position:relative
and the inner element to position:absolute; bottom:0
For those looking for an alias that works with git pull
, this is what I use:
alias up="git branch | awk '/^\\* / { print \$2 }' | xargs -I {} git branch --set-upstream-to=origin/{} {}"
Now whenever you get:
$ git pull
There is no tracking information for the current branch.
...
Just run:
$ up
Branch my_branch set up to track remote branch my_branch from origin.
$ git pull
And you're good to go
I even run the command prompt as Administrator but it didn't work for me with the below error.
'keytool' is not recognized as an internal or external command,
operable program or batch file.
If the path to the keytool is not in your System paths then you will need to use the full path to use the keytool, which is
C:\Program Files\Java\jre<version>\bin
So, the command should be like
"C:\Program Files\Java\jre<version>\bin\keytool.exe" -importcert -alias certificateFileAlias -file CertificateFileName.cer -keystore cacerts
that worked for me.
Another way round it would be to stop UAC then restart it. Create a CMD file with the following code;
Rem Stop UAC %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f rem force reboot Start ShutDown /R /F /T 30
You'll need to right click on the CMD file and use run as admin. once you have finished what you are doing restart UAC with the following code (no need to use run as admin this time);
%windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f
rem force reboot Start ShutDown /R /F /T 30
The down sides to using this method is have to right click and use run as admin to close UAC down and you have to reboot for it to take effect.
BTW there are several reasons why you would need to write to the forbidden areas...the first two that springs to mind would be to run a batch file to append host to prevent your browser going to dodgy sites or to copy license keys in a silent install.
The solution is very simple and worked for me.
Try this :
git pull --rebase <url>
then
git push -u origin master
The same will happen if your published version is not the same as the version you're testing on your phone.
For example, uploaded version is android:versionCode="1"
, and the version you're testing on your phone is android:versionCode="2"
For Windows, you can use winsound. It's built in
import winsound
winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
You should be able to use ossaudiodev for linux:
from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('tada.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
from sys import byteorder
if byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()
(Credit for ossaudiodev: Bill Dandreta http://mail.python.org/pipermail/python-list/2004-October/288905.html)
Trying with a different version of gcc worked for me - gcc 4.9 in my case.
If you want to compare file in your project/directory with an external file (which is by the way the most common way I used to compare files) you can easily drag and drop the external file into the editor's tab and just use the command: "Compare Active File With..." on one of them selecting the other one in the newly popped up choice window. That seems to be the fastest way.
Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.
What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n
children, that state should be "owned" by whatever contains your component. eg:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
Go to https://login.windows.net/YOURDIRECTORYNAME.onmicrosoft.com/.well-known/openid-configuration and you'll see a bunch of URLs containing your tenant ID.
From the mysql documentation version: 8.0.18:
A superuser account 'root'@'localhost'
is created. A password for the superuser is set and stored
in the error log file. To reveal it, use the following command:
shell> sudo grep 'temporary password' /var/log/mysqld.log
Change the root password as soon as possible by logging in with the generated, temporary password
and set a custom password for the superuser account:
shell> mysql -uroot -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass4!';
In my case the suggested file name to be used was jarFile*.jar
in the command line. The file in the folder was jarFile-1.2.3.jar
. So I renamed the file to jarFile
. Then I used jarFile.jar
instead of jarFile*.jar
and then the problem got resolved
var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();
See the google.maps.LatLng docs and google.maps.Marker getPosition()
.
# ------------- SCRIPT ------------- #
#!/bin/bash
echo
echo "# arguments called with ----> ${@} "
echo "# \$1 ----------------------> $1 "
echo "# \$2 ----------------------> $2 "
echo "# path to me ---------------> ${0} "
echo "# parent path --------------> ${0%/*} "
echo "# my name ------------------> ${0##*/} "
echo
exit
# ------------- CALLED ------------- #
# Notice on the next line, the first argument is called within double,
# and single quotes, since it contains two words
$ /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"
# ------------- RESULTS ------------- #
# arguments called with ---> 'hello there' 'william'
# $1 ----------------------> 'hello there'
# $2 ----------------------> 'william'
# path to me --------------> /misc/shell_scripts/check_root/show_parms.sh
# parent path -------------> /misc/shell_scripts/check_root
# my name -----------------> show_parms.sh
# ------------- END ------------- #
Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.
It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).
I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.
All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();
For downloading + documentation see the plugin's page: jQuery: clickable — jLix
Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get
>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160
There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.
If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).
Since vars passed through url are $_GET vars, you can use filter_input()
function:
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$othervar = filter_input(INPUT_GET, 'othervar', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
It would store the values of each var and sanitize/validate them too.
Another approach to solve this, question:
public class CollectionUtils {
/**
* Splits the collection into lists with given batch size
* @param collection to split in to batches
* @param batchsize size of the batch
* @param <T> it maintains the input type to output type
* @return nested list
*/
public static <T> List<List<T>> makeBatch(Collection<T> collection, int batchsize) {
List<List<T>> totalArrayList = new ArrayList<>();
List<T> tempItems = new ArrayList<>();
Iterator<T> iterator = collection.iterator();
for (int i = 0; i < collection.size(); i++) {
tempItems.add(iterator.next());
if ((i+1) % batchsize == 0) {
totalArrayList.add(tempItems);
tempItems = new ArrayList<>();
}
}
if (tempItems.size() > 0) {
totalArrayList.add(tempItems);
}
return totalArrayList;
}
}
As a workaround you can simply make the code receiving the POST respond to application/json data. For PHP I added the code below, allowing me to POST to it in either form-encoded or JSON.
//handles JSON posted arguments and stuffs them into $_POST
//angular's $http makes JSON posts (not normal "form encoded")
$content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
if ($content_type_args[0] == 'application/json')
$_POST = json_decode(file_get_contents('php://input'),true);
//now continue to reference $_POST vars as usual
Warning: This function was REMOVED in PHP 7.0.0.
http://php.net/manual/en/function.mssql-query.php
For anyone still using these mssql_* functions, keep in mind that they have been removed from PHP as of v7.0.0. So, that means you eventually have to rewrite your model code to either use the PDO library, sqlsrv_* etc. If you're looking for something with a "quoting/escaping" method, I would recommend PDO.
Alternatives to this function include: PDO::query(), sqlsrv_query() and odbc_exec()
This will work for a multiple row df having the dataframe as df with the same name of the columns in the df as the db.
tuples = list(df.itertuples(index=False, name=None))
columns_list = df.columns.tolist()
marks = ['?' for _ in columns_list]
columns_list = f'({(",".join(columns_list))})'
marks = f'({(",".join(marks))})'
table_name = 'whateveryouwant'
c.executemany(f'INSERT OR REPLACE INTO {table_name}{columns_list} VALUES {marks}', tuples)
conn.commit()
I've been trying to get my ASP.NET MVC controller to parse some model that i submitted to it using Postman.
I needed the following to get it to work:
controller action
[HttpPost]
[PermitAllUsers]
[Route("Models")]
public JsonResult InsertOrUpdateModels(Model entities)
{
// ...
return Json(response, JsonRequestBehavior.AllowGet);
}
a Models class
public class Model
{
public string Test { get; set; }
// ...
}
headers for Postman's request, specifically, Content-Type
json in the request body
As others have said, you are adding the same key more than once. If this is a NOT a valid scenario, then check Jdinklage Morgoone's answer (which only saves the first value found for a key), or, consider this workaround (which only saves the last value found for a key):
// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];
Otherwise, if it is valid to have multiple values for a single key, then you should consider storing your values in a List<string>
for each string
key.
For example:
var rct3Features = new Dictionary<string, List<string>>();
var rct4Features = new Dictionary<string, List<string>>();
foreach (string line in rct3Lines)
{
string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);
if (!rct3Features.ContainsKey(items[0]))
{
// No items for this key have been added, so create a new list
// for the value with item[1] as the only item in the list
rct3Features.Add(items[0], new List<string> { items[1] });
}
else
{
// This key already exists, so add item[1] to the existing list value
rct3Features[items[0]].Add(items[1]);
}
}
// To display your keys and values (testing)
foreach (KeyValuePair<string, List<string>> item in rct3Features)
{
Console.WriteLine("The Key: {0} has values:", item.Key);
foreach (string value in item.Value)
{
Console.WriteLine(" - {0}", value);
}
}
In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below,
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java
In your case the jsp name is error.jsp so the path should be something like below
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java
in line no 124 you are trying to access a null object which results in null pointer exception.
From Prepared statements and stored procedures
Use bindParam
to insert multiple rows with one time binding:
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
You could create a user form:
With the new feature WindowInsetsCompat
in androidx core release 1.5.0-alpha02 you could check the visibility of the soft keyboard easily as below
Quoting from reddit comment
val View.keyboardIsVisible: Boolean get() = WindowInsetsCompat .toWindowInsetsCompat(rootWindowInsets) .isVisible(WindowInsetsCompat.Type.ime())
Some note about backward compatibility, quoting from release notes
New Features
The
WindowInsetsCompat
APIs have been updated to those in the platform in Android 11. This includes the newime()
inset type, which allows checking the visibility and size of the on-screen keyboard.Some caveats about the
ime()
type, it works very reliably on API 23+ when your Activity is using theadjustResize
window soft input mode. If you’re instead using theadjustPan
mode, it should work reliably back to API 14.
References
I know that this question is pretty old, but I stumbled upon it recently, found a solution that I liked better, and figured I'd share it.
Now that Bootstrap 5 is available, there's a new approach that works similarly to using input-group
s, but looks more like an ordinary form, without any CSS tweaks:
<div class="row g-3 align-items-center">
<div class="col-auto">
<label>Label:</label>
</div>
<div class="col">
<input class="form-control">
</div>
<div class="col-auto">
<button type="button" class="btn btn-primary">Button</button>
</div>
</div>
The col-auto
class makes those columns fit themselves to their contents (the label and the button in this case), and anything with a col
class should be evenly distributed to take up the remaining space.
We strongly recommend that you use a secure app, like Gmail, to access your account. All apps made by Google meet these security standards. Using a less secure app, on the other hand, could leave your account vulnerable. Learn more.
Set
smtp.UseDefaultCredentials = false;
before
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
I am currently running OS X Yosemite Developer Preview 7 and Xcode 6 beta 6 targeting iOS 7.1 and following solution works fine for me:
UINavigationItem
and UIBarButtonItem
sRun following code to remove
[self.navItem setRightBarButtonItem:nil];
[self.navItem setLeftBarButtonItem:nil];
Run following codes to add buttons again
[self.navItem setRightBarButtonItem:deleteItem];
[self.navItem setLeftBarButtonItem:addItem];
I had the same problem. Adding new rows to WPF DataGrid
requires a trick. DataGrid
relies on property fields of an item object. ExpandoObject
enables to add new properties dynamically. The code below explains how to do it:
// using System.Dynamic;
DataGrid dataGrid;
string[] labels = new string[] { "Column 0", "Column 1", "Column 2" };
foreach (string label in labels)
{
DataGridTextColumn column = new DataGridTextColumn();
column.Header = label;
column.Binding = new Binding(label.Replace(' ', '_'));
dataGrid.Columns.Add(column);
}
int[] values = new int[] { 0, 1, 2 };
dynamic row = new ExpandoObject();
for (int i = 0; i < labels.Length; i++)
((IDictionary<String, Object>)row)[labels[i].Replace(' ', '_')] = values[i];
dataGrid.Items.Add(row);
//edit:
Note that this is not the way how the component should be used, however, it simplifies a lot if you have only programmatically generated data (eg. in my case: a sequence of features and neural network output).
Put this right before the closing Body tag at the bottom of the page.
<script>
if (location.hash) {
location.href = location.hash;
}
</script>
jQuery is actually not required.
Another option (to avoid any forced push which can be problematic for other contributors) is to:
master
on origin/master
master
, always keeping commits from the dedicated branch (meaning creating new revisions on top of master
which will mirror your dedicated branch).git merge --strategy=theirs
.That way, you can push master to remote without having to force anything.
I use
android:scaleX="0.70"
android:scaleY="0.70"
to ajust the size of checkbox
then I set margins like this
android:layout_marginLeft="-10dp"
to adjust ths location of the checkbox.
UITableView's selectRowAtIndexPath:animated:scrollPosition: should do the trick.
Just pass UITableViewScrollPositionNone
for scrollPosition and the user won't see any movement.
You should also be able to manually run the action:
[theTableView.delegate tableView:theTableView didSelectRowAtIndexPath:indexPath]
after you selectRowAtIndexPath:animated:scrollPosition:
so the highlight happens as well as any associated logic.
You can use a for
loop:
var found = false;
for (var i = 0; i < categories.length && !found; i++) {
if (categories[i] === "specialword") {
found = true;
break;
}
}
This happens when you move your main class location manually because Netbeans doesn't refresh one of its property files. Open nbproject/project.properties and change the value of main.class to the correct package location.
You can also get a 403 if when testing with dev server you are using integrated pipeline and then install as classic pipeline mode on your live IIS 7.5 web server, also I was missing my app_data folder which also was required
https://docs.python.org/library/os.html
To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.
I use @Thiho answer but i get this error:
'git' is not recognized as an internal or external command
For solving that i use this steps:
I add the following paths to PATH:
C:\Program Files\Git\bin\
C:\Program Files\Git\cmd\
In windows 7:
Finally close and re-open your console.
To pipe the result to the response object (scenarios where there is a need to download the zip rather than store locally)
archive.pipe(res);
Sam's hints for accessing the content of the directory worked for me.
src: ["**/*"]
os.Mkdir
is used to create a single directory. To create a folder path, instead try using:
os.MkdirAll(folderPath, os.ModePerm)
func MkdirAll(path string, perm FileMode) error
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.
Edit:
Updated to correctly use os.ModePerm
instead.
For concatenation of file paths, use package path/filepath
as described in @Chris' answer.
There are two approaches, you can either take exactly one character or strictly one character. When you use exactly, the reader will take only the first character, irrespective of how many characters you input.
For example:
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.findInLine(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
When you give a set of characters as input, say "abcd", the reader will consider only the first character i.e., the letter 'a'
But when you use strictly, the input should be just one character. If the input is more than one character, then the reader will not take the input
import java.util.Scanner;
public class ReaderExample {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(System.in);
char c = reader.next(".").charAt(0);
reader.close();
System.out.print(c);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Suppose you give input "abcd", no input is taken, and the variable c will have Null value.
very clear answer, using just ANGULARJS, no any JQUERY depends
in your html somewhere on the bottom <back-top>some text</back-top>
in your html somewhere on the top <div id="top"></div>
in your js:
/**
* @ngdoc directive
* @name APP.directive:backTop
<pre>
<back-top></back-top>
</pre>
*/
angular
.module('APP')
.directive('backTop', ['$location', '$anchorScroll' ,function($location, $anchorScroll) {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<span class=\'btn btn-mute pull-right\'><i class=\'glyphicon glyphicon-chevron-up\'></i><ng-transclude></ng-transclude></span>',
scope: {
},
link: function(scope, element) {
element.on('click', function(event) {
$anchorScroll(['top']);
});
}
};
}]);
var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
They are exactly the same character. See: http://en.wikipedia.org/wiki/Dash
Barring browser bugs they will display the same in all cases, so the only difference would be concerning code readability, which would point to —
.
Or, if you are using UTF-8 as a charset in your HTML document, you could enter the character directly. That would also display exactly the same.
Had the same problem in Linux. This solved it. (I'm on Debian 9 derived Bunsen Helium)
$ sudo apt-get install python3-tk
Based on the answer by Adam Boduch, I wrote this function which compares two objects in the deepest possible sense, returning paths that have different values as well as paths missing from one or the other object.
The code was not written with efficiency in mind, and improvements in that regard are most welcome, but here is the basic form:
var compare = function (a, b) {
var result = {
different: [],
missing_from_first: [],
missing_from_second: []
};
_.reduce(a, function (result, value, key) {
if (b.hasOwnProperty(key)) {
if (_.isEqual(value, b[key])) {
return result;
} else {
if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {
//dead end.
result.different.push(key);
return result;
} else {
var deeper = compare(a[key], b[key]);
result.different = result.different.concat(_.map(deeper.different, (sub_path) => {
return key + "." + sub_path;
}));
result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {
return key + "." + sub_path;
}));
result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {
return key + "." + sub_path;
}));
return result;
}
}
} else {
result.missing_from_second.push(key);
return result;
}
}, result);
_.reduce(b, function (result, value, key) {
if (a.hasOwnProperty(key)) {
return result;
} else {
result.missing_from_first.push(key);
return result;
}
}, result);
return result;
}
You can try the code using this snippet (running in full page mode is recommended):
var compare = function (a, b) {_x000D_
_x000D_
var result = {_x000D_
different: [],_x000D_
missing_from_first: [],_x000D_
missing_from_second: []_x000D_
};_x000D_
_x000D_
_.reduce(a, function (result, value, key) {_x000D_
if (b.hasOwnProperty(key)) {_x000D_
if (_.isEqual(value, b[key])) {_x000D_
return result;_x000D_
} else {_x000D_
if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {_x000D_
//dead end._x000D_
result.different.push(key);_x000D_
return result;_x000D_
} else {_x000D_
var deeper = compare(a[key], b[key]);_x000D_
result.different = result.different.concat(_.map(deeper.different, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
_x000D_
result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
_x000D_
result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
return result;_x000D_
}_x000D_
}_x000D_
} else {_x000D_
result.missing_from_second.push(key);_x000D_
return result;_x000D_
}_x000D_
}, result);_x000D_
_x000D_
_.reduce(b, function (result, value, key) {_x000D_
if (a.hasOwnProperty(key)) {_x000D_
return result;_x000D_
} else {_x000D_
result.missing_from_first.push(key);_x000D_
return result;_x000D_
}_x000D_
}, result);_x000D_
_x000D_
return result;_x000D_
}_x000D_
_x000D_
var a_editor = new JSONEditor($('#a')[0], {_x000D_
name: 'a',_x000D_
mode: 'code'_x000D_
});_x000D_
var b_editor = new JSONEditor($('#b')[0], {_x000D_
name: 'b',_x000D_
mode: 'code'_x000D_
});_x000D_
_x000D_
var a = {_x000D_
same: 1,_x000D_
different: 2,_x000D_
missing_from_b: 3,_x000D_
missing_nested_from_b: {_x000D_
x: 1,_x000D_
y: 2_x000D_
},_x000D_
nested: {_x000D_
same: 1,_x000D_
different: 2,_x000D_
missing_from_b: 3_x000D_
}_x000D_
}_x000D_
_x000D_
var b = {_x000D_
same: 1,_x000D_
different: 99,_x000D_
missing_from_a: 3,_x000D_
missing_nested_from_a: {_x000D_
x: 1,_x000D_
y: 2_x000D_
},_x000D_
nested: {_x000D_
same: 1,_x000D_
different: 99,_x000D_
missing_from_a: 3_x000D_
}_x000D_
}_x000D_
_x000D_
a_editor.set(a);_x000D_
b_editor.set(b);_x000D_
_x000D_
var result_editor = new JSONEditor($('#result')[0], {_x000D_
name: 'result',_x000D_
mode: 'view'_x000D_
});_x000D_
_x000D_
var do_compare = function() {_x000D_
var a = a_editor.get();_x000D_
var b = b_editor.get();_x000D_
result_editor.set(compare(a, b));_x000D_
}
_x000D_
#objects {} #objects section {_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
#objects section h1 {_x000D_
background: #444;_x000D_
color: white;_x000D_
font-family: monospace;_x000D_
display: inline-block;_x000D_
margin: 0;_x000D_
padding: 5px;_x000D_
}_x000D_
.jsoneditor-outer, .ace_editor {_x000D_
min-height: 230px !important;_x000D_
}_x000D_
button:hover {_x000D_
background: orangered;_x000D_
}_x000D_
button {_x000D_
cursor: pointer;_x000D_
background: red;_x000D_
color: white;_x000D_
text-align: left;_x000D_
font-weight: bold;_x000D_
border: 5px solid crimson;_x000D_
outline: 0;_x000D_
padding: 10px;_x000D_
margin: 10px 0px;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.css" rel="stylesheet" />_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="objects">_x000D_
<section>_x000D_
<h1>a (first object)</h1>_x000D_
<div id="a"></div>_x000D_
</section>_x000D_
<section>_x000D_
<h1>b (second object)</h1>_x000D_
<div id="b"></div>_x000D_
</section>_x000D_
<button onClick="do_compare()">compare</button>_x000D_
<section>_x000D_
<h1>result</h1>_x000D_
<div id="result"></div>_x000D_
</section>_x000D_
</div>
_x000D_
Get these values from attributes:
int[] attrs = new int[] { android.R.attr.textColorSecondary };
TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, attrs);
DEFAULT_TEXT_COLOR = a.getColor(0, Color.RED);
a.recycle();
Here is a different approach with fixed length by base, without RegExp replace lack (based on @bendytree's answer);
function rand(base) {
// default base 10
base = (base >= 2 && base <= 36) ? base : 10;
for (var i = 0, ret = []; i < base; i++) {
ret[i] = ((Math.random() * base) | 0).toString(base)
// include 0-9a-zA-Z?
// [Math.random() < .5 ? 'toString' : 'toUpperCase']();
}
return ret.join('');
}
Why not to combine random.uniform with a list comprehension?
>>> def random_floats(low, high, size):
... return [random.uniform(low, high) for _ in xrange(size)]
...
>>> random_floats(0.5, 2.8, 5)
[2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]
Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:
;WITH DistinctMails AS
(
SELECT ID, MailID, EMailAddress, NAME,
ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'
FROM dbo.YourMailTable
)
SELECT *
FROM DistinctMails
WHERE RowNum = 1
This works on SQL Server 2005 and newer (you didn't mention what version you're using...)
The ContextSwitchDeadlock
doesn't necessarily mean your code has an issue, just that there is a potential. If you go to Debug > Exceptions
in the menu and expand the Managed Debugging Assistants
, you will find ContextSwitchDeadlock
is enabled. If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue.
Also note that the SPOOL
output is driven by a few SQLPlus settings:
SET LINESIZE nn
- maximum line width; if the output is longer it will wrap to display the contents of each result row.
SET TRIMSPOOL OFF|ON
- if set OFF
(the default), every output line will be padded to LINESIZE
. If set ON
, every output line will be trimmed.
SET PAGESIZE nn
- number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.
Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.
um responsive is simple
display:table-cell
max-width:700px
do {display:block; width:100%; clear:both}
and that's it no absolute divs ever; divs needs to be 100% then max-width: - desired width -
for inner framming. A true responsive sites has less than 9 lines of css anything passed that you are in a world of shit and over complicated things.
PS : reset.css
style sheets are what makes css blinds there was a logical reason why they gave default styles in the first place.
Sometimes using
instead of spaces will work. Clearly it has drawbacks, though.
There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.
I can't figure out exactly what's there, yet ...
edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.
A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.
If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od
command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.
Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
recurse-submodules=<check|on-demand>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
So you could push everything in one go with (from the parent repo) a:
git push --recurse-submodules=on-demand
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.
See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe
).
(Merged by Junio C Hamano -- gitster
-- in commit 5d35d72, 21 Dec 2015)
push
: addrecurseSubmodules
config optionThe
--recurse-submodules
command line parameter has existed for some time but it has no config file equivalent.Following the style of the corresponding parameter for
git fetch
, let's inventpush.recurseSubmodules
to provide a default for this parameter.
This also requires the addition of--recurse-submodules=no
to allow the configuration to be overridden on the command line when required.The most straightforward way to implement this appears to be to make
push
use code insubmodule-config
in a similar way tofetch
.
The git config
doc now include:
push.recurseSubmodules
:Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.
- If the value is '
check
', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.- If the value is '
on-demand
' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -- If the value is '
no
' then default behavior of ignoring submodules when pushing is retained.You may override this configuration at time of push by specifying '
--recurse-submodules=check|on-demand|no
'.
So:
git config push.recurseSubmodules on-demand
git push
Git 2.12 (Q1 2017)
git push --dry-run --recurse-submodules=on-demand
will actually work.
See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 12cf113, 16 Dec 2016)
push run with --dry-run
doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.Teach
push
to respect the--dry-run
option when configured to recursively push submodules 'on-demand'.
This is done by passing the--dry-run
flag to the child process which performs a push for a submodules when performing a dry-run.
And still in Git 2.12, you now havea "--recurse-submodules=only
" option to push submodules out without pushing the top-level superproject.
See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 792e22e, 31 Jan 2017)
While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.
Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:
^([A-Z]{3})$
The {3}
indicates that the [A-Z]
must appear exactly 3 times.
By default, inheritance is private. You have to explicitly use public
:
class Bar : public Foo
Rather than keeping the values to be plotted in an array, store them in a matrix. By default the entire matrix will be treated as one data set. However if you add the same number of modifiers to the plot, e.g. the col(), as you have rows in the matrix, R will figure out that each row should be treated independently. For example:
x = matrix( c(21,50,80,41), nrow=2 )
y = matrix( c(1,2,1,2), nrow=2 )
plot(x, y, col("red","blue")
This should work unless your data sets are of differing sizes.
My preferred method is to actually fix the library rather than playing with environment variables that may or may not actually be in scope depending on how the application is run. This is actually a fairly simple process.
First, look at the error output to see where the offending python module is located:
ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/_mysql.so Reason: image not found
Okay, so the offending file is /Library/Python/2.7/site-packages/_mysql.so
Next, figure out where _mysql.so thinks it should find libmysqlclient.18.dylib:
% otool -L /Library/Python/2.7/site-packages/_mysql.so
/Library/Python/2.7/site-packages/_mysql.so:
libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)
So, it's looking for libmysqlclient.18.dylib with no path information, let's fix that:
% sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Library/Python/2.7/site-packages/_mysql.so
Now _mysql.so knows the full path to the library and everything works, regardless of environment variables.
% otool -L /Library/Python/2.7/site-packages/_mysql.so
/Library/Python/2.7/site-packages/_mysql.so:
/usr/local/mysql/lib/libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)
Assuming you only want to disallow strings that match the regex completely (i.e., mmbla
is okay, but mm
isn't), this is what you want:
^(?!(?:m{2}|t)$).*$
(?!(?:m{2}|t)$)
is a negative lookahead; it says "starting from the current position, the next few characters are not mm
or t
, followed by the end of the string." The start anchor (^
) at the beginning ensures that the lookahead is applied at the beginning of the string. If that succeeds, the .*
goes ahead and consumes the string.
FYI, if you're using Java's matches()
method, you don't really need the the ^
and the final $
, but they don't do any harm. The $
inside the lookahead is required, though.
With the Material Components Library you can use the MaterialShapeDrawable
to draw custom shapes.
With a EditText
you can do:
<EditText
android:id="@+id/edittext"
../>
Then create a MaterialShapeDrawable
:
float radius = getResources().getDimension(R.dimen.default_corner_radius);
EditText editText = findViewById(R.id.edittext);
//Apply the rounded corners
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius)
.build();
MaterialShapeDrawable shapeDrawable =
new MaterialShapeDrawable(shapeAppearanceModel);
//Apply a background color
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.white));
//Apply a stroke
shapeDrawable.setStroke(2.0f, ContextCompat.getColor(this,R.color.colorAccent));
ViewCompat.setBackground(editText,shapeDrawable);
It requires the version 1.1.0 of the library.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
Just add one of these two to the src url:
&wmode=Opaque
&wmode=transparent
<iframe id="videoIframe" width="500" height="281" src="http://www.youtube.com/embed/xxxxxx?rel=0&wmode=transparent" frameborder="0" allowfullscreen></iframe>
Here's some sample code for that.
<script>
var param1var = getQueryVariable("param1");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({`enter code here`
url: "TextFile.txt",
dataType: "text",
success: function (data) {
var text = $('#newCheckText').val();
var str = data;
var str_array = str.split('\n');
for (var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
$('#checkboxes').append('<input type="checkbox" class="checkBoxClass" /> ' + str_array[i] + '<br />');
}
}
});
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
});
</script>
</head>
<body>
<div id="checkboxes">
<input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All<br />
</div>
</body>
</html>
Even, I was looking for the same regex but I wanted to include the all special character and blank spaces too. So here is the regex for that:
^[A-Za-z0-9\s$&+,:;=?@#|'<>.^*()%!-]{0,10}$
Why think? If not
confuses you, switch your if and else clauses around to avoid the negation.
i want to make sure that ( u0 <= u < u0+step ) before do sth.
Just write that.
if u0 <= u < u0+step:
"do sth" # What language is "sth"? No vowels. An odd-looking word.
else:
u0 = u0+ step
Why overthink it?
If you need an empty if
-- and can't work out the logic -- use pass
.
if some-condition-that's-too-complex-for-me-to-invert:
pass
else:
do real work here
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if (b1 is null)
return b2 is null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return obj is BOX b2? (length == b2.length &&
breadth == b2.breadth &&
height == b2.height): false;
}
public override int GetHashCode()
{
return (height,length,breadth).GetHashCode();
}
}
just run DBCC useroptions
and you'll get something like this:
Set Option Value
--------------------------- --------------
textsize 2147483647
language us_english
dateformat mdy
datefirst 7
lock_timeout -1
quoted_identifier SET
arithabort SET
ansi_null_dflt_on SET
ansi_warnings SET
ansi_padding SET
ansi_nulls SET
concat_null_yields_null SET
isolation level read committed
All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337
Some snippets from the above link:
"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "
"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."
" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "
Whenever you have to resort to Regex based script tag cleanup. At least add a white-space to the closing tag in the form of
</script\s*>
Otherwise things like
<script>alert(666)</script >
would remain since trailing spaces after tagnames are valid.
take a look at the jQuery Tooltip plugin. You can pass in an options object for different options.
There are also other alternative tooltip plugins available, of which a few are
Take look at the demos and documentation and please update your question if you have specific questions about how to use them in your code.
I had very similar problem today and solution was as it is..
$email = Array("Zaffar Saffee" => "[email protected]");
$schedule->command('cmd:mycmd')
->everyMinute()
->sendOutputTo("/home/forge/dev.mysite.com/storage/logs/cron.log")
->emailWrittenOutputTo($email);
It laravel 5.2 though...
my basic problem was , I was passing string instead of array so, error was
->emailWrittenOutputTo('[email protected]'); // string, we need an array
<a href="1.html"><input type="text" class="button_active" value="1"></a>
<a href="2.html"><input type="text" class="button" value="2"></a>
<a href="3.html"><input type="text" class="button" value="3"></a>
Try that. Unless you truly need to stick with the type as submit, then what I provided should work. If you are going to stick with submit, then everything mentioned above is correct, it makes no sense.
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “@EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
see 15.22.2 of the JLS. For boolean operands, the &
operator is boolean, not bitwise. The only difference between &&
and &
for boolean operands is that for &&
it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).
So in your case, if b
is a primitive, a = a && b
, a = a & b
, and a &= b
all do the same thing.
#!/usr/bin/env node --max-old-space-size=4096 in the ionic-app-scripts.js dint work
Modifying
node_modules/.bin/ionic-app-scripts.cmd
By adding:
@IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0..@ionic\app-scripts\bin\ionic-app-scripts.js" %* ) ELSE ( @SETLOCAL @SET PATHEXT=%PATHEXT:;.JS;=;% node --max_old_space_size=4096 "%~dp0..@ionic\app-scripts\bin\ionic-app-scripts.js" %* )
Worked fianlly
In case when X derives from Y you can also use ToList<T>
method instead of Cast<T>
listOfX.ToList<Y>()
f.write(plaintext)
f.write("\n".encode("utf-8"))
You can try using the below code
NSString *fileName = @"Demo.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
NSLog(@"File path%@",pdfFileName);
Remark: Spark is intended to work on Big Data - distributed computing. The size of the example DataFrame is very small, so the order of real-life examples can be altered with respect to the small ~ example.
Slowest: Method_1, because .describe("A") calculates min, max, mean, stddev, and count (5 calculations over the whole column)
Medium: Method_4, because, .rdd (DF to RDD transformation) slows down the process.
Faster: Method_3 ~ Method_2 ~ method_5, because the logic is very similar, so Spark's catalyst optimizer follows very similar logic with minimal number of operations (get max of a particular column, collect a single-value dataframe); (.asDict() adds a little extra-time comparing 3,2 to 5)
import pandas as pd
import time
time_dict = {}
dfff = self.spark.createDataFrame([(1., 4.), (2., 5.), (3., 6.)], ["A", "B"])
#-- For bigger/realistic dataframe just uncomment the following 3 lines
#lst = list(np.random.normal(0.0, 100.0, 100000))
#pdf = pd.DataFrame({'A': lst, 'B': lst, 'C': lst, 'D': lst})
#dfff = self.sqlContext.createDataFrame(pdf)
tic1 = int(round(time.time() * 1000))
# Method 1: Use describe()
max_val = float(dfff.describe("A").filter("summary = 'max'").select("A").collect()[0].asDict()['A'])
tac1 = int(round(time.time() * 1000))
time_dict['m1']= tac1 - tic1
print (max_val)
tic2 = int(round(time.time() * 1000))
# Method 2: Use SQL
dfff.registerTempTable("df_table")
max_val = self.sqlContext.sql("SELECT MAX(A) as maxval FROM df_table").collect()[0].asDict()['maxval']
tac2 = int(round(time.time() * 1000))
time_dict['m2']= tac2 - tic2
print (max_val)
tic3 = int(round(time.time() * 1000))
# Method 3: Use groupby()
max_val = dfff.groupby().max('A').collect()[0].asDict()['max(A)']
tac3 = int(round(time.time() * 1000))
time_dict['m3']= tac3 - tic3
print (max_val)
tic4 = int(round(time.time() * 1000))
# Method 4: Convert to RDD
max_val = dfff.select("A").rdd.max()[0]
tac4 = int(round(time.time() * 1000))
time_dict['m4']= tac4 - tic4
print (max_val)
tic5 = int(round(time.time() * 1000))
# Method 4: Convert to RDD
max_val = dfff.agg({"A": "max"}).collect()[0][0]
tac5 = int(round(time.time() * 1000))
time_dict['m5']= tac5 - tic5
print (max_val)
print time_dict
Result on an edge-node of a cluster in milliseconds (ms):
small DF (ms) : {'m1': 7096, 'm2': 205, 'm3': 165, 'm4': 211, 'm5': 180}
bigger DF (ms): {'m1': 10260, 'm2': 452, 'm3': 465, 'm4': 916, 'm5': 373}
I thinks it is vary helpful way.
models.py
from django.db import models
class User(models.Model):
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=32)
forms.py
from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
class Meta:
model= User
fields=[
'user_name',
'password'
]
widgets = {
'password': forms.PasswordInput()
}
your code is correct because in some cases it does not work, I also do not know where the error comes from but this can help you solve the problem, move the code in the head of the view like this:
index.cshtml:
@using expert.Models;
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
Manager db = new Manager();
ViewBag.FORM_PRESTATION = new SelectList(db.T_BDE_PRESTATION_PRES.OrderBy(p => p.PRES_INTITULE).Where(p => p.T_B_PRES_ID == null), "PRES_ID", "PRES_INTITULE");
}
<div class="form-group">
<label class = "w3-blue" style ="text-shadow:1px 1px 0 #444">Domaine:</label>
<div class="col-md-10">
@Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { @class = "w3-select ", @required = "true" })
</div>
</div>
The probably only way which is marginally faster than
d = [[] for x in xrange(n)]
is
from itertools import repeat
d = [[] for i in repeat(None, n)]
It does not have to create a new int
object in every iteration and is about 15 % faster on my machine.
Edit: Using NumPy, you can avoid the Python loop using
d = numpy.empty((n, 0)).tolist()
but this is actually 2.5 times slower than the list comprehension.
iirc :
cat filename.txt | awk '{ print $2 $4 }'
or, as mentioned in the comments :
awk '{ print $2 $4 }' filename.txt
Here is what backup in this sense really means:
Android's backup service allows you to copy your persistent application data to remote "cloud" storage, in order to provide a restore point for the application data and settings. If a user performs a factory reset or converts to a new Android-powered device, the system automatically restores your backup data when the application is re-installed. This way, your users don't need to reproduce their previous data or application settings.
~Taken from http://developer.android.com/guide/topics/data/backup.html
You can register for this backup service as a developer here: https://developer.android.com/google/backup/signup.html
The type of data that can be backed up are files, databases, sharedPreferences, cache, and lib. These are generally stored in your device's /data/data/[com.myapp] directory, which is read-protected and cannot be accessed unless you have root privileges.
UPDATE: You can see this flag listed on BackupManager's api doc: BackupManager
It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.
https://github.com/davidjbradshaw/iframe-resizer
It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.
Works in all modern browsers and IE8 upwards.
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
I had this challenge when working on a Rails 6 API application in Ubuntu 20.04.
I had already existing models, and I needed to generate corresponding controllers for the models and also add their allowed attributes in the controller params.
Here's how I did it:
I used the rails generate scaffold_controller
to get it done.
I simply ran the following commands:
rails generate scaffold_controller School name:string logo:json motto:text address:text
rails generate scaffold_controller Program name:string logo:json school:references
This generated the corresponding controllers for the models and also added their allowed attributes in the controller params, including the foreign key attributes.
create app/controllers/schools_controller.rb
invoke test_unit
create test/controllers/schools_controller_test.rb
create app/controllers/programs_controller.rb
invoke test_unit
create test/controllers/programs_controller_test.rb
That's all.
I hope this helps
There is two way you can define cell. If your table cell is inside on your ViewControllern then get the cell this way:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
// write your code here
return cell
}
But if you define cell outside of your ViewController then call the sell this way:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
// write your code here
return cell
}
And as everyone said don't forget to set your cell identifier:
jQuery.validator.methods.matches = function( value, element, params ) {
var re = new RegExp(params);
// window.console.log(re);
// window.console.log(value);
// window.console.log(re.test( value ));
return this.optional( element ) || re.test( value );
}
rules: {
input_telf: {
required : true,
matches : "^(\\d|\\s)+$",
minlength : 10,
maxlength : 20
}
}
Yes the set of instructions above are outdated. For the new GitHub the Settings button must be clicked.
Also the person you try to add as a collaborator must have an existing GitHub account. In other words he should have signed up on GitHub first because it is not possible to send collaboration requests merely by typing in the email address of the collaborator.
This is a quirk of the C grammar. A label (Cleanup:
) is not allowed to appear immediately before a declaration (such as char *str ...;
), only before a statement (printf(...);
). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.
You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:
int main (void)
{
char *str;
printf("Hello ");
goto Cleanup;
Cleanup:
str = "World\n";
printf("%s\n", str);
return 0;
}
I wrote shell script below (named start.sh
).
Because my package.json
has prestart
option.
So I want to run npm start
.
#!/bin/bash
cd /path/to/project
npm start
Then, start start.sh
by pm2.
pm2 start start.sh --name appNameYouLike
Working fine chartJs sector onclick
ChartJS : pie Chart - Add options "onclick"
options: {
legend: {
display: false
},
'onClick' : function (evt, item) {
console.log ('legend onClick', evt);
console.log('legd item', item);
}
}
A simple way to do what OP desires in core JS.
document.getElementById(parent.id).children[child.id];
Normal array
can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.
$names = [
'bob' => 27,
'billy' => 43,
'sam' => 76,
];
$names['bob'];
And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject
or you can use SplObjectStorage
class which is map (dictionary) implementation allowing objects to be assigned as keys.
Simply convert int
to NSString
use :
int x=10;
NSString *strX=[NSString stringWithFormat:@"%d",x];
You can do this without an interface.
class myClass{
public error(message: string, title?: string, autoHideAfter? : number){
//....
}
}
use the ?
operator as an optional parameter.
I think this is what you're looking for: PAW Server from http://paw-android.fun2code.de/
hope it works
Try,
var newList =
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();
None of the response works for me targeting a phonegapp App.
As the following link points, the solution below works.
@media screen and (device-height: 568px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
// css here
}
Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you.
The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values.
Something like this:
function reverseGeocode(latitude,longitude){
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
geocoder.getLocations(latlng, function(addresses) {
var address = addresses.Placemark[0].address;
var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
var countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
do_something_with_address(address, country, countrycode, locality);
});
}
function do_something_with_address(address, country, countrycode, locality) {
if (country==="USA") {
alert("USA A-OK!"); // or whatever
}
}
If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:
function reverseGeocode(latitude,longitude, callback){
// Function contents the same as above, then
callback(address, country, countrycode, locality);
}
reverseGeocode(latitude, longitude, do_something_with_address);
If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer.
Gitg is a great tool for Linux, similar to Gitx for OS X. Just run 'gitg' on the command line from somewhere inside your repository's tree structure (same with gitx).
Following @Caspar comment on accepted answer, the preferred way to fix this according to Sun is :
"change the locale of the underlying platform before starting your Java program."
http://bugs.java.com/view_bug.do?bug_id=4163515
For docker see:
I faced the same problem. Though I am a little bit backdated developer (Still using windows to develop :P)
To solve this issue on windows :
STEP 1: Install jdk 8 if it wasn't installed (jdk 9 or 11 doesn't work but you may have them installed for using in other dev uses).
Very simple using Chocolatey:
choco install jdk8
(If installed using Chocolatey, skip steps 2 and 3)
STEP 2: Go to the Environment variables settings and set JAVA_HOME TO jdk 8's installation directory.
STEP 3: Go to path variable and add bin directory of jdk 8 and move it to top.
STEP 4: Close any open terminal sessions and restart a new session
OPTIONAL STEP 5: Depending on your objective in the terminal run (may need to add sdkmanager to path or just navigate to the directory):
sdkmanager --update
That's all! :O Enjoy fluttering! :D
Let's start by the following example:
Now we have 3 options to merge changes of feature branch into master branch:
Merge commits
Will keep all commits history of the feature branch and move them into the master branch
Will add extra dummy commit.
Rebase and merge
Will append all commits history of the feature branch in the front of the master branch
Will NOT add extra dummy commit.
Squash and merge
Will group all feature branch commits into one commit then append it in the front of the master branch
Will add extra dummy commit.
You can find below how the master branch will look after each one of them.
In all cases:
We can safely DELETE the feature branch.
First, you need to display/check all running queries using below query-
SELECT text, GETDATE(), *
FROM sys.dm_exec_requests
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
Find Session-Id
and Description
for respective all running queries and then copy specific query's Session-Id which you want to kill/stop immediately.
Kill/stop specific query using Session-Id using this query:
Kill Session-id
Example:
kill 125 --125 is my Session-Id
ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,)
from telephone number:
var str = "+(48) 123-456-789".replace(/[-+()\s]/g, ''); // result: "48123456789"
We use regular expression [-+()\s]
where we put unwanted characters between [
and ]
(the "\s
" is 'space' character escape - for more info google 'character escapes in in regexp')
After submitting the post you can redirect using inline javascript like below:
echo '<script language="javascript">window.location.href=""</script>';
I use this code all the time to clear form data and reload the current form. The empty href reloads the current page in a reset mode.
If you need a serializable, immutable list with a single entity you can use:
List<String> singList = Collections.singletonList("stackoverlow");
One way we do this in our application is using IDisposable and then with using(){}
blocks to ensure the cursor is reset when done.
public class OverrideCursor : IDisposable
{
public OverrideCursor(Cursor changeToCursor)
{
Mouse.OverrideCursor = changeToCursor;
}
#region IDisposable Members
public void Dispose()
{
Mouse.OverrideCursor = null;
}
#endregion
}
and then in your code:
using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait))
{
// Do work...
}
The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement.
Update
To prevent the cursor flickering you can do:
public class OverrideCursor : IDisposable
{
static Stack<Cursor> s_Stack = new Stack<Cursor>();
public OverrideCursor(Cursor changeToCursor)
{
s_Stack.Push(changeToCursor);
if (Mouse.OverrideCursor != changeToCursor)
Mouse.OverrideCursor = changeToCursor;
}
public void Dispose()
{
s_Stack.Pop();
Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null;
if (cursor != Mouse.OverrideCursor)
Mouse.OverrideCursor = cursor;
}
}
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
json_encode() function will help you to encode array to JSON in php.
if you will use just json_encode function directly without any specific option, it will return an array. Like mention above question
$array = array(
2 => array("Afghanistan",32,13),
4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]
Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below
<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
Theres an excellent tutorial on this subject at HelloAndroid regarding this very subject. Infact it was the first hit i got on google. You should try googling before asking here, as it is good practice.
This was my solution:
I added required to the select tag:
<div class="col-lg-10">
<select class="form-control" name="HoursEntry" id="HoursEntry" required>
<option value="">Select.....</option>
<option value="0.25">0.25</option>
<option value="0.5">0.50</option>
<option value="1">1.00</option>
<option value="1.25">1.25</option>
<option value="1.5">1.50</option>
<option value="2">2.00</option>
<option value="2.25">2.25</option>
<option value="2.5">2.50</option>
<option value="3">3.00</option>
<option value="3.25">3.25</option>
<option value="3.5">3.50</option>
<option value="4">4.00</option>
<option value="4.25">4.25</option>
<option value="4.5">4.50</option>
<option value="5">5.00</option>
<option value="5.25">5.25</option>
<option value="5.5">5.50</option>
<option value="6">6.00</option>
<option value="6.25">6.25</option>
<option value="6.5">6.50</option>
<option value="7">7.00</option>
<option value="7.25">7.25</option>
<option value="7.5">7.50</option>
<option value="8">8.00</option>
</select>
If you need a custom string sort, you can create a function that returns a number based on the order you specify.
For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:
Private Function sortpictures(s As String) As Integer
If Regex.IsMatch(s, "FRONT") Then
Return 0
ElseIf Regex.IsMatch(s, "SIDE") Then
Return 1
ElseIf Regex.IsMatch(s, "CLASP") Then
Return 2
Else
Return 3
End If
End Function
Then I call the sort function like this:
list.Sort(Function(elA As String, elB As String)
Return sortpictures(elA).CompareTo(sortpictures(elB))
End Function)
In my case for exact same error, I was also not the only developer.
So I went to commit & push my changes at same time, seen at bottom of the Commit
dialog popup:
...but I made the huge mistake of forgetting to hit the Fetch
button to see if I have latest, which I did not.
The commit successfully executed, however not the push, but instead gives the same mentioned error; ...even though other developers didn't alter same files as me, I cannot pull latest as same error is presented.
Most of the time I prefer sticking with Sourcetree's GUI (Graphical User Interface). This solution might not be ideal, however this is what got things going again for me without worrying that I may lose my changes or compromise more recent updates from other developers.
Right-click on the commit right before yours to undo your locally committed changes and select Reset current branch to this commit
like so:
Once all the loading spinners disappear and Sourcetree is done loading the previous commit, at the top-left of window, click on Pull
button...
...then a dialog popup will appear, and click the OK
button at bottom-right:
After pulling latest, if you do not get any errors, skip to STEP 4 (next step below). Otherwise if you discover any merge conflicts at this point, like I did with my Web.config
file:
...then click on the Stash
button at the top, a dialog popup will appear and you will need to write a Descriptive-name-of-your-changes, then click the OK
button:
...once Sourcetree is done stashing your altered file(s), repeat actions in STEP 2 (previous step above), and then your local files will have latest changes. Now your changes can be reapplied by opening your STASHES
seen at bottom of Sourcetree left column, use the arrow to expand your stashes, then right-click to choose Apply Stash 'Descriptive-name-of-your-changes'
, and after select OK
button in dialog popup that appears:
IF you have any Merge Conflict(s) right now, go to your preferred text-editor, like Visual Studio Code, and in the affected files select the Accept Incoming Change
link, then save:
Then back to Sourcetree, click on the Commit
button at top:
then right-click on the conflicted file(s), and under Resolve Conflicts
select the Mark Resolved
option:
Finally!!! We are now able to commit our file(s), also checkmark the Push changes immediately to origin
option before clicking the Commit
button:
P.S. while writing this, a commit was submitted by another developer right before I got to commit, so had to pretty much repeat steps.
This problem happened with me when I used jQUery Fancybox inside a website with many others jQuery plugins. When I used the LightBox (site here) instead of Fancybox, the problem is gone.
Try this CSS code for cross-browser compatibility.
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
create simple method to do that for you:
public void addMulti(String[] strings,List list){
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
Then you can create
String[] wrong ={"1","2","3","4","5","6"};
and add it with this method to your list.
I think the OP's problem was not escaping the slashes.
on windows a path like: "c:\user\folderss\myscript.sql"
should in the command line be written like either:
c:\\\user\\\folders\\\myscript.sql
or:
c:/user/folders/myscript.sql
therefore "\u"
from "c:\user"
was interpreted as a command.
see: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html for more info
Nick's answer works great and the default settings are nice, but you can more fully control the scrolling by completing all of the optional settings.
here is what it looks like in the API:
.animate( properties [, duration] [, easing] [, complete] )
so you could do something like this:
.animate(
{scrollTop:'300px'},
300,
swing,
function(){
alert(animation complete! - your custom code here!);
}
)
here is the jQuery .animate function api page: http://api.jquery.com/animate/
Using TimeZones class makes it easy to create timezone specific date.
TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(TimeZones.Paris.Id));
You need to call $compile
on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.
In your fiddle, it would look something like this.
$("#dynamicContent").html(
$compile(
"<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
)(scope)
);
Obviously, $compile
must be injected into your controller for this to work.
Read more in the $compile
documentation.
1.Run Spring Boot app with java -jar command
To run your Spring Boot app from a command line in a Terminal window you can use java -jar command. This is provided your Spring Boot app was packaged as an executable jar file.
java -jar target/app-0.0.1-SNAPSHOT.jar
2.Run Spring Boot app using Maven
You can also use Maven plugin to run your Spring Boot app. Use the below command to run your Spring Boot app with Maven plugin:
mvn spring-boot:run
3.Run Spring Boot App with Gradle
And if you use Gradle you can run the Spring Boot app with the following command:
gradle bootRun
Normally, encryption functions take
encrypt(const void *ptr, size_t bufferSize);
as arguments. You can pass c_str and length directly:
encrypt(strng.c_str(), strng.length());
This way, extra space is allocated or wasted.
I guess tc
could do the job on UNIX based platform.
tc
is used to configure Traffic Control in the Linux kernel
http://lartc.org/manpages/tc.txt
As other people have answered, .cshtml
(or .vbhtml
if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx
extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.
This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.
Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.
The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.
use ProgressDialog.
ProgressDialog dialog=new ProgressDialog(context);
dialog.setMessage("message");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();
hide it whenever your UI is ready with data. call :
dialog.hide();
After reading the above answers, here adding my interpretations.
Suppose browsing online, web browser is your frame
which decides where and how big to show webpage. Scroller of browser is your bounds.origin
that decides which part of webpage will be shown. bounds.origin
is hard to understand. The best way to learn is creating Single View Application, trying modify these parameters and see how subviews change.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 200.0f, 200.0f, 400.0f)];
[view1 setBackgroundColor:[UIColor redColor]];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];
[view2 setBackgroundColor:[UIColor yellowColor]];
[view1 addSubview:view2];
[[self view] addSubview:view1];
NSLog(@"Old view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
NSLog(@"Old view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));
// Modify this part.
CGRect bounds = view1.bounds;
bounds.origin.x += 10.0f;
bounds.origin.y += 10.0f;
// incase you need width, height
//bounds.size.height += 20.0f;
//bounds.size.width += 20.0f;
view1.bounds = bounds;
NSLog(@"New view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
NSLog(@"New view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));
With current Angular 4 and 5 versions, there is an IDE for that.
Go to eclipse market place any search for 'Angular'. You will see the IDE and install it.
After that restart eclipse and follow the welcome messages to choose preferences.
How to start using eclipse with angular projects?
Considering you already have angular project and you want to import it into eclipse.
go to file > import > choose Angular Project
and It would be better to have your projects in a separate working set so that you will not confuse it with other kind of (like java)projects.
With Angular IDE You will have a terminal window too.
To open this type terminal in eclipse search box(quick access) on the top right corner.
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
Set autoplay=0
<iframe width="100%" height="100%" src="//www.youtube.com/embed/qUJYqhKZrwA?autoplay=0&showinfo=0&controls=0" frameborder="0" allowfullscreen>
As seen here: Autoplay=0 Test
Above answers are pretty sufficient. Additional to the onChange
, if you upload a file using drag and drop events, you can get the file in drop
event by accessing eventArgs.dataTransfer.files
.
I have mysql version 5.6.27 on my LEMP and CURRENT_TIMESTAMP as default value works fine.
You use an SDK to access functionality of a library, and an API to control it.
Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex
on the row container and at least making sure your middle container on the row has a flex-grow
value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow
properties applied, middle container only needs 1 for flex-grow
).
Here's a pic of what I was trying to do and sample code for how I solved it.
.row {
background: lightgray;
height: 30px;
width: 100%;
display: flex;
align-items:flex-end;
margin-top:5px;
}
.left {
background:lightblue;
}
.separator{
flex-grow:1;
border-bottom:dotted 2px black;
}
.right {
background:coral;
}
_x000D_
<div class="row">
<div class="left">Left</div>
<div class="separator"></div>
<div class="right">Right With Text</div>
</div>
<div class="row">
<div class="left">Left With More Text</div>
<div class="separator"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left With Text</div>
<div class="separator"></div>
<div class="right">Right With More Text</div>
</div>
_x000D_
This works for me:
#! /bin/bash CACERTS=$(readlink -e $(dirname $(readlink -e $(which keytool)))/../lib/security/cacerts) if keytool -list -keystore $CACERTS -storepass changeit > /dev/null ; then echo $CACERTS else echo 'Can not find cacerts file.' >&2 exit 1 fi
Only for Linux. My Solaris has no readlink. In the end I used this Perl-Script:
#! /usr/bin/env perl use strict; use warnings; use Cwd qw(realpath); $_ = realpath((grep {-x && -f} map {"$_/keytool"} split(':', $ENV{PATH}))[0]); die "Can not find keytool" unless defined $_; my $keytool = $_; print "Using '$keytool'.\n"; s/keytool$//; $_ = realpath($_ . '../lib/security/cacerts'); die "Can not find cacerts" unless -f $_; my $cacerts = $_; print "Importing into '$cacerts'.\n"; `$keytool -list -keystore "$cacerts" -storepass changeit`; die "Can not read key container" unless $? == 0; exit if $ARGV[0] eq '-d'; foreach (@ARGV) { my $cert = $_; s/\.[^.]+$//; my $alias = $_; print "Importing '$cert' as '$alias'.\n"; `keytool -importcert -file "$cert" -alias "$alias" -keystore "$cacerts" -storepass changeit`; warn "Can not import certificate: $?" unless $? == 0; }
This can be done for a normal subview
inside a larger UIView
, but it doesn't work automatically for headerViews
. The height of a headerView
is determined by what's returned by tableView:heightForHeaderInSection:
so you have to calculate the height
based on the height
of the UILabel
plus space for the UIButton
and any padding
you need. You need to do something like this:
-(CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
NSString *s = self.headeString[indexPath.section];
CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 60;
}
Here headerString
is whatever string you want to populate the UILabel
, and the 281 number is the width
of the UILabel
(as setup in Interface Builder
)
Just use a specific variable for that.
$ cat Makefile
all:
echo foo | gcc $(USER_DEFINES) -E -xc -
$ make USER_DEFINES="-Dfoo=one"
echo foo | gcc -Dfoo=one -E -xc -
...
one
$ make USER_DEFINES="-Dfoo=bar"
echo foo | gcc -Dfoo=bar -E -xc -
...
bar
$ make
echo foo | gcc -E -xc -
...
foo
elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).
By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.
It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.
We are using Response.SetCookie()
for update the old one cookies and Response.Cookies.Add()
are use to add the new cookies. Here below code CompanyId
is update in old cookie[OldCookieName]
.
HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.
Beside above solutions, there is a more "COMMON" way - directly delete the largest space consumer from Linux machine. You can follow the below steps:
Using ls -lart to list out hidden folder also, normally jenkin installation is placed in .jenkins/ folder
[xxxxx ~]$ ls -lart drwxrwxr-x 12 xxxx 4096 Feb 8 02:08 .jenkins/
Use df -h
to show Disk space in high level
du -sh ./*/
to list out total memory for each subfolder in current path.
du -a /etc/ | sort -n -r | head -n 10
will list top 10 directories eating disk space in /etc/
Normally ./job/ folder or ./workspace/ folder can be the largest folder. Please go inside and delete base on you need (DO NOT delete entire folder).
rm -rf theFolderToDelete
Dynamic programming problems can be solved using either bottom-up or top-down approaches.
Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.
But you can also have bottom-up and top-down approaches using recursion as shown below.
Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.
int n = 5;
fibBottomUp(1, 1, 2, n);
private int fibBottomUp(int i, int j, int count, int n) {
if (count > n) return 1;
if (count == n) return i + j;
return fibBottomUp(j, i + j, count + 1, n);
}
Top-Down: Start with the final condition and recursively get the result of its sub-problems.
int n = 5;
fibTopDown(n);
private int fibTopDown(int n) {
if (n <= 1) return 1;
return fibTopDown(n - 1) + fibTopDown(n - 2);
}
I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .
While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output
you never set d[a]
to any value.
Because of this, d[a]
evaluates to undefined
, and you can't set properties on undefined
.
If you add d[a] = {}
right after d = {}
things should work as expected.
Alternatively, you could use an object initializer:
d[a] = {
greetings: b,
data: c
};
Or you could set all the properties of d
in an anonymous function instance:
d = new function () {
this[a] = {
greetings: b,
data: c
};
};
If you're in an environment that supports ES2015 features, you can use computed property names:
d = {
[a]: {
greetings: b,
data: c
}
};
You can do something like this:
<%
out.print("<p>Hey!</p>");
out.print("<p>How are you?</p>");
%>
On sqlite 3.7.2:
INSERT INTO table_name (column1, column2)
SELECT 'value1', 'value1'
UNION SELECT 'value2', 'value2'
UNION SELECT 'value3', 'value3'
and so on
SELECT TIMEDIFF('2007-12-31 10:02:00','2007-12-30 12:01:01');
-- result: 22:00:59, the difference in HH:MM:SS format
SELECT TIMESTAMPDIFF(SECOND,'2007-12-30 12:01:01','2007-12-31 10:02:00');
-- result: 79259 the difference in seconds
So, you can use TIMESTAMPDIFF
for your purpose.
I was having the same exception with node v12.13.1,
Downgraded node to v10.15.3 and it works fine now.
If you're open to a PHP solution:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////EDIT OK, here's a JS version:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>
I was also trying to run Spring Boot application in Eclipse, without any plugins.
Step 1
Right click on your project. Select "Run As" -> "Maven build...". Then in "Goals" field, enter "spring-boot:run". Apply & Run.
After this you do not have to Run again.
Step 2
After making any change, clean your project. After cleaning, it automatically builds the project once. Then when you will refresh your pages on browser, change will be reflected.
Presumably you have it in a variable and are using JSON.parse(data);
. In which case, use:
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because "
is not valid in a JSON object.
You can also use the not now documented disabled
attribute:
$("#element").dialog({
buttons: [
{
text: "Confirm",
disabled: true,
id: "my-button-1"
},
{
text: "Cancel",
id: "my-button-2",
click: function(){
$(this).dialog("close");
}
}]
});
To enable after dialog has opened, use:
$("#my-button-1").attr('disabled', false);
JsFiddle: http://jsfiddle.net/xvt96e1p/4/
Java commons-io has a FileAlterationObserver. it does polling in combination with a FileAlterationMonitor. Similar to commons VFS. The advantag is that it has much less dependencies.
edit: Less dependencies is not true, they are optional for VFS. But it uses java File instead of the VFS abstraction layer.
It is n for next and N for previous.
And if you use reverse search with ?
(for example, ?cake
) instead of /
, it is the other way round.
If it is installed on your system, you should try to run vimtutor
command from your terminal, which will start a tutorial of the basic Vim commands.
Rob Wells advice about * and # is also very pertinent.
If you have Div as follows in one Iframe
<iframe id="ifrmReportViewer" name="ifrmReportViewer" frameborder="0" width="980"
<div id="EndLetterSequenceNoToShow" runat="server"> 11441551 </div> Or
<form id="form1" runat="server">
<div style="clear: both; width: 998px; margin: 0 auto;" id="divInnerForm">
Some Text
</div>
</form>
</iframe>
Then you can find the text of those Div using the following code
var iContentBody = $("#ifrmReportViewer").contents().find("body");
var endLetterSequenceNo = iContentBody.find("#EndLetterSequenceNoToShow").text();
var divInnerFormText = iContentBody.find("#divInnerForm").text();
I hope this will help someone.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Hide();
var main = new Main();
main.Show();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
the chsh
program will let you change your default shell. It will want the full path to the executable, so if your shell is fish
then it will want you to provide the output given when you type which fish
.
You'll see a line starting with "Shell:
". If you've never edited it, it most likely says "Shell: /bin/bash
". Replace that /bin/bash
path with the path to your desired shell.
You can automatically encode into Json, your complex entity with:
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');
Regular expressions with character classes (e.g. [[:digit:]]
) are not supported in the default regular expression syntax used by find
. You need to specify a different regex type such as posix-extended
in order to use them.
Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.
Using guava you can just do something like Sets.newHashSet(charArray).toArray();
If you are not using any libraries, you can still use new HashSet<Char>()
and add your char
array there.
Here is the example:
var charCode = "a".charCodeAt(0);_x000D_
console.log(charCode);
_x000D_
Or if you have longer strings:
var string = "Some string";_x000D_
_x000D_
for (var i = 0; i < string.length; i++) {_x000D_
console.log(string.charCodeAt(i));_x000D_
}
_x000D_
String.charCodeAt(x)
method will return ASCII character code at a given position.
You can use the mciSendString
API to play an MP3 or a WAV file:
[DllImport("winmm.dll")]
public static extern uint mciSendString(
string lpstrCommand,
StringBuilder lpstrReturnString,
int uReturnLength,
IntPtr hWndCallback
);
mciSendString(@"close temp_alias", null, 0, IntPtr.Zero);
mciSendString(@"open ""music.mp3"" alias temp_alias", null, 0, IntPtr.Zero);
mciSendString("play temp_alias repeat", null, 0, IntPtr.Zero);
Very simple don't make it complicated with lots of logic use simple attribute draggable and make it false
<img draggable="false" src="img/magician.jpg" alt="" />
Only one column version
df[column_name].fillna(method='ffill', inplace=True)
df[column_name].fillna(method='backfill', inplace=True)
Apparently running sudo chmod -R a+rw
on your home folder causes this to happen as well.
You want to do something like the following:
(I won't write the actual code, since this looks like homework, but feel free to post other questions on specific bits that you have trouble with)
Try this:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
Save the following script as something like findPK.sql.
set verify off
accept TABLE_NAME char prompt 'Table name>'
SELECT cols.column_name
FROM all_constraints cons NATURAL JOIN all_cons_columns cols
WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');
It can then be called using
@findPK
You can actually compare files natively right in Sublime Text.
Open Folder...
or
in a projectDiff files...
option.Use brackets. So to look for 75%
WHERE MyCol LIKE '%75[%]%'
This is simpler than ESCAPE and common to most RDBMSes.