A reboot prevents it from opening the dialog.
$*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
$@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).
Source: Bash man
As has been discussed elsewhere, the .length
property reference is failing because theHref
is undefined. However, be aware of any solution which involves comparing theHref
to undefined
, which is not a keyword in JavaScript and can be redefined.
For a full discussion of checking for undefined variables, see Detecting an undefined object property and the first answer in particular.
If you're using .NET 4.0 you should be able to allow these urls via the web.config
<system.web>
<httpRuntime
requestPathInvalidCharacters="<,>,%,&,:,\,?" />
</system.web>
Note, I've just removed the asterisk (*), the original default string is:
<httpRuntime
requestPathInvalidCharacters="<,>,*,%,&,:,\,?" />
See this question for more details.
You can use a combiation of LEFT
and CHARINDEX
to find the index of the first space, and then grab everything to the left of that.
SELECT LEFT(YourColumn, charindex(' ', YourColumn) - 1)
And in case any of your columns don't have a space in them:
SELECT LEFT(YourColumn, CASE WHEN charindex(' ', YourColumn) = 0 THEN
LEN(YourColumn) ELSE charindex(' ', YourColumn) - 1 END)
I'm not sure about bash-like environment. You might try some simple wrapper programs in Java (with program arguments) that invoke your MBeans on the remote server. You can then call these wrappers from the shell script
If you can use something like Python or Perl, you might be interested in JSR-262 which allows you to expose JMX operations over web services. This is scheduled to be included in Java 7 but you might be able to use a release candidate of the reference implementation
From page 106 of the ggplot2 book by Hadley Wickham:
The default colour scheme, scale_colour_hue picks evenly spaced hues around the hcl colour wheel.
With a bit of reverse engineering you can construct this function:
ggplotColours <- function(n = 6, h = c(0, 360) + 15){
if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}
Demonstrating this in barplot:
y <- 1:3
barplot(y, col = ggplotColours(n = 3))
An alternative solution:
div[class|='tocolor']
will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.
Beware that this won't match
<div class="foo tocolor-">
Reference: https://www.w3.org/TR/css3-selectors/#attribute-representation
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)
You can use Gnu-Parallel to run commands concurrently, works on Windows, Linux/Unix.
parallel ::: "python script1.py" "python script2.py"
Use git push origin master
instead.
You have a repository locally and the initial git push
is "pushing" to it. It's not necessary to do so (as it is local) and it shows everything as up-to-date. git push origin master
specifies a a remote repository (origin
) and the branch located there (master
).
For more information, check out this resource.
Ensure you have included the different abiFilters, this enables Gradle know what ABI libraries to package into your apk.
defaultConfig {
ndk {
abiFilters "armeabi-v7a", "x86", "armeabi", "mips"
}
}
If you storing your jni libs in a different directory, or also using externally linked jni libs, Include them on the different source sets of the app.
sourceSets {
main {
jni.srcDirs = ['src/main/jniLibs']
jniLibs.srcDir 'src/main/jniLibs'
}
}
As shown in the latest edit, the password is valid until 1970, which means it's currently invalid. This explains the error message which is the same as if the password was incorrect.
Reset the validity with:
ALTER USER postgres VALID UNTIL 'infinity';
In a recent question, another user had the same problem with user accounts and PG-9.2:
PostgreSQL - Password authentication fail after adding group roles
So apparently there is a way to unintentionally set a bogus password validity to the Unix epoch (1st Jan, 1970, the minimum possible value for the abstime
type). Possibly, there's a bug in PG itself or in some client tool that would create this situation.
EDIT: it turns out to be a pgadmin bug. See https://dba.stackexchange.com/questions/36137/
Don't forget also that the path for the file is on the actual oracle server machine and not any local development machine that might be calling your stored procedure. This is probably very obvious but something that should be remembered.
Here is my layout:
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/padding" >
<LinearLayout
android:id="@+id/shapeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
</LinearLayout>
</HorizontalScrollView>
And I populate it in the code with dynamic check-boxes.
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
You can also use number formatter JS available at
https://code.google.com/p/javascript-number-formatter/
http://jsfiddle.net/chauhangs/hUE3h/
format("##,###.", 98700)
format("#,###.", 8211)
I'm sure you'll get a ton of "don't do this" answers, and I must say, there is good reason. This isn't an ideal solution....
That being said, I've gone down this road (and similar ones) before, mostly because the job specified it as a hard requirement and I couldn't talk around it.
Here are a few things to consider with this:
How easy is it to link to Access from Excel using ADO / DAO? Is it quite limited in terms of functionality or can I get creative?
It's fairly straitforward. You're more limited than you would be doing things using other tools, since VBA and Excel forms is a bit more limiting than most full programming languages, but there isn't anything that will be a show stopper. It works - sometimes its a bit ugly, but it does work. In my last company, I often had to do this - and occasionally was pulling data from Access and Oracle via VBA in Excel.
Do I pay a performance penalty (vs.using forms in Access as the UI)?
My experience is that there is definitely a perf. penalty in doing this. I never cared (in my use case, things were small enough that it was reasonable), but going Excel<->Access is a lot slower than just working in Access directly. Part of it depends on what you want to do....
In my case, the thing that seemed to be the absolute slowest (and most painful) was trying to fill in Excel spreadsheets based on Access data. This wasn't fun, and was often very slow. If you have to go down this road, make sure to do everything with Excel hidden/invisible, or the redrawing will absolutely kill you.
Assuming that the database will always be updated using ADO / DAO commands from within Excel VBA, does that mean I can have multiple Excel users using that one single Access database and not run into any concurrency issues etc.?
You're pretty much using Excel as a client - the same way you would use a WinForms application or any other tool. The ADO/DAO clients for Access are pretty good, so you probably won't run into any concurrency issues.
That being said, Access does NOT scale well. This works great if you have 2 or 3 (or even 10) users. If you are going to have 100, you'll probably run into problems. Also, I tended to find that Access needed regular maintenance in order to not have corruption issues. Regular backups of the Access DB are a must. Compacting the access database on a regular basis will help prevent database corruption, in my experience.
Any other things I should be aware of?
You're doing this the hard way. Using Excel to hit Access is going to be a lot more work than just using Access directly.
I'd recommend looking into the Access VBA API - most of it is the same as Excel, so you'll have a small learning curve. The parts that are different just make this easier. You'll also have all of the advantages of Access reporting and Forms, which are much more data-oriented than the ones in Excel. The reporting can be great for things like this, and having the Macros and Reports will make life easier in the long run. If the user's going to be using forms to manage everything, doing the forms in Access will be very, very similar to doing them in Excel, and will look nearly identical, but will make everything faster and smoother.
Actually it can be done in pure css and it's pretty easy...
HTML Code
<label class="filebutton">
Browse For File!
<span><input type="file" id="myfile" name="myfile"></span>
</label>
CSS Styles
label.filebutton {
width:120px;
height:40px;
overflow:hidden;
position:relative;
background-color:#ccc;
}
label span input {
z-index: 999;
line-height: 0;
font-size: 50px;
position: absolute;
top: -2px;
left: -700px;
opacity: 0;
filter: alpha(opacity = 0);
-ms-filter: "alpha(opacity=0)";
cursor: pointer;
_cursor: hand;
margin: 0;
padding:0;
}
The idea is to position the input absolutely inside your label. set the font size of the input to something large, which will increase the size of the "browse" button. It then takes some trial and error using the negative left / top properties to position the input browse button behind your label.
When positioning the button, set the alpha to 1. When you've finished set it back to 0 (so you can see what you're doing!)
Make sure you test across browsers because they'll all render the input button a slightly different size.
While many of these solutions have worked for me in the past, they all failed me today on a Mac with a Samsung S7. After trying a few cables, someone suggested that the ADB connection requires an official Samsung cable to work. Indeed, when I used the Samsung cable, ADB worked just fine. I hope this helps someone else!
String[][] shades = new String[intSize][intSize];
// print array in rectangular form
for (int r=0; r<shades.length; r++) {
for (int c=0; c<shades[r].length; c++) {
shades[r][c]="hello";//your value
}
}
Maybe you have closed the project and configured the project explorer view to filter closed projects.
In that case, have a look at Filters in the Project Explorer view. Make sure that closed projects are disabled in the "Filters" view.
Yes. But remember that such primary key allow NULL
values in both columns multiple times.
Create a table as such:
sqlite> CREATE TABLE something (
column1, column2, value, PRIMARY KEY (column1, column2));
Now this works without any warning:
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> select * from something;
NULL|NULL|bla-bla
NULL|NULL|bla-bla
If you have an SVG icon, you can use this script to generate your android icon set.
There is a much simpler solution for that.
Actually treating the items of JArray
as JObject
works.
Here is an example:
Let's say we have such array of JSON objects:
JArray jArray = JArray.Parse(@"[
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
}]");
To get access each item we just do the following:
foreach (JObject item in jArray)
{
string name = item.GetValue("name").ToString();
string url = item.GetValue("url").ToString();
// ...
}
First WebClient
is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
Query all users and filter by the list from your text file:
$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users -contains $_.SamAccountName } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
Get-ADUser -Filter '*'
returns all AD user accounts. This stream of user objects is then piped into a Where-Object
filter, which checks for each object if its SamAccountName
property is contained in the user list from your input file ($Users
). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.
You can further optimize the code by replacing the -contains
operator with hashtable lookups:
$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users.ContainsKey($_.SamAccountName) } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
You could do:
import inspect
mydict = {'one': 1, 'two': 2}
source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print [x for x in source if x.startswith("mydict = ")]
Also: make sure not to shadow the dict builtin!
Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="First"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Second"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Third"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
android:text="fourth"/>
</android.support.v7.widget.GridLayout>
In your current Activity, create a new Intent
:
String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);
i.putExtra("key",value);
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//The key argument here must match that used in the other activity
}
Use this technique to pass variables from one Activity to the other.
Here is my take on this issue. The following retry
function supports the following features:
import time
def retry(func, ex_type=Exception, limit=0, wait_ms=100, wait_increase_ratio=2, logger=None):
attempt = 1
while True:
try:
return func()
except Exception as ex:
if not isinstance(ex, ex_type):
raise ex
if 0 < limit <= attempt:
if logger:
logger.warning("no more attempts")
raise ex
if logger:
logger.error("failed execution attempt #%d", attempt, exc_info=ex)
attempt += 1
if logger:
logger.info("waiting %d ms before attempt #%d", wait_ms, attempt)
time.sleep(wait_ms / 1000)
wait_ms *= wait_increase_ratio
Usage:
def fail_randomly():
y = random.randint(0, 10)
if y < 10:
y = 0
return x / y
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(stream=sys.stdout))
logger.info("starting")
result = retry.retry(fail_randomly, ex_type=ZeroDivisionError, limit=20, logger=logger)
logger.info("result is: %s", result)
See my post for more info.
1.you will use different locale array element in datepicker.js from following link https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales
2.add array in datepicker.js like this:
$.fn.datepicker.Constructor = Datepicker;_x000D_
var dates = $.fn.datepicker.dates = {_x000D_
en: {_x000D_
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],_x000D_
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],_x000D_
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],_x000D_
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],_x000D_
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],_x000D_
today: "Today"_x000D_
},_x000D_
CN:{_x000D_
days: ["???", "???", "???", "???", "???", "???", "???", "???"],_x000D_
daysShort: ["??", "??", "??", "??", "??", "??", "??", "??"],_x000D_
daysMin: ["?", "?", "?", "?", "?", "?", "?", "?"],_x000D_
months: ["??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "???", "???"],_x000D_
monthsShort: ["??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "???", "???"],_x000D_
today: "??",_x000D_
suffix: [],_x000D_
meridiem: ["??", "??"]_x000D_
}_x000D_
};
_x000D_
In my case I had to delete the jars inside .m2/repository
and then did a Maven->Update Maven Project
Looks like the jars were corrupt and deleting and downloading the fresh jar fixed the issue.
zip -r "$destFileName.zip" "$srcFileName" -x "*/\__MACOSX" -x "*/\.*"
-x "*/\__MACOSX"
: ignore __MACOSX as you mention.-x "*/\.*"
: ignore any hidden file, such as .DS_Store .Also, you can build Automator Service to make it easily to use in Finder. Check link below to see detail if you need.
Yes, you can:
UPDATE foobar SET column_a = CASE
WHEN column_b = '123' THEN 1
WHEN column_b = '345' THEN 2
END
WHERE column_b IN ('123','345')
And working proof: http://sqlfiddle.com/#!2/97c7ea/1
For create mysql where conditions from array
$sWheres = array('item1' => 'object1',
'item2' => 'object2',
'item3' => 1,
'item4' => array(4,5),
'item5' => array('object3','object4'));
$sWhere = '';
if(!empty($sWheres)){
$sWhereConditions = array();
foreach ($sWheres as $key => $value){
if(!empty($value)){
if(is_array($value)){
$value = array_filter($value); // For remove blank values from array
if(!empty($value)){
array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'
$sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));
}
}else{
$sWhereConditions[] = sprintf("%s='%s'", $key, $value);
}
}
}
if(!empty($sWhereConditions)){
$sWhere .= "(".implode(' AND ', $sWhereConditions).")";
}
}
echo $sWhere; // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))
testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>
Short answer: 400-800 pixels.
What I have read is that HTML newsletter width should be as narrow as possible without being too narrow. For instance, 400-500 pixels for a one column layout is a lower limit. Any less may look too weird.
Today's widescreen monitors allow for more horizontal pixels and most web email clients will either be of the two-column variety (Gmail) or 3-pane layout where the content window bellow the inbox list (Hotmail and Yahoo). In either case, you can be okay with 800 pixels if you're targeting the 1280 wide audience. An older or less technical audience may have older, square monitors.
There is the problem of Outlook having a three-column layout. That limits the width of your email even more. With them, you may want to go even narrower.
I just recently created a template that required an ad banner that is 730 pixels wide. It was near in the wide range, but not so much that most people could not double-click the email an open a new window in Outlook (the web email users should be okay for the most part).
Hope this advice helps.
Same as @Sanchit Gupta.
in this part
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "city name is: " + city;
}
just console the results array
if (results[0]) {
console.log(results[0]);
// choose from console whatever you need.
var city = results[0].address_components[3].short_name;
x.innerHTML = "city name is: " + city;
}
What allowed me to have a custom reply-to address on an Ubuntu 16.04
with UTF-8
encoding and a file attachment:
Install the mail client:
sudo apt-get install heirloom-mailx
Edit the SMTP configuration:
sudo vim /etc/ssmtp/ssmtp.conf
mailhub=smtp.gmail.com:587
FromLineOverride=YES
[email protected]
AuthPass=???
UseSTARTTLS=YES
Send the mail:
sender='[email protected]'
recipient='[email protected]'
zipfile="results/file.zip"
today=`date +\%d-\%m-\%Y`
mailSubject='My subject on the '$today
read -r -d '' mailBody << EOM
Find attached the zip file.
Regards,
EOM
mail -s "$mailSubject" -r "Name <$sender>" -S replyto="$sender" -a $zipfile $recipient < <(echo $mailBody)
Detect key press, including key combinations:
window.addEventListener('keydown', function (e) {
if (e.ctrlKey && e.keyCode == 90) {
// Ctrl + z pressed
}
});
Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.
If I were you I would use conditional compilation or feature detection.
Here's another alternative:
<!--[if lt IE 9]><!-->
<script>
var LTEIE8 = true;
</script>
<!--<![endif]-->
In your component i.e angular js code:
function getthefile (){
window.location.href='http://localhost:1036/CourseRegConfirm/getfile';
};
My comment is mainly in reference to point #3: under what circumstances is ON UPDATE CASCADE applicable if we're assuming that the parent key is not updateable? Here is one case.
I am dealing with a replication scenario in which multiple satellite databases need to be merged with a master. Each satellite is generating data on the same tables, so merging of the tables to the master leads to violations of the uniqueness constraint. I'm trying to use ON UPDATE CASCADE as part of a solution in which I re-increment the keys during each merge. ON UPDATE CASCADE should simplify this process by automating part of the process.
I found out another solution for this case without using Reactivex neither services. I actually love the rxjx API however I think it goes best when resolving an async and/or complex function. Using It in that way, Its pretty exceeded to me.
What I think you are looking for is for a broadcast. Just that. And I found out this solution:
<app>
<app-nav (selectedTab)="onSelectedTab($event)"></app-nav>
// This component bellow wants to know when a tab is selected
// broadcast here is a property of app component
<app-interested [broadcast]="broadcast"></app-interested>
</app>
@Component class App {
broadcast: EventEmitter<tab>;
constructor() {
this.broadcast = new EventEmitter<tab>();
}
onSelectedTab(tab) {
this.broadcast.emit(tab)
}
}
@Component class AppInterestedComponent implements OnInit {
broadcast: EventEmitter<Tab>();
doSomethingWhenTab(tab){
...
}
ngOnInit() {
this.broadcast.subscribe((tab) => this.doSomethingWhenTab(tab))
}
}
This is a full working example: https://plnkr.co/edit/xGVuFBOpk2GP0pRBImsE
This works for me
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setRequestProperty("Authorization", "basic " +
Base64.encode("username:password".getBytes()));
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
There is a more 'smooth' solution for this :)
var Foo = function(){
this.par = 3;
this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
this.p = t;
this.subFunction = function(){
alert(this.p.par);
}
})(this);
}
var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;
myObj.par = 5;
myObj.sub.subFunction() // will popup 5;
The mysqli_query()
method returns an object resource to your $result
variable, not a string.
You need to loop it up and then access the records. You just can't directly use it as your $result
variable.
while ($row = $result->fetch_assoc()) {
echo $row['classtype']."<br>";
}
If you're still wondering how to solve it.
I use
$protected $dates = ['created_at','updated_at','aired'];
In my model and in my where i do
where('aired','>=',time())
So just use the unix to compaire in where.
In views on the otherhand you have to use the date object.
Hope it helps someone!
The Set interface itself does not stipulate any particular order. The SortedSet does however.
Request and response.
To understand the req
, try out console.log(req);
.
String.prototype.capitalize = function(allWords) {
return (allWords) ? // If all words
this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
// calls until capitalizing all words
this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
// meaning the first character of the whole string
}
And then:
"capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
"capitalize all words".capitalize(true); ==> "Capitalize All Words"
const capitalize = (string = '') => [...string].map( // Convert to array with each item is a char of
// string by using spread operator (...)
(char, index) => index ? char : char.toUpperCase() // Index true means not equal 0, so (!index) is
// the first character which is capitalized by
// the `toUpperCase()` method
).join('') // Return back to string
then capitalize("hello") // Hello
It would be neater to capture the error file thus:
ERROR=$(</tmp/Error)
The shell recognizes this and doesn't have to run 'cat
' to get the data.
The bigger question is hard. I don't think there's an easy way to do it. You'd have to build the entire pipeline into the sub-shell, eventually sending its final standard output to a file, so that you can redirect the errors to standard output.
ERROR=$( { ./useless.sh | sed s/Output/Useless/ > outfile; } 2>&1 )
Note that the semi-colon is needed (in classic shells - Bourne, Korn - for sure; probably in Bash too). The '{}
' does I/O redirection over the enclosed commands. As written, it would capture errors from sed
too.
WARNING: Formally untested code - use at own risk.
Another option is to add it on the web.config directly:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
... I found this in here
At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.
Thats why it always -ve.
You can change the encryption of the user's password by altering the user with below Alter command :
ALTER USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password';
OR
We can avoid this error by make it work with old password plugin:
First change the authentication plugin in my.cnf file for Linux / my.ini file in Windows:
[mysqld]
default_authentication_plugin=mysql_native_password
Restart the mysql server to take the changes in affect and try connecting via MySQL with any mysql client.
If still unable to connect and getting the below error:
Unable to load plugin 'caching_sha2_password'
It means your user needs the above plugin. So try creating new user with create user or grant command after changing default plugin. then new user need the native plugin and you will able to connect MySQL.
Thanks
WebStorm 10.0.4
For wrapping text/code line by deafault, but for all types of file: File -> Settings -> Editor -> General -> section "Soft Wraps" -> checkbox "Use soft wraps in editor"
(imho)
Yep, but you have to put the array first in the expression:
... | where { @("user1","user2") -notlike $_.username }
-Oisin
None: The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
Compile: The file is compiled into the build output. This setting is used for code files.
Content: Allows you to retrieve a file (in the same directory as the assembly) as a stream via Application.GetContentStream(URI). For this method to work, it needs a AssemblyAssociatedContentFile custom attribute which Visual Studio graciously adds when you mark a file as "Content"
Embedded resource: Embeds the file in an exclusive assembly manifest resource.
Resource (WPF only): Embeds the file in a shared (by all files in the assembly with similar setting) assembly manifest resource named AppName.g.resources.
Page (WPF only): Used to compile a xaml
file into baml
. The baml
is then embedded with the same technique as Resource
(i.e. available as `AppName.g.resources)
ApplicationDefinition (WPF only): Mark the XAML/class file that defines your application. You specify the code-behind with the x:Class="Namespace.ClassName" and set the startup form/page with StartupUri="Window1.xaml"
SplashScreen (WPF only): An image that is marked as SplashScreen
is shown automatically when an WPF application loads, and then fades
DesignData: Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses mock types)
DesignDataWithDesignTimeCreatableTypes: Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses actual types)
EntityDeploy: (Entity Framework): used to deploy the Entity Framework artifacts
CodeAnalysisDictionary: An XML file containing custom word dictionary for spelling rules
Using python3 pathlib library:
import re
from pathlib import Path
import shutil
shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
Similar method using different approach to backups:
from pathlib import Path
filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
Add position: relative
to .outside
. (https://developer.mozilla.org/en-US/docs/CSS/position)
Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.
The "initial container" would be <body>
, but adding the above makes .outside
positioned.
you can simply use your own code but add name for the select tag
<form method="POST" action="index.php?action=contact_agent&agent_id=">
<select name="agent_id">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
then you can access it like this
String agent=request.getparameter("agent_id");
It is part of the object literal syntax. The basic format is:
var obj = { field_name: "field value", other_field: 42 };
Then you can access these values with:
obj.field_name; // -> "field value"
obj["field_name"]; // -> "field value"
You can even have functions as values, basically giving you the methods of the object:
obj['func'] = function(a) { return 5 + a;};
obj.func(4); // -> 9
Could this be a typo? (two Ps in ppasscode, intended?)
$_POST['ppasscode'];
I would make sure and do:
print_r($_POST);
and make sure the data is accurate there, and then echo out what it should look like:
echo hash('sha256', $_POST['ppasscode']);
Compare this output to what you have in the database (manually). By doing this you're exploring your possible points of failure:
The thing about margins is that you don't need to worry about the element's width.
Like when you give something {padding: 10px;}
, you'll have to reduce the width of the element by 20px to keep the 'fit' and not disturb other elements around it.
So I generally start off by using paddings to get everything 'packed
' and then use margins for minor tweaks.
Another thing to be aware of is that paddings are more consistent on different browsers and IE doesn't treat negative margins very well.
This is really a square peg, round hole question.
If relational databases and SQL are the only hammer you have or are willing to use, then the answers that have been posted thus far are adequate. However, why not use a tool designed to handle hierarchical data? Graph database are ideal for complex hierarchical data.
The inefficiencies of the relational model along with the complexities of any code/query solution to map a graph/hierarchical model onto a relational model is just not worth the effort when compared to the ease with which a graph database solution can solve the same problem.
Consider a Bill of Materials as a common hierarchical data structure.
class Component extends Vertex {
long assetId;
long partNumber;
long material;
long amount;
};
class PartOf extends Edge {
};
class AdjacentTo extends Edge {
};
Shortest path between two sub-assemblies: Simple graph traversal algorithm. Acceptable paths can be qualified based on criteria.
Similarity: What is the degree of similarity between two assemblies? Perform a traversal on both sub-trees computing the intersection and union of the two sub-trees. The percent similar is the intersection divided by the union.
Transitive Closure: Walk the sub-tree and sum up the field(s) of interest, e.g. "How much aluminum is in a sub-assembly?"
Yes, you can solve the problem with SQL and a relational database. However, there are much better approaches if you are willing to use the right tool for the job.
This is actually really easy:
All,
From what I'm seeing here all answers are wrong, especially if you entered the sudo mode, with all returning 'root' instead of the logged in user. The answer is in using 'who' and finding eh 'tty1' user and extracting that. Thw "w" command works the same and var=$SUDO_USER gets the real logged in user.
Cheers!
TBNK
Faced with same issue
ImportError: No module named numpy
So, in our case (we are use PIP and python 2.7) the solution was SPLIT pip install commands :
From
RUN pip install numpy scipy pandas sklearn
TO
RUN pip install numpy scipy
RUN pip install pandas sklearn
Solution found here : https://github.com/pandas-dev/pandas/issues/25193, it's related latest update of pandas to v0.24.0
It's been a lot of times and there are lots of valid answers, but the following code block seems to work:
my_object = SqlAlchemyModel()
my_serializable_obj = my_object.__dict__
del my_serializable_obj["_sa_instance_state"]
print(jsonify(my_serializable_object))
I'm aware that this is not a perfect solution, nor as elegant as the others, however for those who want o quick fix, they might try this.
Here's how I did it... No need for try-catch block... The best solution is always the simplest... Enjoy!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}
#include <sstream>
#include <vector>
const char *input = "1,1,1,1,2,1,1,1,0";
int main() {
std::stringstream ss(input);
std::vector<int> output;
int i;
while (ss >> i) {
output.push_back(i);
ss.ignore(1);
}
}
Bad input (for instance consecutive separators) will mess this up, but you did say simple.
Static variables are common across all instances of a type.
constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.
unlike constants, static variable values can be changed at runtime.
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace XML
{
public class Parser
{
private string _FilePath = string.Empty;
private XDocument _XML_Doc = null;
public Parser(string filePath)
{
_FilePath = filePath;
_XML_Doc = XDocument.Load(_FilePath);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
/// </summary>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string attributeName, string newValue)
{
ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) and value (oldValue)
/// with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues),
/// with the specified new value (newValue) in elements with a given name (elementName).
/// If oldValues is empty then oldValues will be ignored.
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValues"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
{
List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();
foreach (XElement element in elements)
{
if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
{
if (element.Attribute(attributeName) != null)
{
if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
{ element.Attribute(attributeName).Value = newValue; }
}
}
}
}
public void SaveChangesToFile()
{
_XML_Doc.Save(_FilePath);
}
}
}
A small note about the efficiency of abovementioned methods:
library(microbenchmark)
microbenchmark(
which("Feb" == month.abb)[[1]],
which(month.abb %in% "Feb"))
Unit: nanoseconds
min lq mean median uq max neval
891 979.0 1098.00 1031 1135.5 3693 100
1052 1175.5 1339.74 1235 1390.0 7399 100
So, the best one is
which("Feb" == month.abb)[[1]]
Apparently in my case the problem was resolved by adding an "*" at the end
import android.R.*;
I had the same requirements as you but couldn't find a suitable database. nStore was promising but the API was not nearly complete enough and not very coherent.
That's why I made NeDB, which a dependency-less embedded database for Node.js projects. You can use it with a simple require()
, it is persistent, and its API is the most commonly used subset of the very well-known MongoDB API.
My experience is, that NIO is much faster with small files. But when it comes to large files FileInputStream/FileOutputStream is much faster.
It's also possible that in persistence.xml, EmbeddedDriver was used while the jdbc url was pointing to Derby server. In this case just change the url to pointing a path of database.
do it the simpler way,
direc=$(basename `pwd`)
Or use the shell
$ direc=${PWD##*/}
As mentioned, in Swift most of the time you can achieve what you need with the ?
optional unwrapper operator. This allows you to call a method on an object if and only if the object exists (not nil
) and the method is implemented.
In the case where you still need respondsToSelector:
, it is still there as part of the NSObject
protocol.
If you are calling respondsToSelector:
on an Obj-C type in Swift, then it works the same as you would expect. If you are using it on your own Swift class, you will need to ensure your class derives from NSObject
.
Here's an example of a Swift class that you can check if it responds to a selector:
class Worker : NSObject
{
func work() { }
func eat(food: AnyObject) { }
func sleep(hours: Int, minutes: Int) { }
}
let worker = Worker()
let canWork = worker.respondsToSelector(Selector("work")) // true
let canEat = worker.respondsToSelector(Selector("eat:")) // true
let canSleep = worker.respondsToSelector(Selector("sleep:minutes:")) // true
let canQuit = worker.respondsToSelector(Selector("quit")) // false
It is important that you do not leave out the parameter names. In this example, Selector("sleep::")
is not the same as Selector("sleep:minutes:")
.
Use Long.parseLong()
Long.parseLong("0", 10) // returns 0L
Long.parseLong("473", 10) // returns 473L
Long.parseLong("-0", 10) // returns 0L
Long.parseLong("-FF", 16) // returns -255L
Long.parseLong("1100110", 2) // returns 102L
Long.parseLong("99", 8) // throws a NumberFormatException
Long.parseLong("Hazelnut", 10) // throws a NumberFormatException
Long.parseLong("Hazelnut", 36) // returns 1356099454469L
Long.parseLong("999") // returns 999L
public class Add {
static int add(int a, int b){
return (a+b);
}
}
In the above example, 'add' is a static method that takes two integers as arguments.
Following snippet is used to call 'add' method with input 1 and 2.
Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);
Reference link.
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
None of the answers here were quite what I wanted. Here's what I came up with:
# Recursively revert any locally-changed files
svn revert -R .
# Delete any other files in the sandbox (including ignored files),
# being careful to handle files with spaces in the name
svn status --no-ignore | grep '^\?' | \
perl -ne 'print "$1\n" if $_ =~ /^\S+\s+(.*)$/' | \
tr '\n' '\0' | xargs -0 rm -rf
Tested on Linux; may work in Cygwin, but relies on (I believe) a GNU-specific extension which allows xargs to split based on '\0'
instead of whitespace.
The advantage to the above command is that it does not require any network activity to reset the sandbox. You get exactly what you had before, and you lose all your changes. (disclaimer before someone blames me for this code destroying their work) ;-)
I use this script on a continuous integration system where I want to make sure a clean build is performed after running some tests.
Edit: I'm not sure this works with all versions of Subversion. It's not clear if the svn status
command is always formatted consistently. Use at your own risk, as with any command that uses such a blanket rm
command.
If you're using jQuery ...
$('div').html('');
or
$('div').empty();
Communicating through processes
Example:
Python: This python code block should return random temperatures.
# sensor.py
import random, time
while True:
time.sleep(random.random() * 5) # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5 # -5 to 15
print(temperature, flush=True, end='')
Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.
// temperature-listener.js
const { spawn } = require('child_process');
const temperatures = []; // Store readings
const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {
// convert Buffer object to Float
temperatures.push(parseFloat(data));
console.log(temperatures);
});
I achieved the same thing using a local web server and PHP. I used a script containing shell_exec
to launch an application locally.
Alternatively, you could do something like this:
<a href="file://C:/Windows/notepad.exe">Notepad</a>
Use YAML files for properties, this supports properties as an array.
Quick glance about YAML:
A superset of JSON, it can do everything JSON can + more
To delete all DBs use:
for i in $(mongo --quiet --host $HOSTNAME --eval "db.getMongo().getDBNames()" | tr "," " ");
do mongo $i --host $HOSTNAME --eval "db.dropDatabase()";
done
If you use two databases you can add another DataClasses.dbml and map the second database into it.
It works.
@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.
Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.
So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.
UPDATE: Working from the comments, I built this:
ServicePointManager.SecurityProtocol = 0;
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
{
switch (protocol)
{
case SecurityProtocolType.Ssl3:
case SecurityProtocolType.Tls:
case SecurityProtocolType.Tls11:
break;
default:
ServicePointManager.SecurityProtocol |= protocol;
break;
}
}
In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:
HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
request.GetResponse();
while this worked:
HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
request.GetResponse();
This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.
Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.
Guid id = Guid.NewGuid();
change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.
There is no mention that B5 contains any value so assuming 80%
is .8
formatted as percentage without decimals and blank counts as "below":
Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:
=C5>0.8
with green fill and Done.
List it under technologies or something. I'd just leave it off if I were you as it's pretty much expected that you know HTML and XML at this point.
This error means that length of index index
is more then 1000 bytes. MySQL and storage engines may have this restriction. I have got similar error on MySQL 5.5 - 'Specified key was too long; max key length is 3072 bytes' when ran this script:
CREATE TABLE IF NOT EXISTS test_table1 (
column1 varchar(500) NOT NULL,
column2 varchar(500) NOT NULL,
column3 varchar(500) NOT NULL,
column4 varchar(500) NOT NULL,
column5 varchar(500) NOT NULL,
column6 varchar(500) NOT NULL,
KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UTF8 is multi-bytes, and key length is calculated in this way - 500 * 3 * 6 = 9000 bytes.
But note, next query works!
CREATE TABLE IF NOT EXISTS test_table1 (
column1 varchar(500) NOT NULL,
column2 varchar(500) NOT NULL,
column3 varchar(500) NOT NULL,
column4 varchar(500) NOT NULL,
column5 varchar(500) NOT NULL,
column6 varchar(500) NOT NULL,
KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
...because I used CHARSET=latin1, in this case key length is 500 * 6 = 3000 bytes.
I corrected this error as there was a syntax error or some unwanted characters in the query, but MySQL was not able to catch it. I was using and
in between multiple fields during update, e.g.
update user
set token='lamblala',
accessverion='dummy' and
key='somekey'
where user = 'myself'
The problem in above query can be resolved by replacing and
with comma(,
)
On the command line, \r will move the cursor back to the beginning of the current line. To see the difference you must run your code from a command prompt. Eclipse's console show similar output for both the expression. For complete list of escape sequences, click here https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.6
$("element").data('bs.modal').isShown
won't work if the modal hasn't been shown before. You will need to add an extra condition:
$("element").data('bs.modal')
so the answer taking into account first appearance:
if ($("element").data('bs.modal') && $("element").data('bs.modal').isShown){
...
}
CodeIgniter returns result rows as objects, not arrays. From the user guide:
result()
This function returns the query result as an array of objects, or an empty array on failure.
You'll have to access the fields using the following notation:
foreach ($getvidids->result() as $row) {
$vidid = $row->videoid;
}
Here is some code to apply binary mask on a video frame sequence acquired from a webcam. comment and uncomment the "bitwise_not(Mon_mask,Mon_mask);"line and see the effect.
bests, Ahmed.
#include "cv.h" // include it to used Main OpenCV functions.
#include "highgui.h" //include it to use GUI functions.
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
int c;
int radius=100;
CvPoint2D32f center;
//IplImage* color_img;
Mat image, image0,image1;
IplImage *tmp;
CvCapture* cv_cap = cvCaptureFromCAM(0);
while(1) {
tmp = cvQueryFrame(cv_cap); // get frame
// IplImage to Mat
Mat imgMat(tmp);
image =tmp;
center.x = tmp->width/2;
center.y = tmp->height/2;
Mat Mon_mask(image.size(), CV_8UC1, Scalar(0,0,0));
circle(Mon_mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); //-1 means filled
bitwise_not(Mon_mask,Mon_mask);// commenté ou pas = RP ou DMLA
if(tmp != 0)
imshow("Glaucom", image); // show frame
c = cvWaitKey(10); // wait 10 ms or for key stroke
if(c == 27)
break; // if ESC, break and quit
}
/* clean up */
cvReleaseCapture( &cv_cap );
cvDestroyWindow("Glaucom");
}
Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.
#!/usr/bin/python
import sys, socket
def main(args):
ip = args[1]
port = int(args[2])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
file = 'sample.csv'
fp = open(file, 'r')
for line in fp:
sock.sendto(line.encode('utf-8'), (ip, port))
fp.close()
main(sys.argv)
The program reads a file, sample.csv
from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp
then one could run it by doing something like:
$ python send-udp 192.168.1.2 30088
Follow these steps, respectively for rename column migration file.
1- Is there Doctrine/dbal library in your project. If you don't have run the command first
composer require doctrine/dbal
2- create update migration file for update old migration file. Warning (need to have the same name)
php artisan make:migration update_oldFileName_table
for example my old migration file name: create_users_table update file name should : update_users_table
3- update_oldNameFile_table.php
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});
'from' my old column name and 'to' my new column name
4- Finally run the migrate command
php artisan migrate
Source link: laravel document
You need also to set .min-height: 0px;
please see bellow:
.navbar-inner {
min-height: 0px;
}
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
If you set .min-height: 0px;
then you can choose any height you want!
Good Luck!
<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>
This work for me.
edit: An example with your snippet:
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
.container {_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row-fluid">_x000D_
<div class="span6 pull-left">_x000D_
<p>Text left</p>_x000D_
</div>_x000D_
<div class="span6 text-right">_x000D_
<p>text right</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
\p{L}
matches a single code point in the category "letter".
\p{N}
matches any kind of numeric character in any script.
Source: regular-expressions.info
If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.
SQL Server allows the following (be careful to use single quotes instead of double)
UPDATE User
SET UserId = 12345
, Name = 'J Doe'
, Location = 'USA'
, Bio='my bio
spans
multiple
lines!'
WHERE UserId = 12345
What @Nilsi mentioned is perfectly correct. However, adminclass and user class need to be wrapped in single quotes as this might fail due to Thymeleaf looking for adminClass or userclass variables which should be strings. That said,
it should be: -
<a href="" class="baseclass" th:classappend="${isAdmin} ? 'adminclass' :
'userclass'">
</a>
or just:
<a href="" th:class="${isAdmin} ? 'newclass' :
'baseclass'">
</a>
Maps from JDK are not meant for storing data under duplicated keys.
At best new value will override the previous ones.
Worse scenario is exception (e.g when you try to collect it as a stream):
No duplicates:
Stream.of("one").collect(Collectors.toMap(x -> x, x -> x))
Ok. You will get: $2 ==> {one=one}
Duplicated stream:
Stream.of("one", "not one", "surely not one").collect(Collectors.toMap(x -> 1, x -> x))
Exception java.lang.IllegalStateException: Duplicate key 1 (attempted merging values one and not one) | at Collectors.duplicateKeyException (Collectors.java:133) | at Collectors.lambda$uniqKeysMapAccumulator$1 (Collectors.java:180) | at ReduceOps$3ReducingSink.accept (ReduceOps.java:169) | at Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948) | at AbstractPipeline.copyInto (AbstractPipeline.java:484) | at AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:474) | at ReduceOps$ReduceOp.evaluateSequential (ReduceOps.java:913) | at AbstractPipeline.evaluate (AbstractPipeline.java:234) | at ReferencePipeline.collect (ReferencePipeline.java:578) | at (#4:1)
To deal with duplicated keys - use other package, e.g: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html
There is a lot of other implementations dealing with duplicated keys. Those are needed for web (e.g. duplicated cookie keys, Http headers can have same fields, ...)
Good luck! :)
Other answers here seem to favor omitting the trailing slash. There is one case in which a trailing slash will help with search engine optimization (SEO). That is the case that your document has what appears to be a file extension that is not .html
. This becomes an issue with sites that are rating websites. They might choose between these two urls:
http://mysite.example.com/rated.example.com
http://mysite.example.com/rated.example.com/
In such a case, I would choose the one with the trailing slash. That is because the .com
extension is an extension for Windows executable command files. Search engines and virus checkers often dislike URLs that appear that they may contain malware distributed through such mechanisms. The trailing slash seems to mitigate any concerns, allowing the page to rank in search engines and get by virus checkers.
If your URLs have no .
in the file portion, then I would recommend omitting the trailing slash for simplicity.
I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:
"%1"=="-?"
will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?
starting parameter test...
Condition is true, param=-?
C:\>test.bat "-?"
starting parameter test...
Condition is false, param="-?"
Any combination with square brackets [%1]==[-?]
or [%~1]==[-?]
will fail in case the parameter has spaces within quotes:
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat "long file name"
starting parameter test...
First parameter is "long file name"
file was unexpected at this time.
The proposed safest solution "%~1"=="-?"
will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -source:"long file name"
starting parameter test...
First parameter is -source:"long file name"
file was unexpected at this time.
The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:
@ECHO OFF
SETLOCAL EnableDelayedExpansion
echo.
echo starting parameter test...
echo.
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png
starting parameter test...
First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png
C:\>test.bat -source:"c:\app images"\image1.png
starting parameter test...
First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png
C:\>test.bat -source:"c:\app images\image.png"
starting parameter test...
First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"
Looking at the source code I also think there must be some issue with the private key.
What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.
If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.
(see source code from class SecureChannnel, method EnsurePrivateKey)
So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.
You can activate Network Tracing to try to debug this. It will give you output like this:
Right Click the form you want to hide them on, choose Controls -> Properties.
In Properties, set
You'll do this in the designer.
Please use chomp()
or chomp()
with STDIN
i.e. test1.rb
print 'Enter File name: '
fname = STDIN.gets.chomp() # or fname = gets.chomp()
fname_read = File.open(fname)
puts fname_read.read()
Starting with .net framework 4.6 / .net core 1.0, there is now a AppContext.BaseDirectory, which should give the same result as AppDomain.CurrentDomain.BaseDirectory
, except that AppDomains were not part of the .net core 1.x /.net standard 1.x API.
AppContext.BaseDirectory
Create outlets from views that were created in StoryBoard.
@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var greenView: UIView!
Override the touchesBegan method. There are 2 options, everyone can determine which one is better for him.
Detect touch in special view.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
if touch.view == self.redView {
tapOnredViewTapped()
} else if touch.view == self.orangeView {
orangeViewTapped()
} else if touch.view == self.greenView {
greenViewTapped()
} else {
return
}
}
}
Detect touch point on special view.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: view)
if redView.frame.contains(location) {
redViewTapped()
} else if orangeView.frame.contains(location) {
orangeViewTapped()
} else if greenView.frame.contains(location) {
greenViewTapped()
}
}
}
Lastly, you need to declare the functions that will be called, depending on which view the user clicked.
func redViewTapped() {
print("redViewTapped")
}
func orangeViewTapped() {
print("orangeViewTapped")
}
func greenViewTapped() {
print("greenViewTapped")
}
You can use the following format to generate a tooltip for an image.
<div class="tooltip"><img src="joe.jpg" />
<span class="tooltiptext">Tooltip text</span>
</div>
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Hope it helps.
Note: Apple may reject (0.01% chances) your app as we are accessing private API. I am using this in all my projects since two years, but Apple didn't ask for this.
openecry.com is a broker with plenty of information on an API and instructions on how to do yours. There are also other brokers with the OEC platform and all the bells and whistles a pro could ask for.
This is the jQuery method. Looks like overkill but it calculates the offset.
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/dreamerslab/jquery.center/master/jquery.center.js"></script>
<script type="text/javascript">
$(function(){
$('#jquery-center').center();
});
</script>
</head>
<body>
<div id="jquery-center" style="position:absolute;">
<h1>foo</h1>
</div>
</body>
</html>
For bitbucket repository, generate App Password (Bitbucket settings -> Access Management -> App Password, see the image) with read access to the repo and project.
Then the command that you should use is:
git clone https://username:[email protected]/reponame/projectname.git
Not if you want it to resolve on the Internet.
You cannot have: http://my_subdomain.example.com is invalid.
You can have: http://my-subdomain.example.com with a hyphen.
I like that one, because you can "define rules" for the arguments, needed or not,...
or if you're a Unix guy, than you might like the GNU Getopt .NET port.
For example this will start XBMC:
adb shell am start -a android.intent.action.MAIN -n org.xbmc.xbmc/android.app.NativeActivity
(More general answers are already posted, but I missed a nice example here.)
if you go to Quick Access and type in Projects you will get it your projects back.
Old question but just had that problem /dumb jira having problems with java 10/ and didn't find a simple answer here so just gonna leave it:
$ /usr/libexec/java_home -V
shows the versions installed and their locations so you can simply remove /Library/Java/JavaVirtualMachines/<the_version_you_want_to_remove>
. Voila
In my case opening 'Help' >> "Install New Software" had no entries for any URLs (previous url's were not there) - so I Manually added 'em. And updated ... and Voilaaaa !! Above posts have been very helpful in resolving this issue for me.
The problem in your code is xml.LoadXml(filePath);
LoadXml
method take parameter as xml data not the xml file path
Try this code
string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlFile);
XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
string Short_Fall=string.Empty;
foreach (XmlNode node in nodeList)
{
Short_Fall = node.InnerText;
}
Edit
Seeing the last edit of your question i found the solution,
Just replace the below 2 lines
XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")
with
string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;
It should solve your problem or you can use the solution i provided earlier.
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
Just improved phihag's code because it runs into a infinite loop if file not exists.
<?php
$filename = "so-csv.csv";
echo "<html><body><table>\n\n";
if (file_exists($filename)) {
$f = fopen($filename, "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
}
else{ echo "<tr><td>No file exists ! </td></tr>" ;}
echo "\n</table></body></html>";
?>
This is what I got from oracle documentation, but it is for oracle 10g release 2:
When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.
The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:
Reason seems to be that the public key of the remote host is not stored or different from the stored one. (Be aware of security issues, see Greg Bacon's answer for details.)
I was used to git clone
prompting me in this case:
The authenticity of host 'host.net (10.0.0.42)' can't be established.
ECDSA key fingerprint is 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00.
Are you sure you want to continue connecting (yes/no)?
Not sure, why this error is thrown instead. Could be the configuration of your shell or the git SSH command.
Anyhow, you can get the same prompt by running ssh [email protected]
.
I got the same error:
nodemon -w server.js server.js
[nodemon] 2.0.2
[nodemon] reading config .\nodemon.json
[nodemon] to restart at any time, enter `rs`
[nodemon] or send SIGHUP to 19248 to restart
[nodemon] ignoring: .\node_modules/**/* .\.next/**/*
[nodemon] watching dir(s): server.js
[nodemon] watching extensions: js,json
[nodemon] starting `node server.js index.js`
[nodemon] forking
[nodemon] child pid: 18840
[nodemon] watching 30 files
internal/modules/cjs/loader.js:797
throw err;
^
Error: Cannot find module 'D:\Programming\01a.nextjs\project\index.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
at Function.Module._load (internal/modules/cjs/loader.js:687:27)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
[nodemon] app crashed - waiting for file changes before starting...
I followed all the advises from here, but none of them worked for me. What I found is that I moved the server.js in his own folder server/server.js, but in package.json I forgot to make the change from this:
"dev": "nodemon -w server.js server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
to this:
"dev": "nodemon -w server/server.js server/server.js",
"build": "next build",
"start": "NODE_ENV=production node server/server.js"
After I made this change and restart the server with npm run dev
everything worked fine.
Complementing Elmer's answer, as my edit was rolled back.
To cache static content for 365 days with public cache-control header, IIS can be configured with the following
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
This will translate into a header like this:
Cache-Control: public,max-age=31536000
Note that max-age is a delta in seconds, being expressed by a positive 32bit integer as stated in RFC 2616 Sections 14.9.3 and 14.9.4. This represents a maximum value of 2^31 or 2,147,483,648 seconds (over 68 years). However, to better ensure compatibility between clients and servers, we adopt a recommended maximum of 365 days (one year).
As mentioned on other answers, you can use these directives also on the web.config of your site for all static content. As an alternative, you can use it only for contents in a specific location too (on the sample, 30 days public cache for contents in "cdn" folder):
<location path="cdn">
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00"/>
</staticContent>
</system.webServer>
</location>
This is why you should always import the base datetime
module: import datetime
, rather than the datetime
class within that module: from datetime import datetime
.
The other mistake you have made is to actually call the function in the default, with the ()
. This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.
So the field should be:
import datetime
date = models.DateField(_("Date"), default=datetime.date.today)
No. Either use readFile
or readFileSync
(The latter only at startup time).
Or use an existing library like
Alternatively write your config in a js file rather then a json file like
module.exports = {
// json
}
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
I had this issue, and I set the Locale
to US
, then it work.
static DateFormat visitTimeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US);
for String
"Sun Jul 08 00:06:30 UTC 2012"
Use the PasteSpecial method:
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).
Very easily we can parse JSON content with the help of dictionary and JavaScriptSerializer. Here is the sample code by which I parse JSON content from an ashx file.
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string _Name = sData["Name"].ToString();
string _Subject = sData["Subject"].ToString();
string _Email = sData["Email"].ToString();
string _Details = sData["Details"].ToString();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>`enter code here`
$(document).ready(function () {
var result=1;
$('input').keyup(function(){`enter code here`
$('tr').each(function () {
var sum = $(this).find('td.combat').text();
var combat = $(this).find('input.combat').val();
if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
result = parseFloat(sum)*parseFloat(combat);
}
$(this).find('.total-combat').html(result);
});
});
$('.add').click(function(){
var sno = $(this).parent().siblings('.sno').text();
var cust = $(this).parent().siblings('.cust').text();
var price = $(this).parent().siblings('td.combat').text();
var rowValue = [];
$(this).closest('tr').find("input").each(function() {
rowValue.push($(this).val());
return $(this).val();
});
var rowValue1 = [];
$(this).closest('tr').find("span").each(function() {
rowValue1.push($(this).text());
return $(this).val();
});
var markup = "<tr><td class='sno'>" + sno + "</td><td class='custname'>" + cust +"</td><td class='price'>" + price +"</td><td><input type='text' class='newtext' value="+ rowValue[0] +"></td><td class='total'>" + rowValue1[0] +"</td><td><input type='submit' class='update' value='upd'><input type='button' class='del' value='del'></td></tr>";
var rightcol = $(this).closest('tr').find(".cust");
var row_count = $('.tbl1 tbody tr').length;
alert(row_count);
if (row_count == 0) {
$(".tbl1 tbody").append(markup);
}
else
{
var tes=0;
$('.tbl1 tbody tr').each(function(){
var leftcol = $(this).find(".custname");
if(rightcol.html() == leftcol.html()) {
alert(leftcol.html()+"-----------------"+rightcol.html());
$(this).find('.sno').text(sno);
$(this).find('.custname').text(cust);
$(this).find('.price').text(price);
$(this).find('.newtext').val(rowValue[0]);
$(this).find('.total').text(rowValue1[0]);
tes++;
}
});
if(tes==0){
$(".tbl1 tbody").append(markup);
}
}
});
$(".tb").on("click", ".update", function(e) {
var rowValues = [];
$(this).closest('tr').find("input").each(function() {
rowValues.push($(this).val());
return $(this).val();
});
var total=$(this).closest('tr').find('.total').text();
var right_cols = $(this).closest('tr').find(".custname");
$('.tbl tbody tr').each(function(){
var row = $(this);
var left_cols = $(this).find(".cust");
if(left_cols.html() == right_cols.html()) {
$(this).find('.text').val(rowValues[0]);
$(this).find('.total-combat').text(total);
}
});
});
$(".tb").on("keyup", "input", function() {
$('tr').each(function () {
var sum = $(this).find('td.price').text();
var combat = $(this).find('input.newtext').val();
if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
result = parseFloat(sum)*parseFloat(combat);
}
$(this).find('.total').html(result);
});
});
$(".tb").on("click", ".del", function() {
$(this).closest('tr').remove();
});
});
</script>
<style>
.table_style {
width: 500px;
margin: 0px auto;
}
table{
width: 100%;
border-collapse: collapse;
}
table tr td{
width: 50%;
border: 5px solid #ff751a;
padding: 5px;
}
table tr th{
border: 5px solid #79ff4d;
padding: 5px;
}
input{
width:35px;
}
.tbl1{
margin-top: 50px;
border: 0px solid #cdcdcd;
}
.btn{
float:left;
}
</style>
<title>E-Commerce-Table</title>
</head>
<body>
<div class="table_style">
<caption>Price-List</caption>
<table class="tbl">
<tr>
<th>S.No</th>
<th>P.Name</th>
<th>Price</th>
<th>Qnty</th>
<th>Rate</th>
<th>action</th>
</tr>
<tbody>
<tr>
<td class="sno">1</td>
<td class="cust">A</td>
<td class="combat">5</td>
<td class="tester"><input type="number" id="qnty1" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">2</td>
<td class="cust">B</td>
<td class="combat">8</td>
<td><input type="number" id="qnty2" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">3</td>
<td class="cust">C</td>
<td class="combat">7</td>
<td><input type="number" id="qnty3" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">4</td>
<td class="cust">D</td>
<td class="combat">2</td>
<td><input type="number" id="qnty4" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
</tbody>
</table>
<table class="tbl1">
<thead>
<tr>
<th>S.No</th>
<th>P.Name</th>
<th>Price</th>
<th>Qnty</th>
<th>Rate</th>
<th>action</th>
</tr>
</thead>
<tbody class="tb">
</tbody>
</table>
<button type="submit" name="addtocart" id="btn">Add-to-cart</button>
</div>
</body>
</html>
The API docs give some good hints:
print() ? nil
print(obj, ...) ? nil
Writes the given object(s) to ios. Returns
nil
.The stream must be opened for writing. Each given object that isn't a string will be converted by calling its
to_s
method. When called without arguments, prints the contents of$_
.If the output field separator (
$,
) is notnil
, it is inserted between objects. If the output record separator ($\
) is notnil
, it is appended to the output....
puts(obj, ...) ? nil
Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns
nil
.The stream must be opened for writing. If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its
to_s
method. If called without arguments, outputs a single newline.
Experimenting a little with the points given above, the differences seem to be:
Called with multiple arguments, print
separates them by the 'output field separator' $,
(which defaults to nothing) while puts
separates them by newlines. puts
also puts a newline after the final argument, while print
does not.
2.1.3 :001 > print 'hello', 'world'
helloworld => nil
2.1.3 :002 > puts 'hello', 'world'
hello
world
=> nil
2.1.3 :003 > $, = 'fanodd'
=> "fanodd"
2.1.3 :004 > print 'hello', 'world'
hellofanoddworld => nil
2.1.3 :005 > puts 'hello', 'world'
hello
world
=> nil
puts
automatically unpacks arrays, while print
does not:
2.1.3 :001 > print [1, [2, 3]], [4] [1, [2, 3]][4] => nil 2.1.3 :002 > puts [1, [2, 3]], [4] 1 2 3 4 => nil
print
with no arguments prints $_
(the last thing read by gets
), while puts
prints a newline:
2.1.3 :001 > gets
hello world
=> "hello world\n"
2.1.3 :002 > puts
=> nil
2.1.3 :003 > print
hello world
=> nil
print
writes the output record separator $\
after whatever it prints, while puts
ignores this variable:
mark@lunchbox:~$ irb
2.1.3 :001 > $\ = 'MOOOOOOO!'
=> "MOOOOOOO!"
2.1.3 :002 > puts "Oink! Baa! Cluck! "
Oink! Baa! Cluck!
=> nil
2.1.3 :003 > print "Oink! Baa! Cluck! "
Oink! Baa! Cluck! MOOOOOOO! => nil
The best practice is to reference the WSDL and use it like a web service reference. It's easier and works better, but if you don't have the WSDL, the XSD definitions are a good piece of code.
Assuming you have a module file called Dummy-Name.psm1 which has a method called Function-Dumb()
Import-Module "Dummy-Name.psm1";
Get-Command -Module "Function-Dumb";
#
#
Function-Dumb;
I had this problem just now and solved it by removing the --recursive
option (which I had set) and using the same structure suggested above:
mochify "test/unit/**/*.js"
This ran all tests in all directories under /test/unit/
for me while ignoring the other directories within /test/
add a float property to the #main_content
div - it will then expand to contain its floated contents
Use rgba()
:
.transparent {
background-color: rgba(255,255,255,0.5);
}
This will give you 50% opacity while the content of the box will continue to have 100% opacity.
If you use opacity:0.5
, the content will be faded as well as the background. Hence do not use it.
Now Accepting Larger Binaries February 12, 2015
The size limit of an app package submitted through iTunes Connect has increased from 2 GB to 4 GB, so you can include more media in your submission and provide a more complete, rich user experience upon installation. Please keep in mind that this change does not affect the cellular network delivery size limit of 100 MB.
Open Tools -> Options -> Keymap, then look for the action called "Re-indent current line or selection" and set whatever shortcut you want.
You are looking for dynamic_cast<B*>(pointer)
Python 3.x:
for i in range(20):
print('a', end='')
Python 2.6 or 2.7:
from __future__ import print_function
for i in xrange(20):
print('a', end='')
$('#txtConfirmPassword').keyup(function(){
if($(this).val() != $('#txtNewPassword').val().substr(0,$(this).val().length))
{
alert('confirm password not match');
}
});
Intent intent = null;
try {
getPackageManager().getPackageInfo("com.facebook.katana", 0);
String url = "https://www.facebook.com/"+idFacebook;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href="+url));
} catch (Exception e) {
// no Facebook app, revert to browser
String url = "https://facebook.com/"+idFacebook;
intent = new Intent(Intent.ACTION_VIEW);
intent .setData(Uri.parse(url));
}
this.startActivity(intent);
Objects does not support push property, but you can save it as well using the index as key,
var tempData = {};_x000D_
for ( var index in data ) {_x000D_
if ( data[index].Status == "Valid" ) { _x000D_
tempData[index] = data; _x000D_
} _x000D_
}_x000D_
data = tempData;
_x000D_
I think this is easier if remove the object if its status is invalid, by doing.
for(var index in data){_x000D_
if(data[index].Status == "Invalid"){ _x000D_
delete data[index]; _x000D_
} _x000D_
}
_x000D_
And finally you don't need to create a var temp –
You could use this:
if(drEntity.ItemArray.Where(c => IsNotEmpty(c)).ToArray().Length == 0)
{
// Row is empty
}
IsNotEmpty(cell)
would be your own implementation, checking whether the data is null or empty, based on what type of data is in the cell. If it's a simple string, it could end up looking something like this:
if(drEntity.ItemArray.Where(c => c != null && !c.Equals("")).ToArray().Length == 0)
{
// Row is empty
}
else
{
// Row is not empty
}
Still, it essentially checks each cell for emptiness, and lets you know whether all cells in the row are empty.
Since you're using jQuery, stop binding event handlers in your HTML, and start writing unobtrusive JavaScript.
$(document).ready(function ()
{
function myfunction(me)
{
$(me).fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true // remove the trailing comma!!
}).click();
// fire the click event after initializing fancybox on this element
// this should open the fancybox
}
// use .one() so that the handler is executed at most once per element
$('a[href=#modalMine]').one('click', function ()
{
myfunction(this);
return false;
});
});
However, I don't particularly see a reason for setting up the fancybox on click. You could just do this instead:
$(document).ready(function ()
{
function myfunction()
{
// note the use of "this" rather than a function argument
$(this).fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true
});
}
$('a[href=#modalMine]').each(myfunction);
});
Courtesy of this post, you can do the following:
from IPython.display import Image
Image(filename='test.png')
Python 2 didn't have closures - it had workarounds that resembled closures.
There are plenty of examples in answers already given - copying in variables to the inner function, modifying an object on the inner function, etc.
In Python 3, support is more explicit - and succinct:
def closure():
count = 0
def inner():
nonlocal count
count += 1
print(count)
return inner
Usage:
start = closure()
start() # prints 1
start() # prints 2
start() # prints 3
The nonlocal
keyword binds the inner function to the outer variable explicitly mentioned, in effect enclosing it. Hence more explicitly a 'closure'.
Another option:
"My name is Milan, people know me as Milan Vasic"
.replaceAll("Milan Vasic|Milan", "Milan Vasic"))
Bash doesn't have multi-dimensional array. But you can simulate a somewhat similar effect with associative arrays. The following is an example of associative array pretending to be used as multi-dimensional array:
declare -A arr
arr[0,0]=0
arr[0,1]=1
arr[1,0]=2
arr[1,1]=3
echo "${arr[0,0]} ${arr[0,1]}" # will print 0 1
If you don't declare the array as associative (with -A
), the above won't work. For example, if you omit the declare -A arr
line, the echo
will print 2 3
instead of 0 1
, because 0,0
, 1,0
and such will be taken as arithmetic expression and evaluated to 0
(the value to the right of the comma operator).
I have different approach if you want access token and make call to other resource system with access token in header
Spring Security comes with automatic security: oauth2 properties access from application.yml file for every request and every request has SESSIONID which it reads and pull user info via Principal, so you need to make sure inject Principal in OAuthUser and get accessToken and make call to resource server
This is your application.yml, change according to your auth server:
security:
oauth2:
client:
clientId: 233668646673605
clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
accessTokenUri: https://graph.facebook.com/oauth/access_token
userAuthorizationUri: https://www.facebook.com/dialog/oauth
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: https://graph.facebook.com/me
@Component
public class OAuthUser implements Serializable {
private static final long serialVersionUID = 1L;
private String authority;
@JsonIgnore
private String clientId;
@JsonIgnore
private String grantType;
private boolean isAuthenticated;
private Map<String, Object> userDetail = new LinkedHashMap<String, Object>();
@JsonIgnore
private String sessionId;
@JsonIgnore
private String tokenType;
@JsonIgnore
private String accessToken;
@JsonIgnore
private Principal principal;
public void setOAuthUser(Principal principal) {
this.principal = principal;
init();
}
public Principal getPrincipal() {
return principal;
}
private void init() {
if (principal != null) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
if (oAuth2Authentication != null) {
for (GrantedAuthority ga : oAuth2Authentication.getAuthorities()) {
setAuthority(ga.getAuthority());
}
setClientId(oAuth2Authentication.getOAuth2Request().getClientId());
setGrantType(oAuth2Authentication.getOAuth2Request().getGrantType());
setAuthenticated(oAuth2Authentication.getUserAuthentication().isAuthenticated());
OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) oAuth2Authentication
.getDetails();
if (oAuth2AuthenticationDetails != null) {
setSessionId(oAuth2AuthenticationDetails.getSessionId());
setTokenType(oAuth2AuthenticationDetails.getTokenType());
// This is what you will be looking for
setAccessToken(oAuth2AuthenticationDetails.getTokenValue());
}
// This detail is more related to Logged-in User
UsernamePasswordAuthenticationToken userAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
if (userAuthenticationToken != null) {
LinkedHashMap<String, Object> detailMap = (LinkedHashMap<String, Object>) userAuthenticationToken.getDetails();
if (detailMap != null) {
for (Map.Entry<String, Object> mapEntry : detailMap.entrySet()) {
//System.out.println("#### detail Key = " + mapEntry.getKey());
//System.out.println("#### detail Value = " + mapEntry.getValue());
getUserDetail().put(mapEntry.getKey(), mapEntry.getValue());
}
}
}
}
}
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getGrantType() {
return grantType;
}
public void setGrantType(String grantType) {
this.grantType = grantType;
}
public boolean isAuthenticated() {
return isAuthenticated;
}
public void setAuthenticated(boolean isAuthenticated) {
this.isAuthenticated = isAuthenticated;
}
public Map<String, Object> getUserDetail() {
return userDetail;
}
public void setUserDetail(Map<String, Object> userDetail) {
this.userDetail = userDetail;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public String toString() {
return "OAuthUser [clientId=" + clientId + ", grantType=" + grantType + ", isAuthenticated=" + isAuthenticated
+ ", userDetail=" + userDetail + ", sessionId=" + sessionId + ", tokenType="
+ tokenType + ", accessToken= " + accessToken + " ]";
}
@RestController
public class YourController {
@Autowired
OAuthUser oAuthUser;
// In case if you want to see Profile of user then you this
@RequestMapping(value = "/profile", produces = MediaType.APPLICATION_JSON_VALUE)
public OAuthUser user(Principal principal) {
oAuthUser.setOAuthUser(principal);
// System.out.println("#### Inside user() - oAuthUser.toString() = " + oAuthUser.toString());
return oAuthUser;
}
@RequestMapping(value = "/createOrder",
method = RequestMethod.POST,
headers = {"Content-type=application/json"},
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public FinalOrderDetail createOrder(@RequestBody CreateOrder createOrder) {
return postCreateOrder_restTemplate(createOrder, oAuthUser).getBody();
}
private ResponseEntity<String> postCreateOrder_restTemplate(CreateOrder createOrder, OAuthUser oAuthUser) {
String url_POST = "your post url goes here";
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", String.format("%s %s", oAuthUser.getTokenType(), oAuthUser.getAccessToken()));
headers.add("Content-Type", "application/json");
RestTemplate restTemplate = new RestTemplate();
//restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<String> request = new HttpEntity<String>(createOrder, headers);
ResponseEntity<String> result = restTemplate.exchange(url_POST, HttpMethod.POST, request, String.class);
System.out.println("#### post response = " + result);
return result;
}
}
npm install node-sass
will do the job in most of the cases, as it will add missing sass npm dependency module doesn't exist or it will overwrite previous crashed version.
For Mac Users use sudo
in front of above commands.
On Windows machines npm rebuild node-sass --force
may not work for some users because it's essentially saying, "please force npm to rebuild the sass node module for me". It will not work because that module doesn't exist.
Whenever you did npm install
to the initial installation, the sass module did not get installed, which is why this problem occurs.
This setting goes in your web.config file. It affects the entire application, though... I don't think you can set it per page.
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
"xxx" is in KB. The default is 4096 (= 4 MB).
There is no such flag, and having one runs against the Unix philosophy of having each tool perform just one function and perform it well. Spawning compiler processes is conceptually the job of the build system. What you are probably looking for is the -j (jobs) flag to GNU make, a la
make -j4
Or you can use pmake or similar parallel make systems.
These are all great suggestions, but if I were you, I would do this in your view model. Within your view model, you can create a relay command that you can then bind to the click event in your item template. To determine if the same item was selected, you can store a reference to your selected item in your view model. I like to use MVVM Light to handle the binding. This makes your project much easier to modify in the future, and allows you to set the binding in Blend.
When all is said and done, your XAML will look like what Sergey suggested. I would avoid using the code behind in your view. I'm going to avoid writing code in this answer, because there is a ton of examples out there.
Here is one: How to use RelayCommand with the MVVM Light framework
If you require an example, please comment, and I will add one.
~Cheers
I said I wasn't going to do an example, but I am. Here you go.
1) In your project, add MVVM Light Libraries Only.
2) Create a class for your view. Generally speaking, you have a view model for each view (view: MainWindow.xaml && viewModel: MainWindowViewModel.cs)
3) Here is the code for the very, very, very basic view model:
All included namespace (if they show up here, I am assuming you already added the reference to them. MVVM Light is in Nuget)
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Now add a basic public class:
/// <summary>
/// Very basic model for example
/// </summary>
public class BasicModel
{
public string Id { get; set; }
public string Text { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="text"></param>
public BasicModel(string text)
{
this.Id = Guid.NewGuid().ToString();
this.Text = text;
}
}
Now create your viewmodel:
public class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
ModelsCollection = new ObservableCollection<BasicModel>(new List<BasicModel>() {
new BasicModel("Model one")
, new BasicModel("Model two")
, new BasicModel("Model three")
});
}
private BasicModel _selectedBasicModel;
/// <summary>
/// Stores the selected mode.
/// </summary>
/// <remarks>This is just an example, may be different.</remarks>
public BasicModel SelectedBasicModel
{
get { return _selectedBasicModel; }
set { Set(() => SelectedBasicModel, ref _selectedBasicModel, value); }
}
private ObservableCollection<BasicModel> _modelsCollection;
/// <summary>
/// List to bind to
/// </summary>
public ObservableCollection<BasicModel> ModelsCollection
{
get { return _modelsCollection; }
set { Set(() => ModelsCollection, ref _modelsCollection, value); }
}
}
In your viewmodel, add a relaycommand. Please note, I made this async and had it pass a parameter.
private RelayCommand<string> _selectItemRelayCommand;
/// <summary>
/// Relay command associated with the selection of an item in the observablecollection
/// </summary>
public RelayCommand<string> SelectItemRelayCommand
{
get
{
if (_selectItemRelayCommand == null)
{
_selectItemRelayCommand = new RelayCommand<string>(async (id) =>
{
await selectItem(id);
});
}
return _selectItemRelayCommand;
}
set { _selectItemRelayCommand = value; }
}
/// <summary>
/// I went with async in case you sub is a long task, and you don't want to lock you UI
/// </summary>
/// <returns></returns>
private async Task<int> selectItem(string id)
{
this.SelectedBasicModel = ModelsCollection.FirstOrDefault(x => x.Id == id);
Console.WriteLine(String.Concat("You just clicked:", SelectedBasicModel.Text));
//Do async work
return await Task.FromResult(1);
}
In the code behind for you view, create a property for you viewmodel and set the datacontext for your view to the viewmodel (please note, there are other ways to do this, but I am trying to make this a simple example.)
public partial class MainWindow : Window
{
public MainWindowViewModel MyViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
MyViewModel = new MainWindowViewModel();
this.DataContext = MyViewModel;
}
}
In your XAML, you need to add some namespaces to the top of your code
<Window x:Class="Basic_Binding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:Custom="clr-namespace:GalaSoft.MvvmLight;assembly=GalaSoft.MvvmLight"
Title="MainWindow" Height="350" Width="525">
I added "i" and "Custom."
Here is the ListView:
<ListView
Grid.Row="0"
Grid.Column="0"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding ModelsCollection}"
ItemTemplate="{DynamicResource BasicModelDataTemplate}">
</ListView>
Here is the ItemTemplate for the ListView:
<DataTemplate x:Key="BasicModelDataTemplate">
<Grid>
<TextBlock Text="{Binding Text}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction
Command="{Binding DataContext.SelectItemRelayCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}}}"
CommandParameter="{Binding Id}">
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</Grid>
</DataTemplate>
Run your application, and check out the output window. You can use a converter to handle the styling of the selected item.
This may seem really complicated, but it makes life a lot easier down the road when you need to separate your view from your ViewModel (e.g. develop a ViewModel for multiple platforms.) Additionally, it makes working in Blend 10x easier. Once you develop your ViewModel, you can hand it over to a designer who can make it look very artsy :). MVVM Light adds some functionality to make Blend recognize your ViewModel. For the most part, you can do just about everything you want to in the ViewModel to affect the view.
If anyone reads this, I hope you find this helpful. If you have questions, please let me know. I used MVVM Light in this example, but you could do this without MVVM Light.
~Cheers
Try adding a header() call before sending headers, like:
header('X-Powered-By: Our company\'s development team');
regardless of the expose_php setting in php.ini
Let me summarize all the answers and add some more.
To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w')
stuff.
If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt
stuff.
If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)
One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.
for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:
rows, columns = map(lambda i: i.value, tensor.get_shape())
For me the problem was a wrong copy/paste of the public key into Gitlab. The copy generated an extra return. Make sure what you paste is a one-line key.
git add -u
-u --update Only match against already tracked files in the index rather than the working tree. That means that it will never stage new files, but that it will stage modified new contents of tracked files and that it will remove files from the index if the corresponding files in the working tree have been removed.
If no is given, default to "."; in other words, update all tracked files in the current directory and its subdirectories.
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
For me it worked
public static long getUniqueLongFromString (String value){
return UUID.nameUUIDFromBytes(value.getBytes()).getMostSignificantBits();
}
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
Try like this:
function validate(el, status){
var targetVal = document.getElementById(el).value;
var statusEl = document.getElementById(status);
if(targetVal.length > 0){
statusEl.innerHTML = '';
}
else{
statusEL.innerHTML = "Invalid Name";
}
}
Now HTML:
<!doctype html>
<html lang='en'>
<head>
<title>Derp...</title>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate('fname','fnameStatus')">
<br />
<span id="fnameStatus"></span>
<br />
Last_Name
<input type="text" id="lname" name="lname" onblur="validate('lname','lnameStatus')">
<br />
<span id="lnameStatus"></span>
<br />
<input type=button value=check>
</form>
</body>
</html>
not() is a function in xpath (as opposed to an operator), so
//a[not(contains(@id, 'xx'))]
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
According to me, this would happen if there are two offending classes of same name but with different version. Usually, it happens due to servlet-api.jar. If its present in lib folder of your war, then pls remove it using whichever tool used for building war. Or in case of maven, add the dependency with scope specified as "provided". This will solve the compilation issue and at run time it will refer to jar provided by server environment. Pls configure the dependency as follows:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
There are a number of diff plugins available via Package Control. I've used Sublimerge Pro, which worked well enough, but it's a commercial product (with an unlimited trial period) and closed-source, so you can't tweak it if you want to change something, or just look at its internals. FileDiffs is quite popular, judging by the number of installs, so you might want to try that one out.
You can wrap your query in another SELECT
:
select count(*)
from
(
select count(SID) tot -- add alias
from Test
where Date = '2012-12-10'
group by SID
) src; -- add alias
In order for it to work, the count(SID)
need a column alias and you have to provide an alias to the subquery itself.
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
For example:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
If searching for a value, you will have to loop through all the data. But to minimize code involved, you can use LINQ
.
Given Dictionary defined as following:
Dictionary<Int32, String> dict;
You can use following code :
// Search for all keys with given value
Int32[] keys = dict.Where(kvp => kvp.Value.Equals("SomeValue")).Select(kvp => kvp.Key).ToArray();
// Search for first key with given value
Int32 key = dict.First(kvp => kvp.Value.Equals("SomeValue")).Key;
jQuery's Sizzle selector engine can use querySelectorAll
if it's available. It also smooths out inconsistencies between browsers to achieve uniform results. If you don't want to use all of jQuery, you could just use Sizzle separately. This is a pretty fundamental wheel to invent.
Here's some cherry-pickings from the source that show the kind of things jQuery(w/ Sizzle) sorts out for you:
Safari quirks mode:
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
If that guard fails it uses it's a version of Sizzle that isn't enhanced with querySelectorAll
. Further down there are specific handles for inconsistencies in IE, Opera, and the Blackberry browser.
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
And if all else fails it will return the result of oldSizzle(query, context, extra, seed)
.
I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..
public string DataTableToCSV(DataTable dt)
{
StringBuilder sb = new StringBuilder();
if (dt == null)
return "";
try {
// Create the header row
for (int i = 0; i <= dt.Columns.Count - 1; i++) {
// Append column name in quotes
sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
// Add carriage return and linefeed if last column, else add comma
sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in dt.Rows) {
for (int i = 0; i <= dt.Columns.Count - 1; i++) {
// Append value in quotes
//sb.Append("""" & row.Item(i) & """")
// OR only quote items that that are equivilant to strings
sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);
// Append CR+LF if last field, else add Comma
sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
}
}
return sb.ToString;
} catch (Exception ex) {
// Handle the exception however you want
return "";
}
}
$("#year").datepicker( {
format: "yyyy",
viewMode: "years",
minViewMode: "years"
}).on('changeDate', function(e){
$(this).datepicker('hide');
});
So you want to pass data in body of a GET request, better would be to do it in POST call. You can achieve this by using both Requests.
Raw Request
GET http://ES_search_demo.com/document/record/_search?pretty=true HTTP/1.1
Host: ES_search_demo.com
Content-Length: 183
User-Agent: python-requests/2.9.0
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate
{
"query": {
"bool": {
"must": [
{
"text": {
"record.document": "SOME_JOURNAL"
}
},
{
"text": {
"record.articleTitle": "farmers"
}
}
],
"must_not": [],
"should": []
}
},
"from": 0,
"size": 50,
"sort": [],
"facets": {}
}
Sample call with Requests
import requests
def consumeGETRequestSync():
data = '{
"query": {
"bool": {
"must": [
{
"text": {
"record.document": "SOME_JOURNAL"
}
},
{
"text": {
"record.articleTitle": "farmers"
}
}
],
"must_not": [],
"should": []
}
},
"from": 0,
"size": 50,
"sort": [],
"facets": {}
}'
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url,data = data)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)
consumeGETRequestSync()
Never faced this problem before (not worked much on email, I avoid it like the plague) but you could try declaring the bullet with the unicode code point (different notation for CSS than for HTML): content: '\2022'
. (you need to use the hex number, not the 8226 decimal one)
Then, in case you use something that picks up those characters and HTML-encodes them into entities (which won't work for CSS strings), I guess it will ignore that.
As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.
We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.
Have a ViewModel for the User
public class UserViewModel
{
public int UserID { set;get;}
public string FirstName { set;get;}
//add remaining properties as per your requirement
}
and in your controller have a method to get a list of Users
public class UserController : Controller
{
[HttpGet]
public ActionResult List()
{
List<UserViewModel> objList=UserService.GetUsers(); // this method should returns list of Users
return View("users",objList)
}
}
Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)
and in your users.cshtml ( which is under Views/User folder),
@model List<UserViewModel>
<table>
@foreach(UserViewModel objUser in Model)
{
<tr>
<td>@objUser.UserId.ToString()</td>
<td>@objUser.FirstName</td>
</tr>
}
</table>
All Set now you can access the url like yourdomain/User/List
and it will give you a list of users in an HTML table.
Just Javascript (as requested)
Add this function somewhere on your page (preferably in the <head>
)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
If you want to show all the rows set like bellow
pd.options.display.max_rows = None
If you want to show all columns set like bellow
pd.options.display.max_columns = None
I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect
call. For example,
con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
connect_timeout=1000)
Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.
For detail about different arguments that you can pass to _mysql.connect
, see MySQLdb API documentation
That's an individual question that could depend on how you're working. Some people like to put the variable type at the begining of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: english, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.
If you installed Jupiter notebook through anaconda, this may help you:
conda uninstall jupyter notebook
This problem happens because you are calling fun.cpp
instead of fun.hpp
. So c++ compiler finds func.cpp definition twice and throws this error.
Change line 3 of your main.cpp
file, from #include "fun.cpp"
to #include "fun.hpp"
.
Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.
Yes but its messy hacking the sun classes. There is a simpler way:
http://code.google.com/p/named-regexp/
named-regexp is a thin wrapper for the standard JDK regular expressions implementation, with the single purpose of handling named capturing groups in the .net style : (?...).
It can be used with Java 5 and 6 (generics are used).
Java 7 will handle named capturing groups , so this project is not meant to last.
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}