If you want to DROP
a table which has been referenced by other table using the foreign key use
DROP TABLE *table_name* CASCADE CONSTRAINTS;
I think it should work for you.
Example:
Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.
DROP TABLE IF EXISTS B,C,A;
This can be placed in the beginning of the script instead of individually dropping each table.
I was able to solve "ORA-00604: error" by Droping with purge.
DROP TABLE tablename PURGE
Try this:
SELECT *
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'YourTable';
This should deliver you which Tables have references to the table you want to drop, once you drop these references, or the datasets which reference datasets in this table you will be able to drop the table
You forgot the table
in your syntax:
drop table [table_name]
which drops a table.
Using
drop table if exists [table_name]
checks if the table exists before dropping it.
If it exists, it gets dropped.
If not, no error will be thrown and no action be taken.
You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).
It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)
Using lapply family and anonymous function approach you may:
||
lazy evaluation).Print each package final load status (TRUE
/ FALSE
).
req <- substitute(require(x, character.only = TRUE))
lbs <- c("plyr", "psych", "tm")
sapply(lbs, function(x) eval(req) || {install.packages(x); eval(req)})
plyr psych tm
TRUE TRUE TRUE
In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.
Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.
Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
format = [".jpg",".png",".jpeg"]
for (path,dirs,files) in os.walk(path):
for file in files:
if file.endswith(tuple(format)):
print(path)
print ("Valid",file)
else:
print(path)
print("InValid",file)
Use the beginning and end anchors.
Regex regex = new Regex(@"^\d$");
Use "^\d+$"
if you need to match more than one digit.
Note that "\d"
will match [0-9]
and other digit characters like the Eastern Arabic numerals ??????????
. Use "^[0-9]+$"
to restrict matches to just the Arabic numerals 0 - 9.
If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.
I had to add "Current" using .NET 4.5:
HttpContext.Current.Server.ScriptTimeout = 300;
One way is to use the multiple class selector (no space as that is the descendant selector):
.reMode_hover:not(.reMode_selected):hover _x000D_
{_x000D_
background-color: #f0ac00;_x000D_
}
_x000D_
<a href="" title="Design" class="reMode_design reMode_hover">_x000D_
<span>Design</span>_x000D_
</a>_x000D_
_x000D_
<a href="" title="Design" _x000D_
class="reMode_design reMode_hover reMode_selected">_x000D_
<span>Design</span>_x000D_
</a>
_x000D_
Swift UI solution
Button(action: {}) {
Text("Button")
}.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))
Swift 3, Swift 4, Swift 5
to improve comments. This should work:
button.setTitleColor(.red, for: .normal)
To avoid getting the encryption error you can also try out below commands
ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()
ftp.prot_p() ensure that your connections are encrypted
I came up with the same problem, and I work it out !
<img :src='book.images.small' v-on:mouseenter="hoverImg">
_x000D_
This worked for me with command prompt, from OUTSIDE mysql shell:
# mysqldump -u root -p password db1 > dump.sql
# mysqladmin -u root -p password create db2
# mysql -u root -p password db2 < dump.sql
This looks for me the best way. If zipping "dump.sql" you can symply store it as a compressed backup. Cool! For a 1GB database with Innodb tables, about a minute to create "dump.sql", and about three minutes to dump data into the new DB db2.
Straight copying the hole db directory (mysql/data/db1) didn't work for me, I guess because of the InnoDB tables.
Even the .png
file without transparency the error persists.
The solution was to change the .png
file to a .jpg
file.
foreach($arr as $key=>$value){
echo($key); // key
}
When doing this programmatically, be sure to call the setters in the correct order:
imageView.setAdjustViewBounds(true)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP)
you have to name your checkboxes accordingly:
<input type="checkbox" name="check_list[]" value="…" />
you can then access all checked checkboxes with
// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
// do something
}
ps. make sure to properly escape your output (htmlspecialchars()
)
Actually, it is worth noticing that git merge --abort
is only equivalent to git reset --merge
given that MERGE_HEAD
is present. This can be read in the git help for merge command.
git merge --abort # is equivalent to git reset --merge when MERGE_HEAD is present.
After a failed merge, when there is no MERGE_HEAD
, the failed merge can be undone with git reset --merge
but not necessarily with git merge --abort
, so they are not only old and new syntax for the same thing.
Personally I find git reset --merge
much more useful in everyday work.
Inversion of control is an indicator for a shift of responsibility in the program.
There is an inversion of control every time when a dependency is granted ability to directly act on the caller's space.
The smallest IoC is passing a variable by reference, lets look at non-IoC code first:
function isVarHello($var) {
return ($var === "Hello");
}
// Responsibility is within the caller
$word = "Hello";
if (isVarHello($word)) {
$word = "World";
}
Let's now invert the control by shifting the responsibility of a result from the caller to the dependency:
function changeHelloToWorld(&$var) {
// Responsibility has been shifted to the dependency
if ($var === "Hello") {
$var = "World";
}
}
$word = "Hello";
changeHelloToWorld($word);
Here is another example using OOP:
<?php
class Human {
private $hp = 0.5;
function consume(Eatable $chunk) {
// $this->chew($chunk);
$chunk->unfoldEffectOn($this);
}
function incrementHealth() {
$this->hp++;
}
function isHealthy() {}
function getHungry() {}
// ...
}
interface Eatable {
public function unfoldEffectOn($body);
}
class Medicine implements Eatable {
function unfoldEffectOn($human) {
// The dependency is now in charge of the human.
$human->incrementHealth();
$this->depleted = true;
}
}
$human = new Human();
$medicine = new Medicine();
if (!$human->isHealthy()) {
$human->consume($medicine);
}
var_dump($medicine);
var_dump($human);
*) Disclaimer: The real world human uses a message queue.
In case that you're using a directive like me this is how it works when you need the two data way binding for example after updating an attribute in any model or collection:
angular.module('yourApp').directive('setSurveyInEditionMode', setSurveyInEditionMode)
function setSurveyInEditionMode() {
return {
restrict: 'A',
link: function(scope, element, $attributes) {
element.on('click', function(event){
event.stopPropagation();
// In order to work with stopPropagation and two data way binding
// if you don't use scope.$apply in my case the model is not updated in the view when I click on the element that has my directive
scope.$apply(function () {
scope.mySurvey.inEditionMode = true;
console.log('inside the directive')
});
});
}
}
}
Now, you can easily use it in any button, link, div, etc. like so:
<button set-survey-in-edition-mode >Edit survey</button>
Here's an example:
#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
a b
1 1 2
2 2 3
3 3 4
#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL
#Convert that column to a factor
> d$a <- factor(d$a)
> d
a b
1 1 2
2 2 3
3 3 4
#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"
You can also handle this when reading in your data. See the colClasses
and stringsAsFactors
parameters in e.g. readCSV()
.
Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.
Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.
I rewrote the code provided by Ninja2k because I didn't like that it looped through cells. For future reference here's a version using arrays instead which works noticeably faster over lots of ranges but has the same result:
Function concat2(useThis As Range, Optional delim As String) As String
Dim tempValues
Dim tempString
Dim numValues As Long
Dim i As Long, j As Long
tempValues = useThis
numValues = UBound(tempValues) * UBound(tempValues, 2)
ReDim values(1 To numValues)
For i = UBound(tempValues) To LBound(tempValues) Step -1
For j = UBound(tempValues, 2) To LBound(tempValues, 2) Step -1
values(numValues) = tempValues(i, j)
numValues = numValues - 1
Next j
Next i
concat2 = Join(values, delim)
End Function
I can't help but think there's definitely a better way...
Here are steps to do it manually without VBA which only works with 1d arrays and makes static values instead of retaining the references:
=Sheet2!A1:A15
{ and }
CONCATENATE(
at the front of the formula after the =
sign and )
at the end of the formula.The questions is perfectly valid and clear since Spinner and ComboBox (read it: Spinner where you can provide a custom value as well) are two different things.
I was looking for the same thing myself and I wasn't satisfied with the given answers. So I created my own thing. Perhaps some will find the following hints useful. I am not providing the full source code as I am using some legacy calls in my own project. It should be pretty clear anyway.
Here is the screenshot of the final thing:
The first thing was to create a view that will look the same as the spinner that hasn't been expanded yet. In the screenshot, on the top of the screen (out of focus) you can see the spinner and the custom view right bellow it. For that purpose I used LinearLayout (actually, I inherited from Linear Layout) with style="?android:attr/spinnerStyle"
. LinearLayout contains TextView with style="?android:attr/spinnerItemStyle"
. Complete XML snippet would be:
<com.example.comboboxtest.ComboBox
style="?android:attr/spinnerStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView"
style="?android:attr/spinnerItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:text="January"
android:textAlignment="inherit"
/>
</com.example.comboboxtest.ComboBox>
As, I mentioned earlier ComboBox inherits from LinearLayout. It also implements OnClickListener which creates a dialog with a custom view inflated from the XML file. Here is the inflated view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="Enter custom value ..." >
<requestFocus />
</EditText>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK"
/>
</LinearLayout>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
There are two more listeners that you need to implement: onItemClick for the list and onClick for the button. Both of these set the selected value and dismiss the dialog.
For the list, you want it to look the same as expanded Spinner, you can do that providing the list adapter with the appropriate (Spinner) style like this:
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(
activity,
android.R.layout.simple_spinner_dropdown_item,
states
);
More or less, that should be it.
PDFsharp seems to allow merging multiple PDF documents into one.
And the same is also possible with ITextSharp.
It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.
Using bash regular expressions:
re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi
Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.
re="http://([^/]+)/"
This is the regular expression stored in a bash variable, re
- i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:
http://
is just a string - the input string must contain this substring for the regular expression to match[]
Normally square brackets are used say "match any character within the brackets". So c[ao]t
would match both "cat" and "cot". The ^
character within the []
modifies this to say "match any character except those within the square brackets. So in this case [^/]
will match any character apart from "/".+
to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+
matches 1 or more of the set of all characters, excluding "/".()
parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:
if [[ $name =~ $re ]]; then
echo ${BASH_REMATCH[1]}
fi
In bash, the [[ ]]
specify an extended conditional test, and may contain the =~
bash regular expression operator. In this case we test whether the input string $name
matches the regular expression $re
. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()
), and we can access it using the BASH_REMATCH array:
${BASH_REMATCH[0]}
will be the entire string matched by the regular expression, i.e. "http://www.google.com/".()
within a regular expression - The BASH_REMATCH
elements will correspond to these in order. So in this case ${BASH_REMATCH[1]}
will contain "www.google.com", which I think is the string you want.Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~
operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.
This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.
Note that instead of setting the $re
variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~
match operator.
You need NGNIX or Apache HTTP server as a proxy server for forwarding http requests to appropriate application -> which listens particular port (or do it with CNAME which provides Hosting company). It is most powerful solution and this is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server.
Apache era call it Virtual host -> httpd.apache.org/docs/trunk/vhosts/examples.html
NGINX -> Server Block https://www.nginx.com/resources/wiki/start/topics/examples/server_blocks/
On MacOS: add source ~/.bash_profile
to the end of ~/.zshrc
.
Then this profile will be in effect when you open zsh.
Low
is a string.
.toFixed()
only works with a number.
A simple way to overcome such problem is to use type coercion:
Low = (Low*1).toFixed(..);
The multiplication by 1 forces to code to convert the string to number and doesn't change the value.
I know this is for php, but I got here looking for a solution for node. Using mongoskin:
mongodb.admin().ping(function(err) {
if(err === null)
// true - you got a conntion, congratulations
else if(err.message.indexOf('failed to connect') !== -1)
// false - database isn't around
else
// actual error, do something about it
})
With other drivers, you can attempt to make a connection and if it fails, you know the mongo server's down. Mongoskin needs to actually make some call (like ping) because it connects lazily. For php, you can use the try-to-connect method. Make a script!
PHP:
$dbIsRunning = true
try {
$m = new MongoClient('localhost:27017');
} catch($e) {
$dbIsRunning = false
}
List<String> listA = new ArrayList<String>();
listA.add("A");
listA.add("B");
List<String> listB = new ArrayList<String>();
listB.add("B");
listB.add("C");
Set<String> newSet = new HashSet<String>(listA);
newSet.addAll(listB);
List<String> newList = new ArrayList<String>(newSet);
System.out.println("New List :"+newList);
is giving you New List :[A, B, C]
Presumably, if one wants to use an OnTouchListener
rather than an OnClickListener
, then the extra functionality of the OnTouchListener
is needed. This is a supplemental answer to show more detail of how an OnTouchListener
can be used.
Define the listener
Put this somewhere in your activity or fragment.
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
Set the listener
Set the listener in onCreate
(for an Activity) or onCreateView
(for a Fragment).
myView.setOnTouchListener(handleTouch);
Notes
getX
and getY
give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX
and getRawY
if you want the absolute screen coordinates.x
and y
values to determine things like swipe direction.Guys don't forget to call xmlWriter.Close() and xmlWriter.Dispose() or else your string won't finish creating. It will just be an empty string
There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.
However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.
Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]
UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact
You want:
this.value = ''; // straight JS, no jQuery
or
$(this).val(''); // jQuery
With $(this).value = ''
you're assigning an empty string as the value
property of the jQuery object that wraps this
-- not the value
of this
itself.
If you want just pass all attributes to redirect...
public String yourMethod( ...., HttpServletRequest request, RedirectAttributes redirectAttributes) {
if(shouldIRedirect()) {
redirectAttributes.addAllAttributes(request.getParameterMap());
return "redirect:/newPage.html";
}
}
It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:
http://howtonode.org/control-flow
Also see the Sequential Actions section of the second part of that posting:
if qs.count()==1:
print('cart id exists')
if ....
else:
return render(request,"carts/home.html",{})
Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.
above code can be changed to
if qs.count()==1:
print('cart id exists')
if ....
else:
return render(request,"carts/home.html",{})
This may solve such issues
This is how I base
ically think of the problem.
my.df <- data.frame(group = rep(c(1,2), each = 3),
score = runif(6), info = letters[1:6])
my.agg <- with(my.df, aggregate(score, list(group), max))
my.df.split <- with(my.df, split(x = my.df, f = group))
my.agg$info <- unlist(lapply(my.df.split, FUN = function(x) {
x[which(x$score == max(x$score)), "info"]
}))
> my.agg
Group.1 x info
1 1 0.9344336 a
2 2 0.7699763 e
Great answers here. If you're looking for the default view "Store Name" set in the Magento configuration:
Mage::app()->getStore()->getFrontendName()
Why not combine the onclick method with the <a>
element inside the <td>
for backup for non-JS? Seems to work great.
<td onclick="location.href='yourpage.html'"><a href="yourpage.html">Link</a></td>
You can't. The CLR won't let you. A stack overflow is a fatal error and can't be recovered from.
Yes you can return an empty value from a React render method.
You can return any of the following: false, null, undefined, or true
According to the docs:
false
,null
,undefined
, andtrue
are valid children. They simply don’t render.
You could write
return null; or
return false; or
return true; or
return <div>{undefined}</div>;
However return null
is the most preferred as it signifies that nothing is returned
Another way I haven't seen listed yet is to set your sentinel value ahead of time. This method takes advantage of Python's lazy evaluation, in which you don't always have to provide an else
statement. Example:
startingpoint = 'blah'
if len(sys.argv) >= 2:
startingpoint = sys.argv[1]
Or if you're going syntax CRAZY you could use Python's ternary operator:
startingpoint = sys.argv[1] if len(sys.argv) >= 2 else 'blah'
try
Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
End Sub
If you want to save the workbook with the macros use the below code
Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
if you want to save workbook with no macros and no pop-up use this
Sub save()
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
You can use native bootstrap validation states (No Custom CSS!):
<div class="form-group has-feedback">
<label class="control-label" for="inputSuccess2">Name</label>
<input type="text" class="form-control" id="inputSuccess2"/>
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box
You can use the .input-group
class like this:
<div class="input-group">
<input type="text" class="form-control"/>
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box
You can still use .input-group
for positioning but just override the default styling to make the two elements appear separate.
Use a normal input group but add the class input-group-unstyled
:
<div class="input-group input-group-unstyled">
<input type="text" class="form-control" />
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
Then change the styling with the following css:
.input-group.input-group-unstyled input.form-control {
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
Also, these solutions work for any input size
With Python 3, how about:
try:
with open(filename, 'x') as tempfile: # OSError if file exists or is invalid
pass
except OSError:
# handle error here
With the 'x' option we also don't have to worry about race conditions. See documentation here.
Now, this WILL create a very shortlived temporary file if it does not exist already - unless the name is invalid. If you can live with that, it simplifies things a lot.
You can do like this basically:
int[] ints = new[] { 10, 20, 10, 34, 113 };
this is your array, and than you can call your new list like this:
var newList = new List<int>(ints);
You can do this for complex object too.
>>> import string
>>> string.ascii_lowercase[:14]
'abcdefghijklmn'
>>> string.ascii_lowercase[:14:2]
'acegikm'
To do the urls, you could use something like this
[i + j for i, j in zip(list_of_urls, string.ascii_lowercase[:14])]
Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:
my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);
Difference between database and flat files are given below:
Database provide more flexibility whereas flat file provide less flexibility.
Database system provide data consistency whereas flat file can not provide data consistency.
Database support DML and DDL whereas flat files can not support these.
Less data redundancy in database whereas more data redundancy in flat files.
Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose
.feature_desc {
display: block;
}
.feature_desc:before {
content: "";
display: block;
}
might give you want you want to achieve without the <br/>
element. Though it would help to see your CSS applied to these elements.
NOTE. The example above doesn't work in IE7 though.
As blocking on keyboard input (since the input()
function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.
This works by creating one thread to run in the background, continually calling input()
and then passing any data it receives to a queue.
In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.
import threading
import queue
import time
def read_kbd_input(inputQueue):
print('Ready for keyboard input:')
while (True):
input_str = input()
inputQueue.put(input_str)
def main():
EXIT_COMMAND = "exit"
inputQueue = queue.Queue()
inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
inputThread.start()
while (True):
if (inputQueue.qsize() > 0):
input_str = inputQueue.get()
print("input_str = {}".format(input_str))
if (input_str == EXIT_COMMAND):
print("Exiting serial terminal.")
break
# Insert your code here to do whatever you want with the input_str.
# The rest of your program goes here.
time.sleep(0.01)
print("End.")
if (__name__ == '__main__'):
main()
"""
read_keyboard_input.py
Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018
References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html
To install PySerial: `sudo python3 -m pip install pyserial`
To run this program: `python3 this_filename.py`
"""
import threading
import queue
import time
def read_kbd_input(inputQueue):
print('Ready for keyboard input:')
while (True):
# Receive keyboard input from user.
input_str = input()
# Enqueue this input string.
# Note: Lock not required here since we are only calling a single Queue method, not a sequence of them
# which would otherwise need to be treated as one atomic operation.
inputQueue.put(input_str)
def main():
EXIT_COMMAND = "exit" # Command to exit this program
# The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
# method calls in a row. Use this if you have such a need, as follows:
# 1. Pass queueLock as an input parameter to whichever function requires it.
# 2. Call queueLock.acquire() to obtain the lock.
# 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
# inputQueue.qsize(), followed by inputQueue.put(), for example.
# 4. Call queueLock.release() to release the lock.
# queueLock = threading.Lock()
#Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
inputQueue = queue.Queue()
# Create & start a thread to read keyboard inputs.
# Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
# this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
inputThread.start()
# Main loop
while (True):
# Read keyboard inputs
# Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
# multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
# example program, no locks are required.
if (inputQueue.qsize() > 0):
input_str = inputQueue.get()
print("input_str = {}".format(input_str))
if (input_str == EXIT_COMMAND):
print("Exiting serial terminal.")
break # exit the while loop
# Insert your code here to do whatever you want with the input_str.
# The rest of your program goes here.
# Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
time.sleep(0.01)
print("End.")
# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'):
main()
$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.
Note that Queue.put()
and Queue.get()
and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):
The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.
//Parent[@id='1']/Children/child/@name
Your original child[@name]
means an element child
which has an attribute name
. You want child/@name
.
cw
Change word - deletes the word under the cursor and puts you in insert mode to type a new one. Of course this works with other movement keys, so you can do things like c$ to change to the end of the line.
f + character
Finds the next occurrence of the character on the current line. So you can do vft to select all the text up to the next "t" on the current line. It's another movement key, so it works with other commands too.
def doAppend( size=10000 ):
result = []
for i in range(size):
message= "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate( size=10000 ):
result=size*[None]
for i in range(size):
message= "some unique object %d" % ( i, )
result[i]= message
return result
Results. (evaluate each function 144 times and average the duration)
simple append 0.0102
pre-allocate 0.0098
Conclusion. It barely matters.
Premature optimization is the root of all evil.
There is two steps to extract year for all the dataframe without using method apply.
Step1
convert the column to datetime :
df['ArrivalDate']=pd.to_datetime(df['ArrivalDate'], format='%Y-%m-%d')
Step2
extract the year or the month using DatetimeIndex()
method
pd.DatetimeIndex(df['ArrivalDate']).year
I think you're looking for something more like WebClient.
Specifically, UploadFile().
I prefer to limit the number of retries, so that if there's a problem with that specific item you will eventually continue onto the next one, thus:
for i in range(100):
for attempt in range(10):
try:
# do thing
except:
# perhaps reconnect, etc.
else:
break
else:
# we failed all the attempts - deal with the consequences.
min(df['some_property'])
max(df['some_property'])
The built-in functions work well with Pandas Dataframes.
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
I would recommend you to make use of the $.post
or $.get
syntax of jQuery for simple cases:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
});
If you need to catch the fail cases, just do this:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}, 'json');
Thanks everybody, here is the most succinct explanation I found on the MSDN site:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
Use WebElement.send_keys
method to simulate key typing.
name
in the code (Username
, Password
) does not match actual name
of the elements (username
, password
).
username = browser.find_element_by_name('username')
username.send_keys('user1')
password = browser.find_element_by_name('password')
password.send_keys('secret')
form = browser.find_element_by_id('loginForm')
form.submit()
# OR browser.find_element_by_id('submit').click()
Until host.docker.internal
is working for every platform, you can use my container acting as a NAT gateway without any manual setup:
Here an example with 100000 rows (occupations are set here from A to Z):
> a = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(LETTERS, 100000, replace=T))
> sum(a$sex == "M" & a$occupation=="A")
[1] 1882
returns the number of males with occupation "A".
EDIT
As I understand from your comment, you want the counts of all possible combinations of sex and occupation. So first create a dataframe with all combinations:
combns = expand.grid(c("M", "F"), LETTERS)
and loop with apply
to sum for your criteria and append the results to combns
:
combns = cbind (combns, apply(combns, 1, function(x)sum(a$sex==x[1] & a$occupation==x[2])))
colnames(combns) = c("sex", "occupation", "count")
The first rows of your result look as follows:
sex occupation count
1 M A 1882
2 F A 1869
3 M B 1866
4 F B 1904
5 M C 1979
6 F C 1910
Does this solve your problem?
OR:
Much easier solution suggested by thelatemai:
table(a$sex, a$occupation)
A B C D E F G H I J K L M N O
F 1869 1904 1910 1907 1894 1940 1964 1907 1918 1892 1962 1933 1886 1960 1972
M 1882 1866 1979 1904 1895 1845 1946 1905 1999 1994 1933 1950 1876 1856 1911
P Q R S T U V W X Y Z
F 1908 1907 1883 1888 1943 1922 2016 1962 1885 1898 1889
M 1928 1938 1916 1927 1972 1965 1946 1903 1965 1974 1906
You can add nulls to the ArrayList
, and you will have to check for nulls in the loop:
for(Item i : itemList) {
if (i != null) {
}
}
itemsList.size();
would take the null
into account.
List<Integer> list = new ArrayList<Integer>();
list.add(null);
list.add (5);
System.out.println (list.size());
for (Integer value : list) {
if (value == null)
System.out.println ("null value");
else
System.out.println (value);
}
Output :
2
null value
5
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}}
and then add dependency
dependencies {
compile 'com.github.varunest:sparkbutton:1.0.5'
}
<com.varunest.sparkbutton.SparkButton
android:id="@+id/spark_button"
android:layout_width="40dp"
android:layout_height="40dp"
app:sparkbutton_activeImage="@drawable/active_image"
app:sparkbutton_inActiveImage="@drawable/inactive_image"
app:sparkbutton_iconSize="40dp"
app:sparkbutton_primaryColor="@color/primary_color"
app:sparkbutton_secondaryColor="@color/secondary_color" />
SparkButton button = new SparkButtonBuilder(context)
.setActiveImage(R.drawable.active_image)
.setInActiveImage(R.drawable.inactive_image)
.setDisabledImage(R.drawable.disabled_image)
.setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
.setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
.setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
.build();
Answering the "usefulness" part of the question:
One rather subtle gotcha of using FileChannel
over FileOutputStream
is that performing any of its blocking operations (e.g. read()
or write()
) from a thread that's in interrupted state will cause the channel to close abruptly with java.nio.channels.ClosedByInterruptException
.
Now, this could be a good thing if whatever the FileChannel
was used for is part of the thread's main function, and design took this into account.
But it could also be pesky if used by some auxiliary feature such as a logging function. For example, you can find your logging output suddenly closed if the logging function happens to be called by a thread that's also interrupted.
It's unfortunate this is so subtle because not accounting for this can lead to bugs that affect write integrity.[1][2]
You can take update / pull on git branch you can use below command
git pull origin <branch-name>
The above command will take an update/pull from giving branch name
If you want to take pull from another branch, you need to go to that branch.
git checkout master
Than
git pull origin development
Hope that will work for you
In my case, it was very a silly and funny mistake. I, accidentally without actually knowing, checked "Android Debug Bridge, Use libUsb backend". Actually it should stay unchecked..
In Mac Pro, Go Preferences - > Build, Execution,Deployment -> Debugger.
If you are just wandering over the collection to read all of the values, then there is no difference between using an iterator or the new for loop syntax, as the new syntax just uses the iterator underwater.
If however, you mean by loop the old "c-style" loop:
for(int i=0; i<list.size(); i++) {
Object o = list.get(i);
}
Then the new for loop, or iterator, can be a lot more efficient, depending on the underlying data structure. The reason for this is that for some data structures, get(i)
is an O(n) operation, which makes the loop an O(n2) operation. A traditional linked list is an example of such a data structure. All iterators have as a fundamental requirement that next()
should be an O(1) operation, making the loop O(n).
To verify that the iterator is used underwater by the new for loop syntax, compare the generated bytecodes from the following two Java snippets. First the for loop:
List<Integer> a = new ArrayList<Integer>();
for (Integer integer : a)
{
integer.toString();
}
// Byte code
ALOAD 1
INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator;
ASTORE 3
GOTO L2
L3
ALOAD 3
INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object;
CHECKCAST java/lang/Integer
ASTORE 2
ALOAD 2
INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String;
POP
L2
ALOAD 3
INVOKEINTERFACE java/util/Iterator.hasNext()Z
IFNE L3
And second, the iterator:
List<Integer> a = new ArrayList<Integer>();
for (Iterator iterator = a.iterator(); iterator.hasNext();)
{
Integer integer = (Integer) iterator.next();
integer.toString();
}
// Bytecode:
ALOAD 1
INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator;
ASTORE 2
GOTO L7
L8
ALOAD 2
INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object;
CHECKCAST java/lang/Integer
ASTORE 3
ALOAD 3
INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String;
POP
L7
ALOAD 2
INVOKEINTERFACE java/util/Iterator.hasNext()Z
IFNE L8
As you can see, the generated byte code is effectively identical, so there is no performance penalty to using either form. Therefore, you should choose the form of loop that is most aesthetically appealing to you, for most people that will be the for-each loop, as that has less boilerplate code.
You can write following codes to achieve this task:
SELECT ... FROM ... WHERE ...
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'
It export the result to CSV and then export it to excel sheet.
Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.
/**
* HTTP request types
*/
public static final int POST_TYPE = 1;
public static final int GET_TYPE = 2;
public static final int PUT_TYPE = 3;
public static final int DELETE_TYPE = 4;
/**
* HTTP request header constants
*/
public static final String CONTENT_TYPE = "Content-Type";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String ENCODING_GZIP = "gzip";
public static final String MIME_FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN = "text/plain";
private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
final Map<String, String> headers, final Map<String, String> params, final int requestType)
throws IOException {
DefaultHttpClient client = HTTPClientFactory.newClient();
client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);
// add user and pass to client credentials if present
if ((user != null) && (pass != null)) {
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
}
// process headers using request interceptor
final Map<String, String> sendHeaders = new HashMap<String, String>();
if ((headers != null) && (headers.size() > 0)) {
sendHeaders.putAll(headers);
}
if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
}
// request gzip encoding for response
sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);
if (sendHeaders.size() > 0) {
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException,
IOException {
for (String key : sendHeaders.keySet()) {
if (!request.containsHeader(key)) {
request.addHeader(key, sendHeaders.get(key));
}
}
}
});
}
//.... code omitted ....//
}
pip install --ignore-installed six
Would do the trick.
Source: github.com/pypa/pip/issues/3165
If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"
You may try one of these methods:
Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.
Use double quote for your password: like - "Abc@%$67eSDu"
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
If you would like the new data frame to have the same index and columns as an existing data frame, you can just multiply the existing data frame by zero:
df_zeros = df * 0
I want to understand the lock each transaction isolation takes on the table
For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT
statement to read data. C reads and updates data. All these process work on the same table T.
WHERE aField > 10 AND aField < 20
, A inserts data where aField
value is between 10 and 20, then B reads the data again and get a different result.I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also
Using JDBC, you define it using Connection#setTransactionIsolation
.
Using Hibernate:
<property name="hibernate.connection.isolation">2</property>
Where
Hibernate configuration is taken from here (sorry, it's in Spanish).
By the way, you can set the isolation level on RDBMS as well:
SET ISOLATION TO DIRTY READ
sentence.)and on and on...
In my case I found duplicate paths in Servers/Tomcat5.5 at localhost-config/server.xml under tag. Removing the duplicates solved the problem.
In javascript that uses the CommonJS spec, like node.js for instance you can do what I show below. Which is pretty handy for accessing a variable by a string even if its not defined on the window
object. If there is a class named MyClass
, defined within a CommonJS module named MyClass.js
// MyClass.js
var MyClass = function() {
// I do stuff in here. Probably return an object
return {
foo: "bar"
}
}
module.exports = MyClass;
You can then do this nice bit o witchcraft from another file called MyOtherFile.js
// MyOtherFile.js
var myString = "MyClass";
var MyClass = require('./' + myString);
var obj = new MyClass();
console.log(obj.foo); // returns "bar"
One more reason why CommonJS is such a pleasure.
Absolute easiest way (with your current code) is to add a require_once("path/to/file")
statement to your php code.
<?php
require_once("../myCSSfile.css");
echo "<table>";
...
Also, as an aside: the opening <?php
tag does not have a >
on the end, and the closing ?>
php tag does not start with <
. Weird, but true.
Or just like this in Kotlin:
val tv = findViewById(R.id.textViewOne) as TextView
tv.setTypeface(null, Typeface.BOLD_ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD or Typeface.ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD)
// OR
tv.setTypeface(null, Typeface.ITALIC)
// AND
tv.paintFlags = tv.paintFlags or Paint.UNDERLINE_TEXT_FLAG
Or in Java:
TextView tv = (TextView)findViewById(R.id.textViewOne);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD|Typeface.ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD);
// OR
tv.setTypeface(null, Typeface.ITALIC);
// AND
tv.setPaintFlags(tv.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);
Keep it simple and in one line :)
You can use PDF.js to create PDF files from javascript... it's easy to code... hope this solve your doubt!!!
Regards!
It's a common misconception that you can denormalise like this for performance. Use date_trunc('month', date)
for your queries and add an index expression for this if you find it running slow.
The short version: use formatC
or sprintf
.
The longer version:
There are several functions available for formatting numbers, including adding leading zeroes. Which one is best depends upon what other formatting you want to do.
The example from the question is quite easy since all the values have the same number of digits to begin with, so let's try a harder example of making powers of 10 width 8 too.
anim <- 25499:25504
x <- 10 ^ (0:5)
paste
(and it's variant paste0
) are often the first string manipulation functions that you come across. They aren't really designed for manipulating numbers, but they can be used for that. In the simple case where we always have to prepend a single zero, paste0
is the best solution.
paste0("0", anim)
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
For the case where there are a variable number of digits in the numbers, you have to manually calculate how many zeroes to prepend, which is horrible enough that you should only do it out of morbid curiosity.
str_pad
from stringr
works similarly to paste
, making it more explicit that you want to pad things.
library(stringr)
str_pad(anim, 6, pad = "0")
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
Again, it isn't really designed for use with numbers, so the harder case requires a little thinking about. We ought to just be able to say "pad with zeroes to width 8", but look at this output:
str_pad(x, 8, pad = "0")
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "0001e+05"
You need to set the scientific penalty option so that numbers are always formatted using fixed notation (rather than scientific notation).
library(withr)
with_options(
c(scipen = 999),
str_pad(x, 8, pad = "0")
)
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
stri_pad
in stringi
works exactly like str_pad
from stringr
.
formatC
is an interface to the C function printf
. Using it requires some knowledge of the arcana of that underlying function (see link). In this case, the important points are the width
argument, format
being "d"
for "integer", and a "0"
flag
for prepending zeroes.
formatC(anim, width = 6, format = "d", flag = "0")
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
formatC(x, width = 8, format = "d", flag = "0")
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
This is my favourite solution, since it is easy to tinker with changing the width, and the function is powerful enough to make other formatting changes.
sprintf
is an interface to the C function of the same name; like formatC
but with a different syntax.
sprintf("%06d", anim)
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
sprintf("%08d", x)
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
The main advantage of sprintf
is that you can embed formatted numbers inside longer bits of text.
sprintf(
"Animal ID %06d was a %s.",
anim,
sample(c("lion", "tiger"), length(anim), replace = TRUE)
)
## [1] "Animal ID 025499 was a tiger." "Animal ID 025500 was a tiger."
## [3] "Animal ID 025501 was a lion." "Animal ID 025502 was a tiger."
## [5] "Animal ID 025503 was a tiger." "Animal ID 025504 was a lion."
See also goodside's answer.
For completeness it is worth mentioning the other formatting functions that are occasionally useful, but have no method of prepending zeroes.
format
, a generic function for formatting any kind of object, with a method for numbers. It works a little bit like formatC
, but with yet another interface.
prettyNum
is yet another formatting function, mostly for creating manual axis tick labels. It works particularly well for wide ranges of numbers.
The scales
package has several functions such as percent
, date_format
and dollar
for specialist format types.
File protocol URIs are like this
file://[HOST]/[PATH]
that's why you often see file URLs like this (3 slashes) file:///c:\path...
So if the host is server01, you want
file://server01/folder/path....
This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.
What is the difference between Git and GitHub?
Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)
In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).
Is Git saving every repository locally (in the user's machine) and in GitHub?
Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:
How does Git compare to a backup system such as Time Machine?
Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, this is a manual process.
If are not collaborating and you are already using a backup system why would you use Git?
For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.
The following code is the version of the general answer but with corrections and clarity.
import numpy as np
import pandas as pd
import scipy.stats as st
import statsmodels.api as sm
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
import random
mpl.style.use("ggplot")
def danoes_formula(data):
"""
DANOE'S FORMULA
https://en.wikipedia.org/wiki/Histogram#Doane's_formula
"""
N = len(data)
skewness = st.skew(data)
sigma_g1 = math.sqrt((6*(N-2))/((N+1)*(N+3)))
num_bins = 1 + math.log(N,2) + math.log(1+abs(skewness)/sigma_g1,2)
num_bins = round(num_bins)
return num_bins
def plot_histogram(data, results, n):
## n first distribution of the ranking
N_DISTRIBUTIONS = {k: results[k] for k in list(results)[:n]}
## Histogram of data
plt.figure(figsize=(10, 5))
plt.hist(data, density=True, ec='white', color=(63/235, 149/235, 170/235))
plt.title('HISTOGRAM')
plt.xlabel('Values')
plt.ylabel('Frequencies')
## Plot n distributions
for distribution, result in N_DISTRIBUTIONS.items():
# print(i, distribution)
sse = result[0]
arg = result[1]
loc = result[2]
scale = result[3]
x_plot = np.linspace(min(data), max(data), 1000)
y_plot = distribution.pdf(x_plot, loc=loc, scale=scale, *arg)
plt.plot(x_plot, y_plot, label=str(distribution)[32:-34] + ": " + str(sse)[0:6], color=(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)))
plt.legend(title='DISTRIBUTIONS', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.show()
def fit_data(data):
## st.frechet_r,st.frechet_l: are disbled in current SciPy version
## st.levy_stable: a lot of time of estimation parameters
ALL_DISTRIBUTIONS = [
st.alpha,st.anglit,st.arcsine,st.beta,st.betaprime,st.bradford,st.burr,st.cauchy,st.chi,st.chi2,st.cosine,
st.dgamma,st.dweibull,st.erlang,st.expon,st.exponnorm,st.exponweib,st.exponpow,st.f,st.fatiguelife,st.fisk,
st.foldcauchy,st.foldnorm, st.genlogistic,st.genpareto,st.gennorm,st.genexpon,
st.genextreme,st.gausshyper,st.gamma,st.gengamma,st.genhalflogistic,st.gilbrat,st.gompertz,st.gumbel_r,
st.gumbel_l,st.halfcauchy,st.halflogistic,st.halfnorm,st.halfgennorm,st.hypsecant,st.invgamma,st.invgauss,
st.invweibull,st.johnsonsb,st.johnsonsu,st.ksone,st.kstwobign,st.laplace,st.levy,st.levy_l,
st.logistic,st.loggamma,st.loglaplace,st.lognorm,st.lomax,st.maxwell,st.mielke,st.nakagami,st.ncx2,st.ncf,
st.nct,st.norm,st.pareto,st.pearson3,st.powerlaw,st.powerlognorm,st.powernorm,st.rdist,st.reciprocal,
st.rayleigh,st.rice,st.recipinvgauss,st.semicircular,st.t,st.triang,st.truncexpon,st.truncnorm,st.tukeylambda,
st.uniform,st.vonmises,st.vonmises_line,st.wald,st.weibull_min,st.weibull_max,st.wrapcauchy
]
MY_DISTRIBUTIONS = [st.beta, st.expon, st.norm, st.uniform, st.johnsonsb, st.gennorm, st.gausshyper]
## Calculae Histogram
num_bins = danoes_formula(data)
frequencies, bin_edges = np.histogram(data, num_bins, density=True)
central_values = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges)-1)]
results = {}
for distribution in MY_DISTRIBUTIONS:
## Get parameters of distribution
params = distribution.fit(data)
## Separate parts of parameters
arg = params[:-2]
loc = params[-2]
scale = params[-1]
## Calculate fitted PDF and error with fit in distribution
pdf_values = [distribution.pdf(c, loc=loc, scale=scale, *arg) for c in central_values]
## Calculate SSE (sum of squared estimate of errors)
sse = np.sum(np.power(frequencies - pdf_values, 2.0))
## Build results and sort by sse
results[distribution] = [sse, arg, loc, scale]
results = {k: results[k] for k in sorted(results, key=results.get)}
return results
def main():
## Import data
data = pd.Series(sm.datasets.elnino.load_pandas().data.set_index('YEAR').values.ravel())
results = fit_data(data)
plot_histogram(data, results, 5)
if __name__ == "__main__":
main()
Strace stands out as a tool for investigating production systems where you can't afford to run these programs under a debugger. In particular, we have used strace in the following two situations:
For an example of analyzing using strace see my answer to this question.
You can use the action()
helper to generate an URL to your route:
<form method="post" action="{{ action('WelcomeController@log_in') }}" accept-charset="UTF-8">
Note that the Laravel 5 default installation already comes with views and controllers for the whole authentication process. Just go to /home
on a fresh install and you should get redirected to a login page.
Also make sure to read the Authentication section in the docs
The error you're getting now (TokenMismatchException
) is because Laravel has CSRF protection out of the box
To make use of it (and make the error go away) add a hidden field to your form:
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
Alternatively you can also disable CSRF protection by removing 'App\Http\Middleware\VerifyCsrfToken'
from the $middleware
array in app/Http/Kernel.php
<select name="owner">
<?php
$sql = mysql_query("SELECT username FROM users");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>
Do you need to rewind the buffer, perhaps?
Also, this might happen if the stride (in bytes) of the bitmap is greater than the row length in pixels * bytes/pixel. Make the length of bytes b.remaining() instead of size.
I faced this problem where the following query doesn't work as expected:
select 1 where getdate()<>null
we expect it to show 1 because getdate() doesn't return null. I guess it has something to do with SQL failing to cast null as datetime and skipping the row! of course we know we should use IS or IS NOT keywords to compare a variable with null but when comparing two parameters it gets hard to handle the null situation. as a solution you can create your own compare function like the following:
CREATE FUNCTION [dbo].[fnCompareDates]
(
@DateTime1 datetime,
@DateTime2 datetime
)
RETURNS bit
AS
BEGIN
if (@DateTime1 is null and @DateTime2 is null) return 1;
if (@DateTime1 = @DateTime2) return 1;
return 0
END
and re writing the query like:
select 1 where dbo.fnCompareDates(getdate(),null)=0
You can use the auto_now
and auto_now_add
options for updated_at
and created_at
respectively.
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
// find the first select and bind a click handler
$('#column_select').bind('click', function(){
// retrieve the selected value
var value = $(this).val(),
// build a regular expression that does a head-match
expression = new RegExp('^' + value),
// find the second select
$select = $('#layout_select);
// hide all children (<option>s) of the second select,
// check each element's value agains the regular expression built from the first select's value
// show elements that match the expression
$select.children().hide().filter(function(){
return !!$(this).val().match(expression);
}).show();
});
(this is far from perfect, but should get you there…)
Requirements to fix this issue:
Image Format: 32-bit PNG (with alpha)
Image should be Transparent
Transparency Color Index: White (FFFFFF)
Source: http://gr1350.blogspot.com/2017/01/problem-with-setsmallicon.html
You can use the deprecated AppDomain.GetCurrentThreadId
to get the ID of the currently running thread. This method uses a PInvoke to the Win32 API method GetCurrentThreadID
, and will return the Windows thread ID.
This method is marked as deprecated because the .NET Thread object does not correspond to a single Windows thread, and as such there is no stable ID which can be returned by Windows for a given .NET thread.
See configurator's answer for more reasons why this is the case.
An undocumented feature of the formData
field that request
implements is the ability to pass options to the form-data
module it uses:
request({
url: 'http://example.com',
method: 'POST',
formData: {
'regularField': 'someValue',
'regularFile': someFileStream,
'customBufferFile': {
value: fileBufferData,
options: {
filename: 'myfile.bin'
}
}
}
}, handleResponse);
This is useful if you need to avoid calling requestObj.form()
but need to upload a buffer as a file. The form-data
module also accepts contentType
(the MIME type) and knownLength
options.
This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0
or above of request
.
All the above answers are correct. Just providing with your dataset to find perfect divisor:
#include <stdio.h>
int main()
{
int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;
for (i=0 ; i < 7; i++) {
if (j % arr[i] == 0)
printf("%d is the perfect divisor of %d\n", arr[i], j);
}
return 0;
}
Another possible option, but it depends if what you mean by before:
undefined = object()
class Widget:
def __init__(self):
self.bar = 1
def zoom(self):
print("zoom!")
a = Widget()
bar = getattr(a, "bar", undefined)
if bar is not undefined:
print("bar:%s" % (bar))
foo = getattr(a, "foo", undefined)
if foo is not undefined:
print("foo:%s" % (foo))
zoom = getattr(a, "zoom", undefined)
if zoom is not undefined:
zoom()
output:
bar:1
zoom!
This allows you to even check for None-valued attributes.
But! Be very careful you don't accidentally instantiate and compare undefined
multiple places because the is
will never work in that case.
because of what I was warning about in the above paragraph, having multiple undefineds that never match, I have recently slightly modified this pattern:
undefined = NotImplemented
NotImplemented
, not to be confused with NotImplementedError
, is a built-in: it semi-matches the intent of a JS undefined
and you can reuse its definition everywhere and it will always match. The drawbacks is that it is "truthy" in booleans and it can look weird in logs and stack traces (but you quickly get over it when you know it only appears in this context).
Drop all the foreign keys of a table:
USE [Database_Name]
DECLARE @FOREIGN_KEY_NAME VARCHAR(100)
DECLARE FOREIGN_KEY_CURSOR CURSOR FOR
SELECT name FOREIGN_KEY_NAME FROM sys.foreign_keys WHERE parent_object_id = (SELECT object_id FROM sys.objects WHERE name = 'Table_Name' AND TYPE = 'U')
OPEN FOREIGN_KEY_CURSOR
----------------------------------------------------------
FETCH NEXT FROM FOREIGN_KEY_CURSOR INTO @FOREIGN_KEY_NAME
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @DROP_COMMAND NVARCHAR(150) = 'ALTER TABLE Table_Name DROP CONSTRAINT' + ' ' + @FOREIGN_KEY_NAME
EXECUTE Sp_executesql @DROP_COMMAND
FETCH NEXT FROM FOREIGN_KEY_CURSOR INTO @FOREIGN_KEY_NAME
END
-----------------------------------------------------------------------------------------------------------------
CLOSE FOREIGN_KEY_CURSOR
DEALLOCATE FOREIGN_KEY_CURSOR
In Clean Code: A Handbook of Agile Software Craftsmanship there is an explicit recommendation against the usage of this prefix:
You also don't need to prefix member variables with
m_
anymore. Your classes and functions should be small enough that you don't need them.
There is also an example (C# code) of this:
Bad practice:
public class Part
{
private String m_dsc; // The textual description
void SetName(string name)
{
m_dsc = name;
}
}
Good practice:
public class Part
{
private String description;
void SetDescription(string description)
{
this.description = description;
}
}
We count with language constructs to refer to member variables in the case of explicitly ambiguity (i.e., description
member and description
parameter): this
.
Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.
Center canvas to middle of the screen or parent element. No wrapping.
HTML:
<canvas id="canvas" width="400" height="300">No canvas support</canvas>
CSS:
#canvas {
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
}
Javascript:
window.onload = window.onresize = function() {
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth * 0.8;
canvas.height = window.innerHeight * 0.8;
}
Works like a charm - tested: firefox, chrome
Just to add to Benjamin's answer — class variables are possible, but you wouldn't use prototype
to set them.
For a true class variable you'd want to do something like the following:
class MyClass {}
MyClass.foo = 'bar';
From within a class method that variable can be accessed as this.constructor.foo
(or MyClass.foo
).
These class properties would not usually be accessible from to the class instance. i.e. MyClass.foo
gives 'bar'
but new MyClass().foo
is undefined
If you want to also have access to your class variable from an instance, you'll have to additionally define a getter:
class MyClass {
get foo() {
return this.constructor.foo;
}
}
MyClass.foo = 'bar';
I've only tested this with Traceur, but I believe it will work the same in a standard implementation.
JavaScript doesn't really have classes. Even with ES6 we're looking at an object- or prototype-based language rather than a class-based language. In any function X () {}
, X.prototype.constructor
points back to X
.
When the new
operator is used on X
, a new object is created inheriting X.prototype
. Any undefined properties in that new object (including constructor
) are looked up from there. We can think of this as generating object and class properties.
If you use:
ps uH p <PID_OF_U_PROCESS> | wc -l
You have to subtract 1 to the result, as one of the lines "wc" is counting is the headers of the "ps" command.
Use the Format function.
Format(Date, "yyyy-mm-dd hh:MM:ss")
They're just trawling lists of web sites, and recording the resulting IP addresses in a database.
All you're seeing is the reverse mapping of that list. It's not guaranteed to be a full list (indeed more often than not it won't be) because it's impossible to learn every possible web site address.
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
You can create a method somewhere
public static <T> T[] toArray(T... ts) {
return ts;
}
then use it
m(toArray("blah", "hey", "yo"));
for better look.
This is exactly what TO_DATE()
is for: to convert timestamp to date.
Just use TO_DATE(sysdate)
instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS')
.
UPDATE:
Per your update, your cdate
column is not real DATE
or TIMESTAMP
type, but VARCHAR2
. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.
You should convert your cdate
VARCHAR2
field into real TIMESTAMP
. Assuming there are no other users for this field except for your code, you can convert cdate
to timestamp as follows:
BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');
-- you may want to check contents of tdate before next step!!!
-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;
I found that using the Common Event described above works well and you could have the common event set up like this:
private void checkChanged(object sender, EventArgs e)
{
foreach (RadioButton r in yourPanel.Controls)
{
if (r.Checked)
textBox.Text = r.Text;
}
}
Of course, then you can't have other controls in your panel that you use, but it's useful if you just have a separate panel for all your radio buttons (such as using a sub panel inside a group box or however you prefer to organize your controls)
Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
Using JavaScript
public ActionResult Index()
{
return Content("<script>window.location = 'http://www.example.com';</script>");
}
Note: As @Jeremy Ray Brown said , This is not the best option but you might find useful in some situations.
Hope this helps.
Answer For Eclipse 2019 With ScreenShots
rt.jar
from JRE systems library, click on corresponding drop down to expandSource attachment none
, Click on Source Attachment
Button, Source attachment configuration window will appear, Select external location
src.zip
file from jdk folder, say ok ok finishI had the same need for conditional tests, and I figured out a good workaround. I defined a macro TEST_C that works like a TEST_F macro, but it has a third parameter, which is a boolean expression, evaluated runtime in main.cpp BEFORE the tests are started. Tests that evaluate false are not executed. The macro is ugly, but it look like:
#pragma once
extern std::map<std::string, std::function<bool()> >* m_conditionalTests;
#define TEST_C(test_fixture, test_name, test_condition)\
class test_fixture##_##test_name##_ConditionClass\
{\
public:\
test_fixture##_##test_name##_ConditionClass()\
{\
std::string name = std::string(#test_fixture) + "." + std::string(#test_name);\
if (m_conditionalTests==NULL) {\
m_conditionalTests = new std::map<std::string, std::function<bool()> >();\
}\
m_conditionalTests->insert(std::make_pair(name, []()\
{\
DeviceInfo device = Connection::Instance()->GetDeviceInfo();\
return test_condition;\
}));\
}\
} test_fixture##_##test_name##_ConditionInstance;\
TEST_F(test_fixture, test_name)
Additionally, in your main.cpp, you need this loop to exclude the tests that evaluate false:
// identify tests that cannot run on this device
std::string excludeTests;
for (const auto& exclusion : *m_conditionalTests)
{
bool run = exclusion.second();
if (!run)
{
excludeTests += ":" + exclusion.first;
}
}
// add the exclusion list to gtest
std::string str = ::testing::GTEST_FLAG(filter);
::testing::GTEST_FLAG(filter) = str + ":-" + excludeTests;
// run all tests
int result = RUN_ALL_TESTS();
I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477
Or you can read it there ==>
When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.
With Bootstrap 3.2 you can wrap each iframe in the responsive-embed wrapper of your choice:
http://getbootstrap.com/components/#responsive-embed
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
If you don't want to wrap your iframes, you can use FluidVids https://github.com/toddmotto/fluidvids. See demo here: http://toddmotto.com/labs/fluidvids/
<!-- fluidvids.js -->
<script src="js/fluidvids.js"></script>
<script>
fluidvids.init({
selector: ['iframe'],
players: ['www.youtube.com', 'player.vimeo.com']
});
</script>
Your mobile class Isn't correct:
.mobile {
display: none !important;
visibility: hidden !important; //This is what's keeping the div from showing, remove this.
}
Your problem stems from a misunderstanding of the or
operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1
, but I'll go into a little more detail about why your attempted solution doesn't work.
When you read x ~=(0 or 1)
or x ~= 0 or 1
it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.
However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or
has a lower precedence than ~=
, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.
As a result, when evaluating x ~=(0 or 1)
, the interpreter will first compute 0 or 1
(because of the parentheses) and then x ~=
the result of the first computation, and in the second example, it will compute x ~= 0
and then apply the result of that computation to or 1
.
The logical operator or
"returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~=
is the inverse of the equality operator ==
; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.
Using these rules, x ~=(0 or 1)
will decompose to x ~= 0
(after applying the or
operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1
will first evaluate x ~= 0
(which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1
or true or 1
. In the first case, the statement will return 1
, and in the second case, the statement will return true
. Because control structures in Lua only consider nil
and false
to be false, and anything else to be true, this will always enter the if
statement, which is not what you want either.
There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:
if x ~= 1 and x ~= 0 then
print( "X must be equal to 1 or 0" )
return
end
Alternatively, you can use a loop to check these values:
local x_is_ok = false
for i = 0,1 do
if x == i then
x_is_ok = true
end
end
if not x_is_ok then
print( "X must be equal to 1 or 0" )
return
end
Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)
if not (x >= 0 and x <= 1 and math.floor(x) == x) then
print( "X must be equal to 1 or 0" )
return
end
Note that I wrote x >= 0 and x <= 1
. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1
, and what this erroneous expression would return!
The advantages of EditorFor
is that your code is not tied to an <input type="text"
. So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div
you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml
) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor
you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.
some_list2 += ["something"]
is actually
some_list2.extend(["something"])
for one value, there is no difference. Documentation states, that:
s.append(x)
same ass[len(s):len(s)] = [x]
s.extend(x)
same ass[len(s):len(s)] = x
Thus obviously s.append(x)
is same as s.extend([x])
Static variable doesn't link with object of the class. It can be accessed using classname. All object of the class will share static variable.
By making function as static, It will restrict the access of that function within that file.
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
The replace function should work for you.
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE()
performs a case-sensitive match when searching for from_str.
Iterators are first choice over operator[]
. C++11 provides std::begin()
, std::end()
functions.
As your code uses just std::vector
, I can't say there is much difference in both codes, however, operator []
may not operate as you intend to. For example if you use map, operator[]
will insert an element if not found.
Also, by using iterator
your code becomes more portable between containers. You can switch containers from std::vector
to std::list
or other container freely without changing much if you use iterator such rule doesn't apply to operator[]
.
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.
Use the subplots_adjust()
function to move the bottom of the subplot up:
fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.
Then play with the offset in the legend bbox_to_anchor
part of the legend command, to get the legend box where you want it. Some combination of setting the figsize
and using the subplots_adjust(bottom=...)
should produce a quality plot for you.
Alternative: I simply changed the line:
fig = plt.figure(1)
to:
fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')
and changed
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
to
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))
and it shows up fine on my screen (a 24-inch CRT monitor).
Here figsize=(M,N)
sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport
option when including graphics.
To inspect the error message and do something with it (with Python 3)...
try:
some_method()
except Exception as e:
if {value} in e.args:
{do something}
I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.
TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
I faced this error becouse I sent the Query string with wrong format
http://localhost:56110/user/updateuserinfo?Id=55?Name=Basheer&Phone=(111)%20111-1111
------------------------------------------^----(^)-----------^---...
--------------------------------------------must be &
so make sure your
Query String
or passed parameter in the right format
the line
age=document.getElementById("age").value;
says 'the variable I called 'age' has the value of the element with id 'age'. In this case the input field.
The line
voteable=(age<18)?"Too young":"Old enough";
says in a variable I called 'voteable' I store the value following the rule :
"If age is under 18 then show 'Too young' else show 'Old enough'"
The last line tell to put the value of 'voteable' in the element with id 'demo' (in this case the 'p' element)
>>> '\\&' == '\&'
True
>>> len('\\&')
2
>>> print('\\&')
\&
Or in other words: '\\&'
only contains one backslash. It's just escaped in the python shell's output for clarity.
can you please try this: replace the case statement with the below one
Sum(CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END) as Count,
int filesCount = Directory.EnumerateFiles(Directory).Count();
The example provided by Mykhaylo Adamovych is very thorough and exposes most of the major features of JSch. I packaged this code (with attribution, of course) into an open-source library called Remote Session. I added JavaDoc and custom exceptions, and I also provided a facility to specify custom session parameters (RemoteConfig).
One feature that Mykhaylo's code doesn't demonstrate is how to provide an "identity" for remote system interactions. This is critical if you're going to execute commands that require super-user access (i.e. - sudo). Remote Session adds this capability in its SessionHolder.newSession() implementation:
RemoteConfig remoteConfig = RemoteConfig.getConfig();
Path keyPath = remoteConfig.getKeyPath();
if (keyPath == null) {
throw new RemoteCredentialsUnspecifiedException();
}
String keyPass = remoteConfig.getString(RemoteSettings.SSH_KEY_PASS.key());
if (keyPass != null) {
Path pubPath = keyPath.resolveSibling(keyPath.getFileName() + ".pub");
jsch.addIdentity(keyPath.toString(), pubPath.toString(), keyPass.getBytes());
} else {
jsch.addIdentity(keyPath.toString());
}
Note that this behavior is bypassed if the remote system URL includes credentials.
Another feature that Remote Session demonstrates is how to provide a known-hosts file:
if ( ! remoteConfig.getBoolean(RemoteSettings.IGNORE_KNOWN_HOSTS.key())) {
Path knownHosts = keyPath.resolveSibling("known_hosts");
if (knownHosts.toFile().exists()) {
jsch.setKnownHosts(knownHosts.toString());
}
}
Remote Session also adds a ChannelStream class that encapsulates input/output operation for the channel attached to this session. This provides the ability to accumulate the output from the remote session until a specified prompt is received:
private boolean appendAndCheckFor(String prompt, StringBuilder input, Logger logger) throws InterruptedException, IOException {
String recv = readChannel(false);
if ( ! ((recv == null) || recv.isEmpty())) {
input.append(recv);
if (logger != null) {
logger.debug(recv);
}
if (input.toString().contains(prompt)) {
return false;
}
}
return !channel.isClosed();
}
Nothing too complicated, but this can greatly simplify the implementation of interactive remote operations.
yaml.load
Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions.
The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not.
part01_customer_info:
cust_fname: "Homer"
cust_lname: "Himpson"
cust_motto: "I love donuts!"
cust_email: [email protected]
part01_government_info:
govt_sales_taxrate: 1.15
part01_purchase_info:
prch_unit_label: "Bacon-Wrapped Fancy Glazed Donut"
prch_unit_price: 3.00
prch_unit_quant: 7
prch_product_cost: "{{prch_unit_price * prch_unit_quant}}"
prch_total_cost: "{{prch_product_cost * govt_sales_taxrate}}"
part02_shipping_info:
cust_fname: "{{cust_fname}}"
cust_lname: "{{cust_lname}}"
ship_city: Houston
ship_state: Hexas
part03_email_info:
cust_email: "{{cust_email}}"
mail_subject: Thanks for your DoughNutz order!
mail_notes: |
We want the mail_greeting to have all the expected values
with filled-in placeholders (and not curly-braces).
mail_greeting: |
Greetings {{cust_fname}} {{cust_lname}}!
We love your motto "{{cust_motto}}" and we agree with you!
Your total purchase price is {{prch_total_cost}}
The substitutions marked in GREEN are readily available in standard YAML, using anchors, aliases, and merge keys.
The substitutions marked in YELLOW are technically available in standard YAML, but not without a custom type declaration, or some other binding mechanism.
The substitutions marked in RED are not available in standard YAML. Yet there are workarounds and alternatives; such as through string formatting or string template engines (such as python's str.format
).
A frequently-requested feature for YAML is the ability to insert arbitrary variable placeholders that support arbitrary cross-references and expressions that relate to the other content in the same (or transcluded) YAML file(s).
YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes.
YAML also supports custom type declarations, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources.
There are YAML extension libraries, but these are not part of the native YAML spec.
sprintf
or str.format
style functionality from the hosting languageIf you know the target paper size, you can place your content in a DIV with that specific size and add a margin to that DIV to simulate the print margin. Unfortunately, I don't believe you have extra control over the print functionality apart from just show the print dialog box.
They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2)
or using the utility kill(1)
.
If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).
Use it like this:
$("#searchField").focus(function() {
$(this).val("");
});
It has to work. Otherwise it probably never gets focused.
I have try this and it works for me:
Private Sub DelayMs(ms As Long)
Debug.Print TimeValue(Now)
Application.Wait (Now + (ms * 0.00000001))
Debug.Print TimeValue(Now)
End Sub
Private Sub test()
Call DelayMs (2000) 'test code with delay of 2 seconds, see debug window
End Sub
window.addEventListener("hashchange", function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
This will allow the browser to do the work of jumping to the anchor for us and then we will use that position to offset from.
EDIT 1:
As was pointed out by @erb, this only works if you are on the page while the hash is changed. Entering the page with a #something
already in the URL does not work with the above code. Here is another version to handle that:
// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);
// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).
NOTE:
To use jQuery, you could just replace window.addEventListener
with $(window).on
in the examples. Thanks @Neon.
EDIT 2:
As pointed out by a few, the above will fail if you click on the same anchor link two or more times in a row because there is no hashchange
event to force the offset.
This solution is very slightly modified version of the suggestion from @Mave and uses jQuery selectors for simplicity
// The function actually applying the offset
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
JSFiddle for this example is here
We have tested a few OCR engines with Java like Tesseract,Asprise, Abbyy etc. In our analysis, Abbyy gave the best results.
As of today, the best solution is probably AsyncSSH
https://asyncssh.readthedocs.io/en/latest/#scp-client
async with asyncssh.connect('host.tld') as conn:
await asyncssh.scp((conn, 'example.txt'), '.', recurse=True)
-F
is an argument to awk
itself:
$echo "1: " | awk -F":" '/1/ {print $1}'
1
Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:
// assuming you allocated the list
public void addItem(Integer[] list, int item) {
list[1] = item;
}
You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:
// assuming you allocated the list
public void changeArray(Integer[] list) {
list = null;
}
If you pass a non-null list, it won't be null by the time the method returns.
Based on Lucio's code, I made a module. It will return an away with all the files with specific extensions under the one. Just post it here in case anybody needs it.
var path = require('path'),
fs = require('fs');
/**
* Find all files recursively in specific folder with specific extension, e.g:
* findFilesInDir('./project/src', '.html') ==> ['./project/src/a.html','./project/src/build/index.html']
* @param {String} startPath Path relative to this file or other file which requires this files
* @param {String} filter Extension name, e.g: '.html'
* @return {Array} Result files with path string in an array
*/
function findFilesInDir(startPath,filter){
var results = [];
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
results = results.concat(findFilesInDir(filename,filter)); //recurse
}
else if (filename.indexOf(filter)>=0) {
console.log('-- found: ',filename);
results.push(filename);
}
}
return results;
}
module.exports = findFilesInDir;
With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:
$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;
The third line will return a structure that looks like this:
array(1) {
["count(*)"]=>string(4) "1570"
}
In which case the ending echo statement will return:
1570
To see local changes compare to your current branch
git diff .
To see local changed compare to any other existing branch
git diff <branch-name> .
To see changes of a particular file
git diff <branch-name> -- <file-path>
Make sure you run git fetch
at the beginning.
In Scala, building up on YourBestBet's solution but simplified:
def prettyDuration(seconds: Long): List[String] = seconds match {
case t if t < 60 => List(s"${t} seconds")
case t if t < 3600 => s"${t / 60} minutes" :: prettyDuration(t % 60)
case t if t < 3600*24 => s"${t / 3600} hours" :: prettyDuration(t % 3600)
case t => s"${t / (3600*24)} days" :: prettyDuration(t % (3600*24))
}
val dur = prettyDuration(12345).mkString(", ") // => 3 hours, 25 minutes, 45 seconds
If you are using the iThemes Security plugin (former Better WP security) please refer to the answer provided by Mikeys4u.
Also, there is a similar thread related to this plugin on the WordPress support: https://wordpress.org/support/topic/how-to-reset-ithemes-security-plugin-to-fix-issues
Make sure you backup your database before trying any of the solutions.
An alternative, which preserves the state of the working copy is:
git stash
git merge --abort
git stash pop
I generally advise against this, because it is effectively like merging in Subversion as it throws away the branch relationships in the following commit.
String hexString = "45a3df";
Color(int.parse("0xff${hexString}"));
Don't know why this is being downed, this was the solution for me.
Only way that didn't require additional steps
pChart is another great PHP graphing library.
The above mentioned comments are very useful but they are a bit difficult to implement. Below steps you can try, I also tried it and it worked:
It is not possible to tell whether a user will be signed when a page starts loading, there is a work around though.
You can memorize last auth state to localStorage to persist it between sessions and between tabs.
Then, when page starts loading, you can optimistically assume the user will be re-signed in automatically and postpone the dialog until you can be sure (ie after onAuthStateChanged
fires). Otherwise, if the localStorage
key is empty, you can show the dialog right away.
The firebase onAuthStateChanged
event will fire roughly 2 seconds after a page load.
// User signed out in previous session, show dialog immediately because there will be no auto-login
if (!localStorage.getItem('myPage.expectSignIn')) showDialog() // or redirect to sign-in page
firebase.auth().onAuthStateChanged(user => {
if (user) {
// User just signed in, we should not display dialog next time because of firebase auto-login
localStorage.setItem('myPage.expectSignIn', '1')
} else {
// User just signed-out or auto-login failed, we will show sign-in form immediately the next time he loads the page
localStorage.removeItem('myPage.expectSignIn')
// Here implement logic to trigger the login dialog or redirect to sign-in page, if necessary. Don't redirect if dialog is already visible.
// e.g. showDialog()
}
})
componentDidMount
of my App root component. There, in the render, I have some PrivateRoutes
<Router>
<Switch>
<PrivateRoute
exact path={routes.DASHBOARD}
component={pages.Dashboard}
/>
...
And this is how my PrivateRoute is implemented:
export default function PrivateRoute(props) {
return firebase.auth().currentUser != null
? <Route {...props}/>
: localStorage.getItem('myPage.expectSignIn')
// if user is expected to sign in automatically, display Spinner, otherwise redirect to login page.
? <Spinner centered size={400}/>
: (
<>
Redirecting to sign in page.
{ location.replace(`/login?from=${props.path}`) }
</>
)
}
// Using router Redirect instead of location.replace
// <Redirect
// from={props.path}
// to={{pathname: routes.SIGN_IN, state: {from: props.path}}}
// />
The dataframe.sort() method is - so my understanding - deprecated in pandas > 0.18. In order to solve your problem you should use dataframe.sort_values() instead:
f.sort_values(by=["c1","c2"], ascending=[False, True])
The output looks like this:
c1 c2
3 10
2 15
2 30
2 100
1 20
<div ng-app="" ng-controller="myCntrl">
<input type="radio" ng-model="people" value="1"/><label>1</label>
<input type="radio" ng-model="people" value="2"/><label>2</label>
<input type="radio" ng-model="people" value="3"/><label>3</label>
</div>
<script>
function myCntrl($scope){
$scope.people=1;
}
</script>
You can use the ESCAPE
keyword with LIKE
. Simply prepend the desired character (e.g. '!') to each of the existing %
signs in the string and then add ESCAPE '!'
(or your character of choice) to the end of the query.
For example:
SELECT *
FROM prices
WHERE discount LIKE '%80!% off%'
ESCAPE '!'
This will make the database treat 80% as an actual part of the string to search for and not 80(wildcard).
Hey i have checked your code, there is no serious error in your code. this is complete code:
main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/info"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
this is Stackoverflow.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Stackoverflow extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View linearLayout = findViewById(R.id.info);
//LinearLayout layout = (LinearLayout) findViewById(R.id.info);
TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setId(5);
valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
((LinearLayout) linearLayout).addView(valueTV);
}
}
copy this code, and run it. it is completely error free. take care...
This did the trick for me coming from Brackets and being used to ctrl+/ on the numpad.
[
{ "keys": ["ctrl+keypad_divide"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+keypad_divide"], "command": "toggle_comment", "args": { "block": true } }
]
Ignacio Vazquez-Abrams is correct. But to elaborate, re.match()
will return either None
, which evaluates to False
, or a match object, which will always be True
as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.
If you want to consider null values equality too, try the following
select column1, column2,
case
when column1 is NULL and column2 is NULL then 'true'
when column1=column2 then 'true'
else 'false'
end
from table;
You are using ES6 Module syntax.
This means your environment (e.g. node.js) must support ES6 Module syntax.
NodeJS uses CommonJS Module syntax (module.exports
) not ES6 module syntax (export
keyword).
Solution:
babel
npm package to transpile your ES6 to a commonjs
targetor
Examples of CommonJS syntax are (from flaviocopes.com/commonjs/):
exports.uppercase = str => str.toUpperCase()
exports.a = 1
You need to iterate over your ResultSet calling next()
.
This is an example from java2s.com:
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
Column 3 is the TABLE_NAME
(see documentation of DatabaseMetaData::getTables
).
If it's a submodule, try this instead on your repository directory :
rm -f ../.git/modules/submodule-name/index.lock
change submodules-name to your submodule name.
You can use line-height in the table:
<table style="width: 400px; line-height:50px;">
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b
Some might encounter this error either locally or on the server:
syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);
This means that their environment does not support short tags the solution is to use this instead:
<?php echo $jsonTable; ?>
And everything should work fine!
The template it is referring to is the Html helper DisplayFor
.
DisplayFor expects to be given an expression that conforms to the rules as specified in the error message.
You are trying to pass in a method chain to be executed and it doesn't like it.
This is a perfect example of where the MVVM (Model-View-ViewModel) pattern comes in handy.
You could wrap up your Trainer
model class in another class called TrainerViewModel
that could work something like this:
class TrainerViewModel
{
private Trainer _trainer;
public string ShortDescription
{
get
{
return _trainer.Description.ToString().Substring(0, 100);
}
}
public TrainerViewModel(Trainer trainer)
{
_trainer = trainer;
}
}
You would modify your view model class to contain all the properties needed to display that data in the view, hence the name ViewModel.
Then you would modify your controller to return a TrainerViewModel
object rather than a Trainer
object and change your model type declaration in your view file to TrainerViewModel
too.
I know it's an old thread, but I felt compelled to mention the translate method, which is always a good way to replace all character codes above 128 (or other if necessary).
Usage : str.translate(table[, deletechars])
>>> trans_table = ''.join( [chr(i) for i in range(128)] + [' '] * 128 )
>>> 'Résultat'.translate(trans_table)
'R sultat'
>>> '6Â 918Â 417Â 712'.translate(trans_table)
'6 918 417 712'
Starting with Python 2.6, you can also set the table to None, and use deletechars to delete the characters you don't want as in the examples shown in the standard docs at http://docs.python.org/library/stdtypes.html.
With unicode strings, the translation table is not a 256-character string but a dict with the ord() of relevant characters as keys. But anyway getting a proper ascii string from a unicode string is simple enough, using the method mentioned by truppo above, namely : unicode_string.encode("ascii", "ignore")
As a summary, if for some reason you absolutely need to get an ascii string (for instance, when you raise a standard exception with raise Exception, ascii_message
), you can use the following function:
trans_table = ''.join( [chr(i) for i in range(128)] + ['?'] * 128 )
def ascii(s):
if isinstance(s, unicode):
return s.encode('ascii', 'replace')
else:
return s.translate(trans_table)
The good thing with translate is that you can actually convert accented characters to relevant non-accented ascii characters instead of simply deleting them or replacing them by '?'. This is often useful, for instance for indexing purposes.
Working example in php.
First Alert then Redirect works....
Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
If you are looking for a programmatical modal creation, you might love this:
http://nakupanda.github.io/bootstrap3-dialog/
Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.
I ran into this because I made a copy-and-paste of ngBoilerplate into my project on a Mac without Finder showing hidden files. So .bower was not copied with the rest of ngBoilerplate. Thus bower moved resources to bower_components (defult) instead of vendor (as configured) and my app didn't get angular. Probably a corner case, but it might help someone here.
I used a different kind of stack. Here is the implementation.
//
// main.cpp
// Eighth
//
// Created by chaitanya on 4/11/13.
// Copyright (c) 2013 cbilgika. All rights reserved.
//
#include <iostream>
#include <limits>
using namespace std;
struct stack
{
int num;
int minnum;
}a[100];
void push(int n,int m,int &top)
{
top++;
if (top>=100) {
cout<<"Stack Full";
cout<<endl;
}
else{
a[top].num = n;
a[top].minnum = m;
}
}
void pop(int &top)
{
if (top<0) {
cout<<"Stack Empty";
cout<<endl;
}
else{
top--;
}
}
void print(int &top)
{
cout<<"Stack: "<<endl;
for (int j = 0; j<=top ; j++) {
cout<<"("<<a[j].num<<","<<a[j].minnum<<")"<<endl;
}
}
void get_min(int &top)
{
if (top < 0)
{
cout<<"Empty Stack";
}
else{
cout<<"Minimum element is: "<<a[top].minnum;
}
cout<<endl;
}
int main()
{
int top = -1,min = numeric_limits<int>::min(),num;
cout<<"Enter the list to push (-1 to stop): ";
cin>>num;
while (num!=-1) {
if (top == -1) {
min = num;
push(num, min, top);
}
else{
if (num < min) {
min = num;
}
push(num, min, top);
}
cin>>num;
}
print(top);
get_min(top);
return 0;
}
Output:
Enter the list to push (-1 to stop): 5
1
4
6
2
-1
Stack:
(5,5)
(1,1)
(4,1)
(6,1)
(2,1)
Minimum element is: 1
Try it. I think it answers the question. The second element of every pair gives the minimum value seen when that element was inserted.
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:
git checkout some-branch # where some-branch can be replaced by any other branch
git branch base-branch -D # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch # recreating branch with correct commits
Note: You can combine these all by putting && between them
Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?
Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.
Ex:
git checkout feature-old # some branch with the extra commits
git log # gives commits (write down the id of the ones you want)
git checkout base-branch # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch
Now feature-new is your branch without the extra (possibly bad) commits!
First create a class to represent your json data.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Or Use JavaScriptSerializer
to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
Assuming you want to convert it to a Customer
classe's instance. Your class should looks similar to the JSON
structure (Properties)
If ds is the DataSet, you can access the CustomerID column of the first row in the first table with something like:
DataRow dr = ds.Tables[0].Rows[0];
Console.WriteLine(dr["CustomerID"]);
As Oscar Wilde said
Consistency is the last refuge of the unimaginative.
R is more of an evolved rather than designed language, so these things happen. names()
and colnames()
work on a data.frame
but names()
does not work on a matrix:
R> DF <- data.frame(foo=1:3, bar=LETTERS[1:3])
R> names(DF)
[1] "foo" "bar"
R> colnames(DF)
[1] "foo" "bar"
R> M <- matrix(1:9, ncol=3, dimnames=list(1:3, c("alpha","beta","gamma")))
R> names(M)
NULL
R> colnames(M)
[1] "alpha" "beta" "gamma"
R>
It is worth noting, the library that John Slegers mentioned does have a jQuery dependency, however here is a version that is vanilla Javascript.
https://github.com/EldonMcGuinness/querystring.js
I would have simply commented on his post, but I lack the reputation to do so. :/
The example below process the following, albeit irregular, query string:
?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
var qs = "?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";_x000D_
//var qs = "?=&=";_x000D_
//var qs = ""_x000D_
_x000D_
var results = querystring(qs);_x000D_
_x000D_
(document.getElementById("results")).innerHTML =JSON.stringify(results, null, 2);
_x000D_
<script _x000D_
src="https://rawgit.com/EldonMcGuinness/querystring.js/master/dist/querystring.min.js"></script>_x000D_
<pre id="results">RESULTS: Waiting...</pre>
_x000D_
egrep
-- extended grep -- will help here
ls | egrep '\.mp4$|\.mp3$|\.exe$'
should do the job.
An easy way that is compatible pretty much everywhere is to set font-size: 0
on the container, provided you don't have any descendent text nodes you need to style (though it is trivial to override this where needed).
.nospace {
font-size: 0;
}
You could also change from the default display: inline
into block
or inline-block
. Be sure to use the workarounds required for <= IE7 (and possibly ancient Firefoxes) for inline-block
to work.
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
This is all you need, no wrapper needed:
.login-icon{
display:inline-block;
font-size: 40px;
line-height: 50px;
background-color:black;
color:white;
width: 50px;
height: 50px;
text-align: center;
vertical-align: bottom;
}
To file under both 'established' and 'key-value store': Berkeley DB.
Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).
Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.
int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";
hope this help! :)
A little late, but here's a regex I found that returns 0 matches for empty or white spaces:
/^(?!\s*$).+/
You can test this out at regex101
The compareTo method is described as follows:
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Let's say we would like to compare Jedis by their age:
class Jedi implements Comparable<Jedi> {
private final String name;
private final int age;
//...
}
Then if our Jedi is older than the provided one, you must return a positive, if they are the same age, you return 0, and if our Jedi is younger you return a negative.
public int compareTo(Jedi jedi){
return this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}
By implementing the compareTo
method (coming from the Comparable
interface) your are defining what is called a natural order. All sorting methods in JDK will use this ordering by default.
There are ocassions in which you may want to base your comparision in other objects, and not on a primitive type. For instance, copare Jedis based on their names. In this case, if the objects being compared already implement Comparable
then you can do the comparison using its compareTo
method.
public int compareTo(Jedi jedi){
return this.name.compareTo(jedi.getName());
}
It would be simpler in this case.
Now, if you inted to use both name and age as the comparison criteria then you have to decide your oder of comparison, what has precedence. For instance, if two Jedis are named the same, then you can use their age to decide which goes first and which goes second.
public int compareTo(Jedi jedi){
int result = this.name.compareTo(jedi.getName());
if(result == 0){
result = this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}
return result;
}
If you had an array of Jedis
Jedi[] jediAcademy = {new Jedi("Obiwan",80), new Jedi("Anakin", 30), ..}
All you have to do is to ask to the class java.util.Arrays
to use its sort method.
Arrays.sort(jediAcademy);
This Arrays.sort
method will use your compareTo
method to sort the objects one by one.
this get me the text value of exact cell in data grid view
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
label1.Text = dataGridView.CurrentRow.Cells[#].Value.ToString();
}
you can see it in label and change # wih the index of the exact cell you want
Insert date in the following format yyyy-MM-dd
example,
INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`)
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')
select * from table where value % 2 = 1
works fine in mysql.
You can also use StringBuilder class
String b = new StringBuilder(a).toString();
Use of String or StringBuilder varies with your method requirements.
To give a complete answer: yield
is working similar to return
, but in a generator.
As for the commonly given example, this works as follows:
function *squareGen(x) {
var i;
for (i = 0; i < x; i++) {
yield i*i;
}
}
var gen = squareGen(3);
console.log(gen.next().value); // prints 0
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 4
But theres also a second purpose of the yield keyword. It can be used to send values to the generator.
To clarify, a small example:
function *sendStuff() {
y = yield (0);
yield y*y;
}
var gen = sendStuff();
console.log(gen.next().value); // prints 0
console.log(gen.next(2).value); // prints 4
This works, as the value 2
is assigned to y
, by sending it to the generator, after it stopped at the first yield (which returned 0
).
This enables us to to some really funky stuff. (look up coroutine)
You can inject .properties
as a map in your class using @Resource
annotation.
If you are working with XML based configuration
, then add below bean in your spring configuration file:
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:your.properties"/>
</bean>
For, Annotation based:
@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource(
"your.properties"));
return bean;
}
Then you can pick them up in your application as a Map:
@Resource(name = "myProperties")
private Map<String, String> myProperties;
form element UI is somewhat controlled by browser and operating system, so it is not trivial to style them very reliably in a way that it would look the same in all common browser/OS combinations.
Instead, if you want something specific, I would recommend to use a library that provides you stylable form elements. uniform.js is one such library.