If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.
I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization
header in my case ("x-li-format"
and "X-UserName"
here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack
in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:
if (isset($_GET['AuthorizationJack'])) {
$request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}
I just made all requests JSONP because it was the only solution for all of our supported browsers (IE7+ and the regulars). Mind you, your answer technically works for IE9 so you have the correct answer.
Note that in case of IE 7 and IE 9 if statment will give true for ("onhashchange" in windows) but the window.onhashchange will never fire, so its better to store hash and check it after every 100 millisecond whether its changed or not for all versions of IE.
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
I solved this problem via creating storage\framework\sessions
folder.
You will also get this if git doesn't have permissions to read the config files. It will just go up in the hierarchy tree until it needs to cross file systems.
You can get the names from the schema by doing
spark_df.schema.names
Printing the schema can be useful to visualize it as well
spark_df.printSchema()
Register your handler with signal.signal
like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Code adapted from here.
More documentation on signal
can be found here.
If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.
set JAVA_HOME=C:\Program Files\Java\jdk1.6.x
If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.
JAVA_HOME=/usr/java/jdk1.6.x
Call System.Reflection.MethodBase.GetCurrentMethod().Name
from within the method.
Call list()
on the dictionary instead:
keys = list(test)
In Python 3, the dict.keys()
method returns a dictionary view object, which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary into a list results in a list of all the keys:
>>> test = {'foo': 'bar', 'hello': 'world'}
>>> list(test)
['foo', 'hello']
>>> list(test)[0]
'foo'
I tried to avoid too much custom CSS and after reading some other examples I merged the ideas there and got this solution:
<div class="form-group has-feedback has-clear">
<input type="text" class="form-control" ng-model="ctrl.searchService.searchTerm" ng-change="ctrl.search()" placeholder="Suche"/>
<a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="ctrl.clearSearch()" style="pointer-events: auto; text-decoration: none;cursor: pointer;"></a>
</div>
As I don't use bootstrap's JavaScript, just the CSS together with Angular, I don't need the classes has-clear and form-control-clear, and I implemented the clear function in my AngularJS controller. With bootstrap's JavaScript this might be possible without own JavaScript.
I don't think there's a builtin function in angular for doing this, but you can do this by creating a separate scope property containing all the header names, and you can fill this property automatically like this:
var data = {
foo: 'a',
bar: 'b'
};
$scope.objectHeaders = [];
for ( property in data ) {
$scope.objectHeaders.push(property);
}
// Output: [ 'foo', 'bar' ]
The following interface became deprecated in pip 10:
from pip.req import parse_requirements
from pip.download import PipSession
So I switched it just to simple text parsing:
with open('requirements.txt', 'r') as f:
install_reqs = [
s for s in [
line.split('#', 1)[0].strip(' \t\n') for line in f
] if s != ''
]
I used .prop('disabled', true) and it worked like a charm, no redefining, simple.
Had to time it out by 125ms as it interfered with the prop from Bootstrap Dropdown.
You can use the "recursive" setting within glob module to search through subdirectories
For example:
import glob
glob.glob('//Mypath/folder/**/*',recursive = True)
The second line would return all files within subdirectories for that folder location (Note, you need the '**/*' string at the end of your folder string to do this.)
If you specifically wanted to find text files deep within your subdirectories, you can use
glob.glob('//Mypath/folder/**/*.txt',recursive = True)
Nimgoble's is the version I used in 2015. Thought I'd put it here as this question was top of the list in google for "wpf autocomplete textbox"
Install nuget package for project in Visual Studio
Add a reference to the library in the xaml:
xmlns:behaviors="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"
Create a textbox and bind the AutoCompleteBehaviour to List<String>
(TestItems):
<TextBox Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}"
behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding TestItems}" />
IMHO this is much easier to get started and manage than the other options listed above.
So the way I got around this was in the command where i would normally run npm install
or npm ci
, i added NODE_ENV=build
, and then NODE_ENV=production
after the command, so my entire command came out to:
RUN NODE_ENV=build && npm ci && NODE_ENV=production
So far I haven't had any bad reactions, and my development dependencies which are used for building the application all worked / loaded correctly.
I find this to be a better solution than adding an additional command like npm install --only=dev
because it takes less time, and enables me to use the npm ci
command, which is faster and specifically designed to be run inside CI tools / build scripts. (See npi-ci documentation for more information on it)
From the manual:
Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.
So you can do (from bash):
FOOBAR=1 make
resulting in a variable FOOBAR
in your Makefile.
I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
Most of the programs that convert java applications to .exe files are just wrappers around the program, and the end user will still need the JRE installed to run it. As far as I know there aren't any converters that will make it a native executable from bytecode (There have been attempts, but if any turned out successful you would hear of them by now).
As for wrappers, the best ones i've used (as previously suggested) are:
and
best of luck!
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
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 sort
command prints the result of the sorting operation to standard output by default. In order to achieve an "in-place" sort, you can do this:
sort -o file file
This overwrites the input file
with the sorted output. The -o
switch, used to specify an output, is defined by POSIX, so should be available on all version of sort
:
-o Specify the name of an output file to be used instead of the standard output. This file can be the same as one of the input files.
If you are unfortunate enough to have a version of sort
without the -o
switch (Luis assures me that they exist), you can achieve an "in-place" edit in the standard way:
sort file > tmp && mv tmp file
They are Synonyms. No Difference At all
Sticky Session / Session Affinity:
Affinity/Stickiness/Contact between user session and, the server to which user request is sent is retained.
You could also do the following:
if (element.innerHTML.trim() !== '') {
// It has at least one
}
This uses the trim() method to treat empty elements which have only whitespaces (in which case hasChildNodes
returns true) as being empty.
NB: The above method doesn't filter out comments. (so a comment would classify a a child)
To filter out comments as well, we could make use of the read-only Node.nodeType property where Node.COMMENT_NODE
(A Comment node, such as <!-- … -->
) has the constant value - 8
if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '' {
// It has at least one
}
let divs = document.querySelectorAll('div');
for(element of divs) {
if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '') {
console.log('has children')
} else { console.log('no children') }
}
_x000D_
<div><span>An element</span>
<div>some text</div>
<div> </div> <!-- whitespace -->
<div><!-- A comment --></div>
<div></div>
_x000D_
IMPORTANT NOTE: You have to sort your data first.
The part I didn't get is that in the example construction
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
k
is the current grouping key, and g
is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the groupby
iterator itself returns iterators.
Here's an example of that, using clearer variable names:
from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print("A %s is a %s." % (thing[1], key))
print("")
This will give you the output:
A bear is a animal.
A duck is a animal.A cactus is a plant.
A speed boat is a vehicle.
A school bus is a vehicle.
In this example, things
is a list of tuples where the first item in each tuple is the group the second item belongs to.
The groupby()
function takes two arguments: (1) the data to group and (2) the function to group it with.
Here, lambda x: x[0]
tells groupby()
to use the first item in each tuple as the grouping key.
In the above for
statement, groupby
returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.
Here's a slightly different example with the same data, using a list comprehension:
for key, group in groupby(things, lambda x: x[0]):
listOfThings = " and ".join([thing[1] for thing in group])
print(key + "s: " + listOfThings + ".")
This will give you the output:
animals: bear and duck.
plants: cactus.
vehicles: speed boat and school bus.
The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax
But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.
You would call it like this:
$.ajax({
url: 'mypage.html',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
I have shown the success and error function taking no arguments, but they can receive arguments.
The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.
The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.
npm start
will run whatever you have defined for the start
command of the scripts
object in your package.json
file.
So if it looks like this:
"scripts": {
"start": "ng serve"
}
Then npm start
will run ng serve
.
This is the most common technique I've seen:
function getUserIP() {
if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
$addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($addr[0]);
} else {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
}
else {
return $_SERVER['REMOTE_ADDR'];
}
}
Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.
To get around the html
vs body
issue, I fixed this by not animating the css directly but rather calling window.scrollTo();
on each step:
$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
duration: 600,
easing: 'swing',
step: function(val) {
window.scrollTo(0, val);
}
});
This works nicely without any refresh gotchas as it's using cross-browser JavaScript.
Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.
My case it solved i was using
@Html.DropDownList(model => model.TypeId ...)
using
@Html.DropDownListFor(model => model.TypeId ...)
will solve it
To remove the last character do as Mark Byers said
s = s.substring(0, s.length() - 1);
Additionally, another way to remove the characters you don't want would be to use the .replace(oldCharacter, newCharacter)
method.
as in:
s = s.replace(",","");
and
s = s.replace(".","");
Check that your index is really datetime
, not str
Can be helpful:
data.index = pd.to_datetime(data['Index']).values
According to this blog post, you need to set -moz-appearance:textfield;
on the input
.
input[type=number]::-webkit-outer-spin-button,_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: none;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
-moz-appearance:textfield;_x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
Just a little addition. If you've only selected 1 row then the code below will select the value of a column (index of 4, but 5th column) for the selected row:
me.lstIssues.Column(4)
This saves having to use the ItemsSelected property.
Kristian
You have to grant the Superuser
right to the shell app (com.anroid.shell
).
In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser
right in the Magisk Manager
app, whih is in the left upper option menu.
Inside template this working finely.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<input ng-model="name" value="0">
<p>My first expression: {{ (name-0) + 5 }}</p>
</div>
</body>
</html>
```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```
see Chunk Options in the Knitr docs
If you try using:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
and receive an error :
"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"
This means the DATE_FIELD
is not specified in seconds.
In my case, it was milli seconds - EPOCH time
.
The conversion worked using below:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))
An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".
If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.
First add next code in your sp:
BEGIN
dbms_output.enable();
dbms_output.put_line ('TEST LINE');
END;
Compile your code in your Oracle SQL developer. So go to Menu View--> dbms output. Click on Icon Green Plus and select your schema. Run your sp now.
Perhaps if you'd use ??
operator when assigning your string variable, it might help you.
string str = SomeMethodThatReturnsaString() ?? "";
// if SomeMethodThatReturnsaString() returns a null value, "" is assigned to str.
I dont like exceptions I registered the OnSaveChanges and have this
var validationErrors = model.GetValidationErrors();
var h = validationErrors.SelectMany(x => x.ValidationErrors
.Select(f => "Entity: "
+(x.Entry.Entity)
+ " : " + f.PropertyName
+ "->" + f.ErrorMessage));
CSS3 has a box-shadow
property. Vendor prefixes are required at the moment for maximum browser compatibility.
div.box-shadow {
-webkit-box-shadow: 2px 2px 4px 1px #fff;
box-shadow: 2px 2px 4px 1px #fff;
}
There is a generator available at css3please.
As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.
First result:
<span myd1="">directive template1</span>
Second result:
<div myd2=""><span>directive template2</span></div>
Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.
You can also run your batch script through a vbs script like this:
'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True
This will execute your batch file with no cmd window shown.
It would be super useful to be able to toggle logging in the production build. The code below turns the logger off by default.
When I need to see logs, I just type debug(true)
into the console.
var consoleHolder = console;
function debug(bool){
if(!bool){
consoleHolder = console;
console = {};
Object.keys(consoleHolder).forEach(function(key){
console[key] = function(){};
})
}else{
console = consoleHolder;
}
}
debug(false);
To be thorough, this overrides ALL of the console methods, not just console.log
.
I don't have enough reputation points to comment on @greg's answer above, so will add my observations here. I have a Swift project for both iPad and iPhone. I have a method inside my main view controller (relevant bit below). When I test this on a phone, everything works properly and no warnings are generated. When I run it on an iPad, everything works properly but I see the warning about snapshotting the view. The interesting bit, however, is that when I run on an iPad without using the popover controller, everything works properly with no warning. Unfortunately, Apple mandates that the image picker must be used within a popover on iPad, if the camera is not being used.
dispatch_async(dispatch_get_main_queue(), {
let imagePicker: UIImagePickerController = UIImagePickerController();
imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
imagePicker.mediaTypes = [kUTTypeImage];
imagePicker.allowsEditing = false;
imagePicker.delegate = self;
if(UIDevice.currentDevice().userInterfaceIdiom == .Pad){ // on a tablet, the image picker is supposed to be in a popover
let popRect: CGRect = buttonRect;
let popover: UIPopoverController = UIPopoverController(contentViewController: imagePicker);
popover.presentPopoverFromRect(popRect, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Up, animated: true);
}else{
self.presentViewController(imagePicker, animated: true, completion: nil);
}
});
With X installed (e.g. from homebrew, or Quartz), a simple "xterm &" does (nearly) the trick, it opens a new terminal window (not a tab, though).
(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$
Link check online https://regex101.com/r/mqGurh/1
using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
writer.WriteLine("whatever you text is");
}
The second "true" parameter tells it to append.
You can use a simple HTML element <embed src="file.txt">
it loads the external resource and displays it on the screen no js needed
In case you have composite primary key, do like this- ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);
If you don't see a drawable folder for the DPI that you need, you can create it yourself. There's nothing magical about it; it's just a folder which needs to have the correct name.
Take a look at this. a clean and simple solution using jQuery.
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
$(function() {
$("h1").on('mouseover', function() {
$("#goy").text('The dog is in its shed');
}).on('mouseout', function() {
$("#goy").text("");
});
});
The code below is based on Christian Brabandt's answer and seems to do what the OP wants:
function! Whitespace()
if !exists('b:ws')
highlight Conceal ctermbg=NONE ctermfg=240 cterm=NONE guibg=NONE guifg=#585858 gui=NONE
highlight link Whitespace Conceal
let b:ws = 1
endif
syntax clear Whitespace
syntax match Whitespace / / containedin=ALL conceal cchar=·
setlocal conceallevel=2 concealcursor=c
endfunction
augroup Whitespace
autocmd!
autocmd BufEnter,WinEnter * call Whitespace()
augroup END
Append those lines to your ~/.vimrc
and start a new Vim session to see the still imperfect magic happen.
Feel free to edit the default colors and conceal character.
Caveat: something in the *FuncBody
syntax group in several languages prevents the middle dot from showing. I don't know (yet?) how to make that solution more reliable.
If an activity
needs to make a fragment
perform an action after initialization, the easiest way is by having the activity
invoke a method on the fragment
instance. In the fragment
, add a method:
public class DemoFragment extends Fragment {
public void doSomething(String param) {
// do something in fragment
}
}
and then in the activity
, get access to the fragment
using the fragment
manager and call the method
:
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentById(R.id.fragmentDemo);
fragmentDemo.doSomething("some param");
}
}
and then the activity
can communicate directly with the fragment
by invoking this method
.
The dir
wrapper can wrap, any other step, and it all works inside a steps
block, for example:
steps {
sh "pwd"
dir('your-sub-directory') {
sh "pwd"
}
sh "pwd"
}
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
I made a simple JQuery plugin for this if anyone is interested.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function scollPos() {
var div = document.getElementById("myDiv").scrollTop;
document.getElementById("pos").innerHTML = div;
}
</script>
</head>
<body>
<form id="form1">
<div id="pos">
</div>
<div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
Place some large content here
</div>
</form>
</body>
</html>
The author appears to have taken a freemium approach to the font library and provides Black Tie to give different weights to the Font-Awesome library.
Comparing various suggestions (as well as comparing in the context of single-character replacements with various sizes and positions of the target).
In this particular case, splitting on the targets and joining on the replacements (in this case, empty string) is the fastest by at least a factor of 3. Ultimately, performance is different depending on the number of replacements, where the replacements are in the source, and the size of the source. #ymmv
(full results here)
| Test | Compare | Elapsed |
|---------------------------|---------|--------------------------------------------------------------------|
| SplitJoin | 1.00x | 29023 ticks elapsed (2.9023 ms) [in 10K reps, 0.00029023 ms per] |
| Replace | 2.77x | 80295 ticks elapsed (8.0295 ms) [in 10K reps, 0.00080295 ms per] |
| RegexCompiled | 5.27x | 152869 ticks elapsed (15.2869 ms) [in 10K reps, 0.00152869 ms per] |
| LinqSplit | 5.43x | 157580 ticks elapsed (15.758 ms) [in 10K reps, 0.0015758 ms per] |
| Regex, Uncompiled | 5.85x | 169667 ticks elapsed (16.9667 ms) [in 10K reps, 0.00169667 ms per] |
| Regex | 6.81x | 197551 ticks elapsed (19.7551 ms) [in 10K reps, 0.00197551 ms per] |
| RegexCompiled Insensitive | 7.33x | 212789 ticks elapsed (21.2789 ms) [in 10K reps, 0.00212789 ms per] |
| Regex Insentive | 7.52x | 218164 ticks elapsed (21.8164 ms) [in 10K reps, 0.00218164 ms per] |
(note: the Perf
and Vs
are timing extensions I wrote)
void test(string title, string sample, string target, string replacement) {
var targets = target.ToCharArray();
var tox = "[" + target + "]";
var x = new Regex(tox);
var xc = new Regex(tox, RegexOptions.Compiled);
var xci = new Regex(tox, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// no, don't dump the results
var p = new Perf/*<string>*/();
p.Add(string.Join(" ", title, "Replace"), n => targets.Aggregate(sample, (res, curr) => res.Replace(new string(curr, 1), replacement)));
p.Add(string.Join(" ", title, "SplitJoin"), n => String.Join(replacement, sample.Split(targets)));
p.Add(string.Join(" ", title, "LinqSplit"), n => String.Concat(sample.Select(c => targets.Contains(c) ? replacement : new string(c, 1))));
p.Add(string.Join(" ", title, "Regex"), n => Regex.Replace(sample, tox, replacement));
p.Add(string.Join(" ", title, "Regex Insentive"), n => Regex.Replace(sample, tox, replacement, RegexOptions.IgnoreCase));
p.Add(string.Join(" ", title, "Regex, Uncompiled"), n => x.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled"), n => xc.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled Insensitive"), n => xci.Replace(sample, replacement));
var trunc = 40;
var header = sample.Length > trunc ? sample.Substring(0, trunc) + "..." : sample;
p.Vs(header);
}
void Main()
{
// also see https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string
"Control".Perf(n => { var s = "*"; });
var text = "My name @is ,Wan.;'; Wan";
var clean = new[] { '@', ',', '.', ';', '\'' };
test("stackoverflow", text, string.Concat(clean), string.Empty);
var target = "o";
var f = "x";
var replacement = "1";
var fillers = new Dictionary<string, string> {
{ "short", new String(f[0], 10) },
{ "med", new String(f[0], 300) },
{ "long", new String(f[0], 1000) },
{ "huge", new String(f[0], 10000) }
};
var formats = new Dictionary<string, string> {
{ "start", "{0}{1}{1}" },
{ "middle", "{1}{0}{1}" },
{ "end", "{1}{1}{0}" }
};
foreach(var filler in fillers)
foreach(var format in formats) {
var title = string.Join("-", filler.Key, format.Key);
var sample = string.Format(format.Value, target, filler.Value);
test(title, sample, target, replacement);
}
}
You need to use table-layout:fixed
in order for CSS ellipsis to work on the table cells.
.table {
table-layout:fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
All the other response are very miss-leading for somebody coming from google and looking for "timestamp in go"! YYYYMMDDhhmmss is not a "timestamp".
To get the "timestamp" of a date in go (number of seconds from january 1970), the correct function is .Unix(), and it really return an integer
Type
netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789
perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.
http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
or you can just do kill %1
, which will kill the first job put in background
If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.
With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.
Below is the summary of the style I have defined for emailing the code snippets.
Do not check spelling or grammar, Border:
Box: (Single solid line, Orange, 0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
In my case the issue was I had installed an app with the package name let's say com.example.package using android studio on my device. I created another app with the same package name and was trying to install it on my device. That is what was causing the problem. So just check on your device whether another app with the same package name already exists or not.
The answer, u
, (and many others) is in $ vimtutor
.
JPA 2.1 now support Stored Procedure, read the Java doc here.
Example:
StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("sales_tax");
// set parameters
storedProcedure.registerStoredProcedureParameter("subtotal", Double.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("tax", Double.class, ParameterMode.OUT);
storedProcedure.setParameter("subtotal", 1f);
// execute SP
storedProcedure.execute();
// get result
Double tax = (Double)storedProcedure.getOutputParameterValue("tax");
See detailed example here.
Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200"
.
This answer might be arriving late but is an interesting find. Using compile can really save you time if you are planning on using the regex multiple times (this is also mentioned in the docs). Below you can see that using a compiled regex is the fastest when the match method is directly called on it. passing a compiled regex to re.match makes it even slower and passing re.match with the patter string is somewhere in the middle.
>>> ipr = r'\D+((([0-2][0-5]?[0-5]?)\.){3}([0-2][0-5]?[0-5]?))\D+'
>>> average(*timeit.repeat("re.match(ipr, 'abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re}))
1.5077415757028423
>>> ipr = re.compile(ipr)
>>> average(*timeit.repeat("re.match(ipr, 'abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re}))
1.8324008992184038
>>> average(*timeit.repeat("ipr.match('abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re}))
0.9187896518778871
Set the background color of the src to none and allow transparencey.
[WITHIN SCR PAGE STYLE]
<style type="text/css">
body
{
background:none transparent;
}
</style>
[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>
NOTE: I code my CSS a little different to how everyone else does.
I suggest you to use mysqldump like so:
mysqldump --compatible=mssql
phpMyAdmin is still a web-app and could potentially have some limitations for large databases (script execution time, allocatable memory and so on).
zip extension is missing, You can avoid this error by simple running below command, It will take version by default
sudo apt-get install php-zip
In case you need any specific version, You need to mention a specific version of your php, Suppose I need to install X
version of php-zip then the command will be.
sudo apt-get install phpX-zip
Replace X
with your required version, In my case, it is X = 7.3
Yet another option is to run swagger using docker, you can use this docker image:
https://hub.docker.com/r/madscientist/swagger-ui/
I made this ghetto little BASH script to kill running containers and rebuild, so basically each time you make a change to your spec and want to see it, just run the script. Make sure to put the name of your application in the APP_NAME variable
#!/bin/bash
# Replace my_app with your application name
APP_NAME="my_app"
# Clean up old containers and images
old_containers=$(docker ps -a | grep $APP_NAME | awk '{ print $1 }')
old_images=$(docker images | grep $APP_NAME | awk '{ print $3 }')
if [[ $old_containers ]];
then
echo "Stopping old containers: $old_containers"
docker stop $old_containers
echo "Removing old containers: $old_containers"
docker rm $old_containers
fi
if [[ $old_images ]];
then
echo "Removing stale images"
docker rmi $old_images
fi
# Create new image
echo "Creating new image for $APP_NAME"
docker build . -t $APP_NAME
# Run container
echo "Running container with image $APP_NAME"
docker run -d --name $APP_NAME -p 8888:8888 $APP_NAME
echo "Check out your swaggery goodness here:
http://localhost:8888/swagger-ui/?url=http://localhost:8888/swagger-ui/swagger.yaml"
Why relying on objc runtime? I don't get the point. By using something like the following you will achieve almost the identical behaviour of a stored property, by using only a pure Swift approach:
extension UIViewController {
private static var _myComputedProperty = [String:Bool]()
var myComputedProperty:Bool {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIViewController._myComputedProperty[tmpAddress] ?? false
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIViewController._myComputedProperty[tmpAddress] = newValue
}
}
}
You don not need to create a $(document).mousemove( function(e) {})
to handle mouse x,y. Get the event in the $.hover
function and from there it is possible to get x and y positions of the mouse. See the code below:
$('foo').hover(function(e){
var pos = [e.pageX-150,e.pageY];
$('foo1').dialog( "option", "position", pos );
$('foo1').dialog('open');
},function(){
$('foo1').dialog('close');
});
You can use exec
command to redirect all stdout/stderr output of any commands later.
sample script:
exec 2> your_file2 > your_file1
your other commands.....
return 0
When a C or C++ program reaches the end of main
the compiler will automatically generate code to return 0, so there is no need to put return 0;
explicitly at the end of main
.
Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments: "I didn't know that." or "That's bad advice!" My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard. For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:
[...] a return from the initial call to the
main
function is equivalent to calling theexit
function with the value returned by themain
function as its argument; reaching the}
that terminates themain
function returns a value of 0.
For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:
If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;
All versions of both standards since then (C99 and C++98) have maintained the same idea. We rely on automatically generated member functions in C++, and few people write explicit return;
statements at the end of a void
function. Reasons against omitting seem to boil down to "it looks weird". If, like me, you're curious about the rationale for the change to the C standard read this question. Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.
Additionally, the C++ Core Guidelines contains multiple instances of omitting return 0;
at the end of main
and no instances in which an explicit return is written. Although there is not yet a specific guideline on this particular topic in that document, that seems at least a tacit endorsement of the practice.
So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.
You can use datejs and convert in different formate. I have tested some formate and working fine.
var d = new Date(1469433907836);
d.toLocaleString() // 7/25/2016, 1:35:07 PM
d.toLocaleDateString() // 7/25/2016
d.toDateString() // Mon Jul 25 2016
d.toTimeString() // 13:35:07 GMT+0530 (India Standard Time)
d.toLocaleTimeString() // 1:35:07 PM
d.toISOString(); // 2016-07-25T08:05:07.836Z
d.toJSON(); // 2016-07-25T08:05:07.836Z
d.toString(); // Mon Jul 25 2016 13:35:07 GMT+0530 (India Standard Time)
d.toUTCString(); // Mon, 25 Jul 2016 08:05:07 GMT
I tried almost everything but could not help,what helped me was disabling SIP(System Integration Protection) n it works,I do not know what happens when and how but system file get confused somewhere and causes this...though there might be risks to disabling this obviously
here is how
1.Power on your Mac and hold down the [command]+[R] keys to access the Recovery Partition.
2.From the Recovery Partition, click Utilities from the menu bar, and then select Terminal.
3.Enter the following command into Terminal and press Enter to execute it: csrutil disable
4.Once the command has executed, exit the Terminal and reboot the Mac. When you log back into OS X, SIP will be disabled.
As an alternative to virtualenv, you can use anaconda.
On Linux, to create an environment with python 2.7:
conda create -n python2p7 python=2.7
source activate python2p7
To deactivate it, you do:
source deactivate
It is possible to install other package inside your environment.
I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do
select field from table where field REGEXP '^-?[0-9]+$';
this is reasonably fast. If your field is numeric, just test for
ceil(field) = field
instead.
An alternative way if you need something more (besides using the keys
method):
hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }
obviously you would only do that if you want to manipulate the array while retrieving it..
I tried several solutions above, but none solved my problem. Solution to refresh a subform in a form after saving data to database:
Me.subformname.Requery
It worked fine for me. Good luck.
For me, the issue was the wrong directory. Make sure you copy paste the directory from your file explorer and not assume the directory specified on the docs page correct.
Kindly to see what is /usr/bin/python
pointing to
if it is pointing to python3 or higher
change to python2.7
This should solve the issue.
I was getting install error for all the python packages. Abe Karplus's solution & discussion gave me the hint as to what could be the problem.
Then I recalled that I had manually changed the /usr/bin/python
from python2.7
to /usr/bin/python3.5
, which actually was causing the issue. Once I reverted
the same. It got solved.
e.g. git cherry-pick 3a7322ac^..7d7c123c
Assuming you are on branchA
where you want to pick commits (start & end commit SHA for the range is given and left commit SHA is older) from branchB
. The entire range of commits (both inclusive) will be cherry picked in branchA
.
The examples given in the official documentation are quite useful.
You need to install Express locally into the context of your application (node_modules
folder):
$ npm install express
The reason for this is that applications always look in their local context for any dependencies. The global installation is only for setting up system-wide available binaries, such as unit test runners or bootstrappers or things like that.
With Express, when you install it globally, you get an express
binary that can bootstrap an application for you. For more information, type
$ express --help
So, to answer your final question: YES, you need to install it without -g
.
I created a function that might help. All it does is imitate the alert but put an image instead of text.
function alertImage(imgsrc) {
$('.d').css({
'position': 'absolute',
'top': '0',
'left': '50%',
'-webkit-transform': 'translate(-50%, 0)'
});
$('.d').animate({
opacity: 0
}, 0)
$('.d').animate({
opacity: 1,
top: "10px"
}, 250)
$('.d').append('An embedded page on this page says')
$('.d').append('<br><img src="' + imgsrc + '">')
$('.b').css({
'position':'absolute',
'-webkit-transform': 'translate(-100%, -100%)',
'top':'100%',
'left':'100%',
'display':'inline',
'background-color':'#598cbd',
'border-radius':'4px',
'color':'white',
'border':'none',
'width':'66',
'height':'33'
})
}
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<div class="d"><button onclick="$('.d').html('')" class="b">OK</button></div>
.d{
font-size: 17px;
font-family: sans-serif;
}
.b{
display: none;
}
Actually, there are four forms of this operator:
<>
!=
^=
and even
¬= -- worked on some obscure platforms in the dark ages
which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).
[2020 Update]
Actually, after spending some times trying the different option provided here which are quite old, I found that the easiest way to do it was to use a small paid tool built for that purpose : FireDaemon Pro. I was trying to run Selenium standalone server as a service and none of the free option worked instantly.
The tool is quite cheap (50 USD one-time-licence, 30 days trial) and it took me 5 minutes to set up the server service instead of a half a day of reading/troubleshooting. So far, it works like a charm.
I have absolutely no link with FusionPro, this is a pure disinterested advice, but feel free to delete if it violates forum rules.
Generally speaking, this is the configuration file of web applications in java. It instructs the servlet container (tomcat for ex.) which classes to load, what parameters to set in the context, and how to intercept requests coming from browsers.
There you specify:
In servlet 3.0 many of the web.xml parts are optional. These configurations can be done via annotations (@WebServlet
, @WebListener
)
Django 1.10 (release notes) added the is
and is not
comparison operators to the if
tag. This change makes identity testing in a template pretty straightforward.
In[2]: from django.template import Context, Template
In[3]: context = Context({"somevar": False, "zero": 0})
In[4]: compare_false = Template("{% if somevar is False %}is false{% endif %}")
In[5]: compare_false.render(context)
Out[5]: u'is false'
In[6]: compare_zero = Template("{% if zero is not False %}not false{% endif %}")
In[7]: compare_zero.render(context)
Out[7]: u'not false'
If You are using an older Django then as of version 1.5 (release notes) the template engine interprets True
, False
and None
as the corresponding Python objects.
In[2]: from django.template import Context, Template
In[3]: context = Context({"is_true": True, "is_false": False,
"is_none": None, "zero": 0})
In[4]: compare_true = Template("{% if is_true == True %}true{% endif %}")
In[5]: compare_true.render(context)
Out[5]: u'true'
In[6]: compare_false = Template("{% if is_false == False %}false{% endif %}")
In[7]: compare_false.render(context)
Out[7]: u'false'
In[8]: compare_none = Template("{% if is_none == None %}none{% endif %}")
In[9]: compare_none.render(context)
Out[9]: u'none'
Although it does not work the way one might expect.
In[10]: compare_zero = Template("{% if zero == False %}0 == False{% endif %}")
In[11]: compare_zero.render(context)
Out[11]: u'0 == False'
For win10 I had the same issue:
error during connect: Post http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.39/images/load?quiet=0: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
The docker service appeared to work. Restarting did not help. Running the binary from the installation directory as administrator helped.
In my case:
run as administrator -> C:\Program Files\Docker\Docker\Docker for Windows.exe
I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.
private void replaceView(View oldV,View newV){
ViewGroup par = (ViewGroup)oldV.getParent();
if(par == null){return;}
int i1 = par.indexOfChild(oldV);
par.removeViewAt(i1);
par.addView(newV,i1);
}
This might work...
from p in db.products
select new
{
Owner = (p.price > 0 ?
from q in db.Users select q.Name :
from r in db.ExternalUsers select r.Name)
}
Math.random
no, but the ran library solves this. It has almost all distributions you can imagine and supports seeded random number generation. Example:
ran.core.seed(0)
myDist = new ran.Dist.Uniform(0, 1)
samples = myDist.sample(1000)
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="9"
android:orientation="horizontal" >
<ImageView
android:id="@+id/ring_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/ring_oss" />
<ImageView
android:id="@+id/maila_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
<EditText
android:id="@+id/edittxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
</LinearLayout>
Update with psycopg2 2.7:
The classic executemany()
is about 60 times slower than @ant32 's implementation (called "folded") as explained in this thread: https://www.postgresql.org/message-id/20170130215151.GA7081%40deb76.aryehleib.com
This implementation was added to psycopg2 in version 2.7 and is called execute_values()
:
from psycopg2.extras import execute_values
execute_values(cur,
"INSERT INTO test (id, v1, v2) VALUES %s",
[(1, 2, 3), (4, 5, 6), (7, 8, 9)])
Previous Answer:
To insert multiple rows, using the multirow VALUES
syntax with execute()
is about 10x faster than using psycopg2 executemany()
. Indeed, executemany()
just runs many individual INSERT
statements.
@ant32 's code works perfectly in Python 2. But in Python 3, cursor.mogrify()
returns bytes, cursor.execute()
takes either bytes or strings, and ','.join()
expects str
instance.
So in Python 3 you may need to modify @ant32 's code, by adding .decode('utf-8')
:
args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x).decode('utf-8') for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)
Or by using bytes (with b''
or b""
) only:
args_bytes = b','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute(b"INSERT INTO table VALUES " + args_bytes)
This feels very hacky, but in chrome 41 on ubuntu I can make a <br>
slightly stylable:
br {
content: "";
margin: 2em;
display: block;
font-size: 24%;
}
I control the spacing with the font size.
I made some test cases to see how the response changes as browsers update.
*{outline: 1px solid hotpink;}
div {
display: inline-block;
width: 10rem;
margin-top: 0;
vertical-align: top;
}
h2 {
display: block;
height: 3rem;
margin-top:0;
}
.old br {
content: "";
margin: 2em;
display: block;
font-size: 24%;
outline: red;
}
.just-font br {
content: "";
display: block;
font-size: 200%;
}
.just-margin br {
content: "";
display: block;
margin: 2em;
}
.brbr br {
content: "";
display: block;
font-size: 100%;
height: 1em;
outline: red;
display: block;
}
_x000D_
<div class="raw">
<h2>Raw <code>br</code>rrrrs</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="old">
<h2>margin & font size</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="just-font">
<h2>only font size</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="just-margin">
<h2>only margin</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="brbr">
<h2><code>br</code>others vs only <code>br</code>s</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
_x000D_
They all have their own version of strange behaviour. Other than the browser default, only the last one respects the difference between one and two brs.
Had a hard time finding the logs because the IDE was crashing on launch, if you are on Mac and use Android Studio 4.1 then the logs location may be found at /Users/{user}/Library/Logs/Google/AndroidStudio4.1/
And to be specific for me it is on macOS Big Sur
Please see my answer to this question. Bottom line whenever two threads need to acquire two different resources, and do so in different orders then you can get deadlocks.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
doesnt directly answer your question. But helpful for those who want to start something after some time.
Future.delayed(Duration(seconds: 1), () {
print('yo hey');
});
Similarly to what was suggested before, this is how I did it:
find . -name '*OldText*' -exec sh -c 'mv "$0" "${0/OldText/NewText}"' {} \;
I first validated with
find . -name '*OldText*' -exec sh -c 'echo mv "$0" "${0/OldText/NewText}"' {} \;
You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in
val myList1 = 1.0 :: 5.5 :: Nil
val myList2 = 2.2 :: 3.7 :: mylist1
or use a var as in
var myList = 1.0 :: 5.5 :: Nil
myList :::= List(2.2, 3.7)
This is equivalent syntax for:
myList = myList.:::(List(2.2, 3.7))
Or you could use one of the mutable collections such as
val myList = scala.collection.mutable.MutableList(1.0, 5.5)
myList.++=(List(2.2, 3.7))
Not to be confused with the following that does not modify the original mutable List, but returns a new value:
myList.++:(List(2.2, 3.7))
However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.
I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.
I'm going to suggest the non-obvious. There is a fantastic (and often under-used) tool called the Immediate Window in Visual Basic Editor. Basically, you can write out commands in VBA and execute them on the spot, sort of like command prompt. It's perfect for cases like this.
Press ALT+F11 to open VBE, then Control+G to open the Immediate Window. Type the following and hit enter:
for each v in range("K2:K5000") : v.value = "'" & v.value : next
And boom! You are all done. No need to create a macro, declare variables, no need to drag and copy, etc. Close the window and get back to work. The only downfall is to undo it, you need to do it via code since VBA will destroy your undo stack (but that's simple).
You can actually have all the code in the aspx page. As explained here.
Sample from here:
<%@ Language=C# %>
<HTML>
<script runat="server" language="C#">
void MyButton_OnClick(Object sender, EventArgs e)
{
MyLabel.Text = MyTextbox.Text.ToString();
}
</script>
<body>
<form id="MyForm" runat="server">
<asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
<asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
<asp:label id="MyLabel" runat="server"></asp:label>
</form>
</body>
</HTML>
m = len(mylist)
for index,value in enumerate(mylist):
for i in xrange(1,m):
if(index != i):
if (L[i] == L[index]):
print "Location %d and location %d has same list-entry: %r" % (index,i,value)
This has some redundancy that can be improved however.
If this helps, you can also use FileSystemObject to retrieve all subfolders of a folder. You need to check the reference "Microsot Scripting Runtime" to get Intellisense and use the "new" keyword.
Sub GetSubFolders()
Dim fso As New FileSystemObject
Dim f As Folder, sf As Folder
Set f = fso.GetFolder("D:\Proj\")
For Each sf In f.SubFolders
'Code inside
Next
End Sub
For me, this worked:
Login as the owner of the process (even root
is denied permission)
~$ su - process_owner
Tail the file descriptor as mentioned in many other answers.
~$ tail -f /proc/<process-id>/fd/1 # (0: stdin, 1: stdout, 2: stderr)
Using Base64 string in JSON will be very heavy. The parser has to do a lot of heavy lifting. Currently, Fresco only supports base supports Base64. Better you put something on Amazon Cloud or Firebase Cloud. And get an image as a URL. So that you can use Picasso or Glide for caching.
Refer this code, auth.ts file
import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { } from 'angular-2-local-storage';
import { Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(public localStorageService:LocalStorageService, private router: Router){}
canActivate() {
// Imaginary method that is supposed to validate an auth token
// and return a boolean
var logInStatus = this.localStorageService.get('logInStatus');
if(logInStatus == 1){
console.log('****** log in status 1*****')
return true;
}else{
console.log('****** log in status not 1 *****')
this.router.navigate(['/']);
return false;
}
}
}
// *****And the app.routes.ts file is as follow ******//
import { Routes } from '@angular/router';
import { HomePageComponent } from './home-page/home- page.component';
import { WatchComponent } from './watch/watch.component';
import { TeachersPageComponent } from './teachers-page/teachers-page.component';
import { UserDashboardComponent } from './user-dashboard/user- dashboard.component';
import { FormOneComponent } from './form-one/form-one.component';
import { FormTwoComponent } from './form-two/form-two.component';
import { AuthGuard } from './authguard';
import { LoginDetailsComponent } from './login-details/login-details.component';
import { TransactionResolver } from './trans.resolver'
export const routes:Routes = [
{ path:'', component:HomePageComponent },
{ path:'watch', component:WatchComponent },
{ path:'teachers', component:TeachersPageComponent },
{ path:'dashboard', component:UserDashboardComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'formone', component:FormOneComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'formtwo', component:FormTwoComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'login-details', component:LoginDetailsComponent, canActivate: [AuthGuard] },
];
You can read the whole file and split lines using str.splitlines
:
temp = file.read().splitlines()
Or you can strip the newline by hand:
temp = [line[:-1] for line in file]
Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.
This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).
If you want to avoid this you can add a newline at the end of file:
with open(the_file, 'r+') as f:
f.seek(-1, 2) # go at the end of the file
if f.read(1) != '\n':
# add missing newline if not already present
f.write('\n')
f.flush()
f.seek(0)
lines = [line[:-1] for line in f]
Or a simpler alternative is to strip
the newline instead:
[line.rstrip('\n') for line in file]
Or even, although pretty unreadable:
[line[:-(line[-1] == '\n') or len(line)+1] for line in file]
Which exploits the fact that the return value of or
isn't a boolean, but the object that was evaluated true or false.
The readlines
method is actually equivalent to:
def readlines(self):
lines = []
for line in iter(self.readline, ''):
lines.append(line)
return lines
# or equivalently
def readlines(self):
lines = []
while True:
line = self.readline()
if not line:
break
lines.append(line)
return lines
Since readline()
keeps the newline also readlines()
keeps it.
Note: for symmetry to readlines()
the writelines()
method does not add ending newlines, so f2.writelines(f.readlines())
produces an exact copy of f
in f2
.
I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:
select min(Id), distinct MailId, EmailAddress, Name
from yourTableName
group by MailId, EmailAddress, Name
I see that I am using a GROUP BY clause
but you still won't have two rows against any particular MailId
.
If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:
'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"
Regular expressions have word boundaries, such as \b
which matches start or end of a word. Thus,
'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"
In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:
'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"
Hi try the following code it will be useful to you,
((ImageView)findViewById(R.id.ImageViewButton)).setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_over);
if(event.getAction() == MotionEvent.ACTION_UP)
((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_normal);
return false;
}
});
Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.
Just cast one of the two operands to a float first.
v = (float)s / t;
The cast has higher precedence than the division, so happens before the division.
The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17
Create a function with return format yyyy-mm-hh hh:mi:ss.sss
create function fn_retornaFecha (@i_fecha datetime)
returns varchar(23)
as
begin
declare
@w_fecha varchar(23),
@w_anio varchar(4),
@w_mes varchar(2),
@w_dia varchar(2),
@w_hh varchar(2),
@w_nn varchar(2),
@w_ss varchar(2),
@w_sss varchar(3)
select @w_fecha = null
if ltrim(rtrim(@i_fecha)) is not null
begin
select
@w_anio = replicate('0',4-char_length( convert(varchar(4), year(@i_fecha)) )) + convert(varchar(4), year(@i_fecha)),
@w_mes = replicate('0',2-char_length( convert(varchar(2),month(@i_fecha)) )) + convert(varchar(2),month(@i_fecha)),
@w_dia = replicate('0',2-char_length( convert(varchar(2), day(@i_fecha)) )) + convert(varchar(2), day(@i_fecha)) ,
@w_hh = replicate('0',2-char_length( convert(varchar(2),datepart( hh, @i_fecha ) ) )) + convert(varchar(2),datepart( hh, @i_fecha ) ),
@w_nn = replicate('0',2-char_length( convert(varchar(2),datepart( mi, @i_fecha ) ) )) + convert(varchar(2),datepart( mi, @i_fecha ) ),
@w_ss = replicate('0',2-char_length( convert(varchar(2),datepart( ss, @i_fecha ) ) )) + convert(varchar(2),datepart( ss, @i_fecha ) ),
@w_sss = convert(varchar(3),datepart( ms, @i_fecha ) ) + replicate('0',3-DATALENGTH( convert(varchar(3),datepart( ms, @i_fecha ) ) ))
select @w_fecha = @w_anio + '-' + @w_mes + '-' + @w_dia + ' ' + @w_hh + ':' + @w_nn + ':' + @w_ss + '.' + @w_sss
end
return @w_fecha
end
go
Example
select fn_retornaFecha(getdate())
and the result is: 2016-12-21 10:12:50.123
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
a much more practical way for those who do not want to use regex:
$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);
note: it works with phone numbers too.
The problem with your macro is that once you have opened your destination Workbook (xlw
in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.
Sub UploadData()
Dim xlo As New Excel.Application
Dim xlw As New Excel.Workbook
Dim myWb as Excel.Workbook
Set myWb = ActiveWorkbook
Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text
xlw.Save
xlw.Close
Set xlo = Nothing
Set xlw = Nothing
End Sub
If you prefer, you could also use myWb.Activate
to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).
No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.
I doubt you need to extend your sessions time though.
It has pretty sensible timeout at the moment and there are no reasons to extend it.
Strictly stated you must check all of the following: defined, not empty AND not None.
For "normal" variables it makes a difference if defined and set or not set. See foo
and bar
in the example below. Both are defined but only foo
is set.
On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz
and xyz.msg
in the example below:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
IE assumes that the clicking of a link heralds a new navigation where the current page contents will be replaced. As part of the process for perparing for that it halts the code that animates the GIFs. I doubt there is anything you can do about it (unless you aren't actually navigating in which case use return false in the onclick event).
I had the same problem after upgrading to Ubuntu 14.10. I found this link which describes the steps to be followed in order to apply the patch. It takes a while since you have to start all over again: downloading, building, installing... but it worked for me! Sorry I'm not an expert and I can't provide further details.
Here are the steps described in the link above:
If you want to patch and build mysql-workbench yourself, get the source from for 6.2.3. From the directory you downloaded it to, do:
wget 'http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-workbench-community-6.2.3-src.tar.gz'
tar xvf mysql-workbench-community-6.2.3-src.tar.gz && cd mysql-workbench-community-6.2.3-src
wget -O patch-glib.diff 'http://bugs.mysql.com/file.php?id=21874&bug_id=74147'
patch -p0 < patch-glib.diff
sudo apt-get build-dep mysql-workbench
sudo apt-get install libgdal-dev
cd build
cmake .. -DBUILD_CONFIG=mysql_release
make
sudo make install
Hope this can be helpful.
Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).
Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.
Temporal types are the set of time-based types that can be used in persistent state mappings.
The list of supported temporal types includes the three java.sql
types java.sql.Date
, java.sql.Time
, and java.sql.Timestamp
, and it includes the two java.util
types java.util.Date
and java.util.Calendar
.
The java.sql
types are completely hassle-free. They act just like any other simple mapping type and do not need any special consideration.
The two java.util
types need additional metadata, however, to indicate which of the JDBC java.sql
types to use when communicating with the JDBC driver. This is done by annotating them with the @Temporal
annotation and specifying the JDBC type as a value of the TemporalType
enumerated type.
There are three enumerated values of DATE, TIME, and TIMESTAMP to represent each of the java.sql
types.
How about ['hello', 'hi', 'howdy'].includes(str)
?
Using query comprehension syntax you could achieve the orderby as follows:
var uniqueColors = (from dbo in database.MainTable
where dbo.Property
orderby dbo.Color.Name ascending
select dbo.Color.Name).Distinct();
do you work with a 3d tool such as maya? for maya you can look at http://www.inka3d.com
just use
file:///
works in IE, Firefox and Chrome as far as I can tell.
see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
I prefer using an adjacency list of Indices ( not pointers )
typedef std::vector< Vertex > Vertices;
typedef std::set <int> Neighbours;
struct Vertex {
private:
int data;
public:
Neighbours neighbours;
Vertex( int d ): data(d) {}
Vertex( ): data(-1) {}
bool operator<( const Vertex& ref ) const {
return ( ref.data < data );
}
bool operator==( const Vertex& ref ) const {
return ( ref.data == data );
}
};
class Graph
{
private :
Vertices vertices;
}
void Graph::addEdgeIndices ( int index1, int index2 ) {
vertices[ index1 ].neighbours.insert( index2 );
}
Vertices::iterator Graph::findVertexIndex( int val, bool& res )
{
std::vector<Vertex>::iterator it;
Vertex v(val);
it = std::find( vertices.begin(), vertices.end(), v );
if (it != vertices.end()){
res = true;
return it;
} else {
res = false;
return vertices.end();
}
}
void Graph::addEdge ( int n1, int n2 ) {
bool foundNet1 = false, foundNet2 = false;
Vertices::iterator vit1 = findVertexIndex( n1, foundNet1 );
int node1Index = -1, node2Index = -1;
if ( !foundNet1 ) {
Vertex v1( n1 );
vertices.push_back( v1 );
node1Index = vertices.size() - 1;
} else {
node1Index = vit1 - vertices.begin();
}
Vertices::iterator vit2 = findVertexIndex( n2, foundNet2);
if ( !foundNet2 ) {
Vertex v2( n2 );
vertices.push_back( v2 );
node2Index = vertices.size() - 1;
} else {
node2Index = vit2 - vertices.begin();
}
assert( ( node1Index > -1 ) && ( node1Index < vertices.size()));
assert( ( node2Index > -1 ) && ( node2Index < vertices.size()));
addEdgeIndices( node1Index, node2Index );
}
Well it's not even close to the full spec, but there is a JavaScript and Canvas based PDF viewer out there.
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
The kernel is part of the operating system, while not being the operating system itself. Rather than going into all of what a kernel does, I will defer to the wikipedia page: http://en.wikipedia.org/wiki/Kernel_%28computing%29. Great, thorough overview.
Like said in docs, use
<meta property="og:url" content="http://www.your-domain.com/your-page.html" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Your Website Title" />
<meta property="og:description" content="Your description" />
<meta property="og:image" content="http://www.your-domain.com/path/image.jpg" />
image size recommended: 1 200 x 630
even simpler, adding up to String[]
,
use built-in filter filter(StringUtils::isNotEmpty)
of org.apache.commons.lang3
import org.apache.commons.lang3.StringUtils;
String test = "a\nb\n\nc\n";
String[] lines = test.split("\\n", -1);
String[] result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(result));
and output:
[a, b, , c, ]
[a, b, c]
@blytung Has a nice function to replace that function
<?php
$url = "http://www.example.org/";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
echo "\n<br />";
$contents = '';
} else {
curl_close($ch);
}
if (!is_string($contents) || !strlen($contents)) {
echo "Failed to get contents.";
$contents = '';
}
echo $contents;
?>
There's literature about it:
Optimized Pagination using MySQL, making the difference between counting the total amount of rows, and pagination.
Efficient Pagination Using MySQL, by Yahoo Inc. in the Percona Performance Conference 2009. The Percona MySQL team provides it also as a Youtube video: Efficient Pagination Using MySQL (video),
The main problem happens with the usage of large OFFSET
s. They avoid using OFFSET
with a variety of techniques, ranging from id
range selections in the WHERE
clause, to some kind of caching or pre-computing pages.
There are suggested solutions at Use the INDEX, Luke:
mplcursors worked for me. mplcursors provides clickable annotation for matplotlib. It is heavily inspired from mpldatacursor (https://github.com/joferkington/mpldatacursor), with a much simplified API
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
data = np.outer(range(10), range(1, 5))
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
"Annotations can be dragged.")
mplcursors.cursor(lines) # or just mplcursors.cursor()
plt.show()
if you want to populate a table in SQL SERVER you can use while statement as follows:
declare @llenandoTabla INT = 0;
while @llenandoTabla < 10000
begin
insert into employeestable // Name of my table
(ID, FIRSTNAME, LASTNAME, GENDER, SALARY) // Parameters of my table
VALUES
(555, 'isaias', 'perez', 'male', '12220') //values
set @llenandoTabla = @llenandoTabla + 1;
end
Hope it helps.
Yes, there is a bool
data type (which inherits from int
and has only two values: True
and False
).
But also Python has the boolean-able
concept for every object, which is used when function bool([x])
is called.
See more: object.nonzero and boolean-value-of-objects-in-python.
I like the approach using list.files()
, lapply()
and list2env()
(or fs::dir_ls()
, purrr::map()
and list2env()
). That seems simple and flexible.
Alternatively, you may try the small package {tor} (to-R): By default it imports files from the working directory into a list (list_*()
variants) or into the global environment (load_*()
variants).
For example, here I read all the .csv files from my working directory into a list using tor::list_csv()
:
library(tor)
dir()
#> [1] "_pkgdown.yml" "cran-comments.md" "csv1.csv"
#> [4] "csv2.csv" "datasets" "DESCRIPTION"
#> [7] "docs" "inst" "LICENSE.md"
#> [10] "man" "NAMESPACE" "NEWS.md"
#> [13] "R" "README.md" "README.Rmd"
#> [16] "tests" "tmp.R" "tor.Rproj"
list_csv()
#> $csv1
#> x
#> 1 1
#> 2 2
#>
#> $csv2
#> y
#> 1 a
#> 2 b
And now I load those files into my global environment with tor::load_csv()
:
# The working directory contains .csv files
dir()
#> [1] "_pkgdown.yml" "cran-comments.md" "CRAN-RELEASE"
#> [4] "csv1.csv" "csv2.csv" "datasets"
#> [7] "DESCRIPTION" "docs" "inst"
#> [10] "LICENSE.md" "man" "NAMESPACE"
#> [13] "NEWS.md" "R" "README.md"
#> [16] "README.Rmd" "tests" "tmp.R"
#> [19] "tor.Rproj"
load_csv()
# Each file is now available as a dataframe in the global environment
csv1
#> x
#> 1 1
#> 2 2
csv2
#> y
#> 1 a
#> 2 b
Should you need to read specific files, you can match their file-path with regexp
, ignore.case
and invert
.
For even more flexibility use list_any()
. It allows you to supply the reader function via the argument .f
.
(path_csv <- tor_example("csv"))
#> [1] "C:/Users/LeporeM/Documents/R/R-3.5.2/library/tor/extdata/csv"
dir(path_csv)
#> [1] "file1.csv" "file2.csv"
list_any(path_csv, read.csv)
#> $file1
#> x
#> 1 1
#> 2 2
#>
#> $file2
#> y
#> 1 a
#> 2 b
Pass additional arguments via ... or inside the lambda function.
path_csv %>%
list_any(readr::read_csv, skip = 1)
#> Parsed with column specification:
#> cols(
#> `1` = col_double()
#> )
#> Parsed with column specification:
#> cols(
#> a = col_character()
#> )
#> $file1
#> # A tibble: 1 x 1
#> `1`
#> <dbl>
#> 1 2
#>
#> $file2
#> # A tibble: 1 x 1
#> a
#> <chr>
#> 1 b
path_csv %>%
list_any(~read.csv(., stringsAsFactors = FALSE)) %>%
map(as_tibble)
#> $file1
#> # A tibble: 2 x 1
#> x
#> <int>
#> 1 1
#> 2 2
#>
#> $file2
#> # A tibble: 2 x 1
#> y
#> <chr>
#> 1 a
#> 2 b
A popular Linux library which has similar functionality would be ncurses.
I know that it's posible to pass references of pointers, I did it last week, but I can't remember what the syntax was, as your code looks correct to my brain right now. However another option is to use pointers of pointers:
Myfunc(String** s)
In a View, in my case a SurfaceView subclass, you can set the screen on always on. I wanted the screen to stay on while this view was still drawing stuff.
public class MyCoolSurfaceView extends SurfaceView {
@Override
protected void onAttachedToWindow (){
super.onAttachedToWindow();
this.setKeepScreenOn(true);
}
@Override
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
this.setKeepScreenOn(false);
}
You delete first from the database and then you update your datagridview
:
//let's suppose delete(id) is a method which will delete a row from the database and
// returns true when it is done
int id = 0;
//we suppose that the first column in the datagridview is the ID of the ROW :
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
id = Convert.ToInt32(row.Cells[0].Value.ToString());
if(delete(id))
this.dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//else show message error!
<div class="leads-search-table">
<div class="row col-md-6 col-md-offset-2 custyle">
<table class="table custab bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Parent ID</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>News</td>
<td>News Cate</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
<tr>
<td>2</td>
<td>Products</td>
<td>Main Products</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
<tr>
<td>3</td>
<td>Blogs</td>
<td>Parent Blogs</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
</table>
</div>
</div>
Css
.custab{
border: 1px solid #ccc;
margin: 5% 0;
transition: 0.5s;
background-color: #fff;
-webkit-border-radius:4px;
border-radius: 4px;
border-collapse: separate;
}
I added the com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.6.1
dependency and started to get the date in the following format:
"birthDate": [
2016,
1,
25,
21,
34,
55
]
which is not what I wanted but I was getting closer. I then added the following
spring.jackson.serialization.write_dates_as_timestamps=false
to application.properties file which gave me the correct format that I needed.
"birthDate": "2016-01-25T21:34:55"
According to Pure CSS Scrollable Table with Fixed Header , I wrote a DEMO to easily fix the header by setting overflow:auto
to the tbody.
table thead tr{
display:block;
}
table th,table td{
width:100px;//fixed width
}
table tbody{
display:block;
height:200px;
overflow:auto;//set tbody to auto
}
Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.
In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.
Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip
Then import it into Eclipse.
If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip
call process1
call process2
in this case the process2 will not begin until process1 have finished.
In iTerm -> Preferences -> Profiles Tab -> General section set Command to: /bin/zsh --login
The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:
sudo chmod 777 file.jpeg
and then you can access if the above mentioned problems are not your case.
I came up with an alternative that actually hides sections and doesn't delete them. I tried @henning77's approach, but I kept running into problems when I changed the number of sections of the static UITableView. This method has worked really well for me, but I'm primarily trying to hide sections instead of rows. I am removing some rows on the fly successfully, but it is a lot messier, so I've tried to group things into sections that I need to show or hide. Here is an example of how I'm hiding sections:
First I declare a NSMutableArray property
@property (nonatomic, strong) NSMutableArray *hiddenSections;
In the viewDidLoad (or after you have queried your data) you can add sections you want to hide to the array.
- (void)viewDidLoad
{
hiddenSections = [NSMutableArray new];
if(some piece of data is empty){
// Add index of section that should be hidden
[self.hiddenSections addObject:[NSNumber numberWithInt:1]];
}
... add as many sections to the array as needed
[self.tableView reloadData];
}
Then implement the following the TableView delegate methods
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
return nil;
}
return [super tableView:tableView titleForHeaderInSection:section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
return 0;
}
return [super tableView:tableView heightForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
[cell setHidden:YES];
}
}
Then set the header and footer height to 1 for hidden sections because you can't set the height to 0. This causes an additional 2 pixel space, but we can make up for it by adjusting the height of the next visible header.
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
CGFloat height = [super tableView:tableView heightForHeaderInSection:section];
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
height = 1; // Can't be zero
}
else if([self tableView:tableView titleForHeaderInSection:section] == nil){ // Only adjust if title is nil
// Adjust height for previous hidden sections
CGFloat adjust = 0;
for(int i = (section - 1); i >= 0; i--){
if([self.hiddenSections containsObject:[NSNumber numberWithInt:i]]){
adjust = adjust + 2;
}
else {
break;
}
}
if(adjust > 0)
{
if(height == -1){
height = self.tableView.sectionHeaderHeight;
}
height = height - adjust;
if(height < 1){
height = 1;
}
}
}
return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
return 1;
}
return [super tableView:tableView heightForFooterInSection:section];
}
Then, if you do have specific rows to hide you can adjust the numberOfRowsInSection and which rows are returned in cellForRowAtIndexPath. In this example here I have a section that has three rows where any three could be empty and need to be removed.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = [super tableView:tableView numberOfRowsInSection:section];
if(self.organization != nil){
if(section == 5){ // Contact
if([self.organization objectForKey:@"Phone"] == [NSNull null]){
rows--;
}
if([self.organization objectForKey:@"Email"] == [NSNull null]){
rows--;
}
if([self.organization objectForKey:@"City"] == [NSNull null]){
rows--;
}
}
}
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [super tableView:tableView cellForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}
Use this offsetIndexPath to calculate the indexPath for rows where you are conditionally removing rows. Not needed if you are only hiding sections
- (NSIndexPath *)offsetIndexPath:(NSIndexPath*)indexPath
{
int row = indexPath.row;
if(self.organization != nil){
if(indexPath.section == 5){
// Adjust row to return based on which rows before are hidden
if(indexPath.row == 0 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Email"] != [NSNull null]){
row++;
}
else if(indexPath.row == 0 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Address"] != [NSNull null]){
row = row + 2;
}
else if(indexPath.row == 1 && [self.organization objectForKey:@"Phone"] != [NSNull null] && [self.organization objectForKey:@"Email"] == [NSNull null]){
row++;
}
else if(indexPath.row == 1 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Email"] != [NSNull null]){
row++;
}
}
}
NSIndexPath *offsetPath = [NSIndexPath indexPathForRow:row inSection:indexPath.section];
return offsetPath;
}
There are a lot of methods to override, but what I like about this approach is that it is re-usable. Setup the hiddenSections array, add to it, and it will hide the correct sections. Hiding the rows it a little trickier, but possible. We can't just set the height of the rows we want to hide to 0 if we're using a grouped UITableView because the borders will not get drawn correctly.
Export a certificate from a keystore:
keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
I have used sub-query and it worked great!
SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories
Below is how the same issue I faced got resolved. Most of the steps I took to solve the issues are already described in the solutions provided earlier by others.
There are two ways to start Jupyter Notebook application
There are different ways to configure Jupyter Notebook application to save the notebooks in a folder other than the default.
If using Anaconda Navigator to launch notebook
In case of using the Anaconda navigator to launch Jupyter notebook application, the way to configure is to un-comment the "c.NotebookApp.notebook_dir" field in "jupyter_notebook_config.py" and add the path. After updating the field looks like: c.NotebookApp.notebook_dir = <Enter the absolute path here>
In case of Windows and when Anaconda is installed for a particular user, this file is located in C:\Users\<USERNAME>.jupyter.
If you don;t find ".jupyter" folder then do the below steps to create it
If using the shortcut (name: Jupyter Notebook) to Jupyter Notebook application to launch it
If you examine the command in the target box of this shortcut, you will notice that Notebook app is started by executing the file "C:\Users\<USERNAME>\Anaconda3\Scripts\ jupyter-notebook-script.py" which accepts a path parameter.
The basic approach to define the location where the notebook files will be saved is --> to provide the path of the required folder when starting the Jupyter Notebook application. This can be done in two ways:
Follow the below steps: (Note: Replace the text in angle brackets with the actual text)
Replace "%USERPROFILE%" with
a. Either: the environment variable created to point to the folder where you want to store the notebook files. The command will look like: C:\Users\<USERNAME>\Anaconda3\Scripts\jupyter-notebook-script.py %<ENVIRONMENTVARIABLE>%
b. OR: the absolute path to the work folder you want the notebook files to be stored in. The command will look like: C:\Users\<USERNAME>\Anaconda3\Scripts\jupyter-notebook-script.py <F://folder//subfolder>
Replace the text (path) in "Start In" box with:
a. Either: the environment variable created to point to the folder where you want to store the notebook files. The text in "Start In" box will look like: %<ENVIRONMENTVARIABLE>%
b. OR: the absolute path to the work folder you want the notebook files to be stored in. The text in "Start In" box will look like: <F://folder//subfolder>
Note 1: If there are spaces in the path then the whole path should be enclosed in double quotes.
Note 2: The paths in this solution apply to the situation when Anaconda 3 (and Jupyter 3) is installed on Windows for a particular user (not for all users).
I personally preferred to define environment variable rather than hard coding the path in the shortcut.
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
There is no need to install Poppler on your OS. This will work:
pip install Wand
from wand.image import Image
f = "somefile.pdf"
with(Image(filename=f, resolution=120)) as source:
for i, image in enumerate(source.sequence):
newfilename = f[:-4] + str(i + 1) + '.jpeg'
Image(image).save(filename=newfilename)
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
Apache Thrift is a cross-language RPC option developed at Facebook. Works over sockets, function signatures are defined in text files in a language-independent way.
In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to
Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).
In other words: Whenever the interpreter encounters the sequence <space>
_
<line terminator>
, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.
To break the statement in your question into several lines you could do the following:
U_matrix(i, j, n + 1) = _
k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))
(Leading whitespaces are ignored.)
I had this issue when I manually pasted google-play-services_lib into my project. Obviously, play-services didn't have a build.gradle file in it. The solution, I learned, is to put this dependency in my project's build.gradle (instead of hard-copying the play-services directory):
compile 'com.google.android.gms:play-services:4.0.+'
A .o object file file (also .obj on Windows) contains compiled object code (that is, machine code produced by your C or C++ compiler), together with the names of the functions and other objects the file contains. Object files are processed by the linker to produce the final executable. If your build process has not produced these files, there is probably something wrong with your makefile/project files.
Its very simple. Just give the below command for listing all keyspaces.
Cqlsh> Describe keyspaces;
If you want to check the keyspace in the system schema using the SQL query
below is the command.
SELECT * FROM system_schema.keyspaces;
Hope this will answer your question...
You can go through the explanation on understanding and creating the keyspaces from below resources.
Documentation:
https://docs.datastax.com/en/cql/3.1/cql/cql_reference/create_keyspace_r.html https://www.i2tutorials.com/cassandra-tutorial/cassandra-create-keyspace/
You can use:
echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php
The short tag "< ?=" can be helpful too:
echo '<?= function_exists("foo") ? "yes" : "no";' | php
echo '<?= 8+7+9 ;' | php
The closing tag "?>" is optional, but don't forget the final ";"!
Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js
He shims the event in the emitChange
emitChange: function(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
I'm using a similar approach successfully
It's probably to late but i think this code work...
$blocks.each(function(i, elm) {
$(elm).fadeOut(200, function() {
$(elm).remove();
});
}).promise().done( function(){ alert("All was done"); } );
In C programming language, \
is used to print some of the special characters which has sepcial meaning in C. Those special characters are listed below
\\ - Backslash
\' - Single Quotation Mark
\" - Double Quatation Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell(beep) sound
To see which ports are available on your machine run:
C:> netstat -an |find /i "listening"
You do not need to limit your compiler to only armv7 and armv7s by removing arm64 setting from supported architectures. You just need to set Deployment target setting to 5.1.1
Important note: you cannot set Deployment target to 5.1.1 in Build Settings section because it is drop-down only with fixed values. But you can easily set it to 5.1.1 in General section of application settings by just typing the value in text field.
All About margins
this works in Android, but did not test it in ios
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { View, Platform } from 'react-native'
import EStyleSheet from 'react-native-extended-stylesheet'
const styles = EStyleSheet.create({
wrapper: {
margin: '-1.4rem'
},
shadow: {
padding: '1.4rem',
margin: '1.4rem',
borderRadius: 4,
borderWidth: 0,
borderColor: 'transparent',
...Platform.select({
ios: {
shadowColor: 'rgba(0,0,0, 0.4)',
shadowOffset: { height: 1, width: 1 },
shadowOpacity: 0.7,
shadowRadius: '1.4rem'
},
android: {
elevation: '1.4rem'
}
})
},
container: {
padding: 10,
margin: '-1.4rem',
borderRadius: 4,
borderWidth: 0,
borderColor: '#Fff',
backgroundColor: '#fff'
}
})
class ShadowWrapper extends PureComponent {
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.node,
PropTypes.arrayOf(PropTypes.element)
]).isRequired
}
render () {
return (
View style={styles.wrapper}
View style={styles.shadow}
View style={styles.container}
{this.props.children}
View
View
View
)
}
}
export default ShadowWrapper
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
This I have found on the internet.
Symfony doc to get request data
Finally, the raw data sent with the request body can be accessed using getContent():
$content = $request->getContent();
Expanding on user187291's post, you could also use getters/setters to get around having to use functions.
var x = 1;
var ref = {
get x() { return x; },
set x(v) { x = v; }
};
(ref.x)++;
console.log(x); // prints '2'
x--;
console.log(ref.x); // prints '1'
This was too long for a comment on Nico's answer, which I don't think works on Firefox any more (per the comments), and didn't work for me on Safari as is.
Firstly, you now appear to be able to read directly from the clipboard. Rather than code like:
if (/text\/plain/.test(e.clipboardData.types)) {
// shouldn't this be writing to elem.value for text/plain anyway?
elem.innerHTML = e.clipboardData.getData('text/plain');
}
use:
types = e.clipboardData.types;
if (((types instanceof DOMStringList) && types.contains("text/plain")) ||
(/text\/plain/.test(types))) {
// shouldn't this be writing to elem.value for text/plain anyway?
elem.innerHTML = e.clipboardData.getData('text/plain');
}
because Firefox has a types
field which is a DOMStringList
which does not implement test
.
Next Firefox will not allow paste unless the focus is in a contenteditable=true
field.
Finally, Firefox will not allow paste reliably unless the focus is in a textarea
(or perhaps input) which is not only contenteditable=true
but also:
display:none
visibility:hidden
I was trying to hide the text field so I could make paste work over a JS VNC emulator (i.e. it was going to a remote client and there was no actually textarea
etc to paste into). I found trying to hide the text field in the above gave symptoms where it worked sometimes, but typically failed on the second paste (or when the field was cleared to prevent pasting the same data twice) as the field lost focus and would not properly regain it despite focus()
. The solution I came up with was to put it at z-order: -1000
, make it display:none
, make it as 1px by 1px, and set all the colours to transparent. Yuck.
On Safari, you the second part of the above applies, i.e. you need to have a textarea
which is not display:none
.
There is a substring function in XSLT. Example here.
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");
}
}
}
You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.
TextEdittingController _controller = new TextEdittingController(text: "your Text");
or
@override
void initState() {
super.initState();
_Controller.text = "Your Text";
}
In mysql server 8.0, on Windows, the location is C:\ProgramData\MySQL\MySQL Server 8.0\Data
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(4)
This method return April
If you need some special language, you can add:
<system.web>
<globalization culture="es-ES" uiCulture="es-ES"></globalization>
<compilation debug="true"
</system.web>
Or your preferred language.
For example, with es-ES
culture:
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(4)
Returns: Abril
Returns: Abril
(in spanish, because, we configured the culture as es-ES
in our webconfig
file, else, you will get April
)
That should work.
document.body.onload
is a cross-browser, but a legacy mechanism that only allows a single callback (you cannot assign multiple functions to it).
The closest "standard" alternative, addEventListener
is not supported by Internet Explorer (it uses attachEvent
), so you will likely want to use a library (jQuery, MooTools, prototype.js, etc.) to abstract the cross-browser ugliness for you.
If you want to do it in code, use the System.Web.HttpCookie.HttpOnly property.
This is directly from the MSDN docs:
// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
Response.AppendCookie(myHttpCookie);
// Show the name of the cookie.
Response.Write(myHttpCookie.Name);
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
Response.AppendCookie(myHttpOnlyCookie);
// Show the name of the HttpOnly cookie.
Response.Write(myHttpOnlyCookie.Name);
Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.
I use an Eclipse plugin (in Eclipse Marketplace) https://marketplace.eclipse.org/content/fontsize
You can use simply pd.to_datetime(then)
and pandas will convert the date elements into ISO date format- [YYYY-MM-DD]
.
You can pass this as map/apply to use it in a dataframe/series too.
It totally depends upon which implementation you have used, whether arraylist linkedlist, or other implementations of set.
if it is set then you can directly get the first element , their can be trick loop over the collection , create a variable of value 1 and get value when flag value is 1 after that break that loop.
if it is list's implementation then it is easy by defining index number.
It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.
In general, I suggest calling a function on ng-click like so:
<a ng-click="navigateToPath()">click me</a>
obj.val1
& obj.val2
should be available on your controller's $scope, you dont need to pass those into a function from the markup.
then, in your controller:
$scope.navigateToPath = function(){
var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
$location.path(path)
}
Add below to pre-build event command line:
echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt"
Add this file as resource, now you have 'BuildDate' string in your resources.
To create resources, see How to create and use resources in .NET.
This traverse
generator function can be used to iterate over all the values:
def traverse(o, tree_types=(list, tuple)):
if isinstance(o, tree_types):
for value in o:
for subvalue in traverse(value, tree_types):
yield subvalue
else:
yield o
data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']
for value in traverse(data):
print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'
Late to the game.. and there are several great answers above-- essentially, that the compileSdkVersion
is the version of the API the app is compiled against, while the targetSdkVersion
indicates the version that the app was tested against.
I'd like to supplement those answers with the following notes:
targetSdkVersion
is 23 or higher, the app requests permissions from the user at run-time.targetSdkVersion
is 22 or lower, the system asks the user to grant the permissions when the user installs the app.If the compileSdkVersion
is higher than the version declared by your app's targetSdkVersion
, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect. (ref)
With each new Android release...
targetSdkVersion
should be incremented to match the latest API level, then thoroughly test your application on the corresponding platform versioncompileSdkVersion
, on the other hand, does not need to be changed unless you're adding features exclusive to the new platform versiontargetSdkVersion
is often (initially) less than than the compileSdkVersion
, it's not uncommon to see a well-maintained/established app with targetSdkVersion > compileSdkVersion
When you run a program in python, the interpreter compiles it to bytecode first (this is an oversimplification) and stores it in the __pycache__
folder. If you look in there you will find a bunch of files sharing the names of the .py files in your project's folder, only their extensions will be either .pyc or .pyo. These are bytecode-compiled and optimized bytecode-compiled versions of your program's files, respectively.
As a programmer, you can largely just ignore it... All it does is make your program start a little faster. When your scripts change, they will be recompiled, and if you delete the files or the whole folder and run your program again, they will reappear (unless you specifically suppress that behavior).
When you're sending your code to other people, the common practice is to delete that folder, but it doesn't really matter whether you do or don't. When you're using version control (git
), this folder is typically listed in the ignore file (.gitignore
) and thus not included.
If you are using cpython (which is the most common, as it's the reference implementation) and you don't want that folder, then you can suppress it by starting the interpreter with the -B flag, for example
python -B foo.py
Another option, as noted by tcaswell, is to set the environment variable PYTHONDONTWRITEBYTECODE
to any value (according to python's man page, any "non-empty string").
There is a parse_dates
parameter for read_csv
which allows you to define the names of the columns you want treated as dates or datetimes:
date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)