The following is a very straightforward method in Python 3.x
a = [1,2,3,4,5,1,2,3,4,5,1] #Replacing every 1 with 10
for i in range(len(a)):
if a[i] == 1:
a[i] = 10
print(a)
This method works. Comments are welcome. Hope it helps :)
Also try understanding how outis's and damzam's solutions work. List compressions and lambda function are useful tools.
Simple solution with ES6 'reduce' and 'find' array helper methods
Works efficiently and perfectly fine!
"use strict";
var things = new Object();
things.thing = new Array();
things.thing.push({
place: "here",
name: "stuff"
});
things.thing.push({
place: "there",
name: "morestuff"
});
things.thing.push({
place: "there",
name: "morestuff"
});
// the logic is here
function removeDup(something) {
return something.thing.reduce(function (prev, ele) {
var found = prev.find(function (fele) {
return ele.place === fele.place && ele.name === fele.name;
});
if (!found) {
prev.push(ele);
}
return prev;
}, []);
}
console.log(removeDup(things));
Check this link
and import these clases UIImage+animatedGIF.h,UIImage+animatedGIF.m
Use this code
NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"dots64" withExtension:@"gif"];
NSString *path=[[NSBundle mainBundle]pathForResource:@"bar180" ofType:@"gif"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
imageVw.image= [UIImage animatedImageWithAnimatedGIFURL:url];
Hope this is helpfull
For those who want single command SQL query for that:
INSERT INTO TABLE002
(COL001_MEM_ID, COL002_MEM_NAME, COL002_MEM_ADD, COL002_CREATE_USER_C, COL002_CREATE_S)
SELECT COL001_MEM_ID, COL001_MEM_NAME, COL001_MEM_ADD, COL001_CREATE_USER_C, COL001_CREATE_S
FROM TABLE001;
This query will copy data from TABLE001
to TABLE002
and we assume that both columns had different column names.
Column names are mapped one-to-one like:
COL001_MEM_ID -> COL001_MEM_ID
COL001_MEM_NAME -> COL002_MEM_NAME
COL001_MEM_ADD -> COL002_MEM_ADD
COL001_CREATE_USER_C -> COL002_CREATE_USER_C
COL002_CREATE_S -> COL002_CREATE_S
You can also specify where clause, if you need some condition.
it may caused by Property which is not populated by model.. instead it is populated by Controller.. which may cause this error.. solution to this is assign the property before applying ModelState validation. and this second Assumption is . you may have already have Data in your Database and trying to update it it but now fetching it.
I believe there is no "out of the box" solution, that's a limitation of the Directory.GetFiles method.
It's fairly easy to write your own method though, here is an example.
The code could be:
/// <summary> /// Returns file names from given folder that comply to given filters /// </summary> /// <param name="SourceFolder">Folder with files to retrieve</param> /// <param name="Filter">Multiple file filters separated by | character</param> /// <param name="searchOption">File.IO.SearchOption, /// could be AllDirectories or TopDirectoryOnly</param> /// <returns>Array of FileInfo objects that presents collection of file names that /// meet given filter</returns> public string[] getFiles(string SourceFolder, string Filter, System.IO.SearchOption searchOption) { // ArrayList will hold all file names ArrayList alFiles = new ArrayList(); // Create an array of filter string string[] MultipleFilters = Filter.Split('|'); // for each filter find mathing file names foreach (string FileFilter in MultipleFilters) { // add found file names to array list alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption)); } // returns string array of relevant file names return (string[])alFiles.ToArray(typeof(string)); }
IN="[email protected];[email protected]"
IFS=';'
read -a IN_arr <<< "${IN}"
for entry in "${IN_arr[@]}"
do
echo $entry
done
Output
[email protected]
[email protected]
System : Ubuntu 12.04.1
Either something like this:
"abc" + str(9)
or
"abs{0}".format(9)
or
"abs%d" % (9,)
To rotate by 45 degrees in IE, you need the following code in your stylesheet:
filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476); /* IE6,IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; /* IE8 */
You’ll note from the above that IE8 has different syntax to IE6/7. You need to supply both lines of code if you want to support all versions of IE.
The horrible numbers there are in Radians; you’ll need to work out the figures for yourself if you want to use an angle other than 45 degrees (there are tutorials on the internet if you look for them).
Also note that the IE6/7 syntax causes problems for other browsers due to the unescaped colon symbol in the filter string, meaning that it is invalid CSS. In my tests, this causes Firefox to ignore all CSS code after the filter. This is something you need to be aware of as it can cause hours of confusion if you get caught out by it. I solved this by having the IE-specific stuff in a separate stylesheet which other browsers didn’t load.
All other current browsers (including IE9 and IE10 — yay!) support the CSS3 transform
style (albeit often with vendor prefixes), so you can use the following code to achieve the same effect in all other browsers:
-moz-transform: rotate(45deg); /* FF3.5/3.6 */
-o-transform: rotate(45deg); /* Opera 10.5 */
-webkit-transform: rotate(45deg); /* Saf3.1+ */
transform: rotate(45deg); /* Newer browsers (incl IE9) */
Hope that helps.
Since this answer is still getting up-votes, I feel I should update it with information about a JavaScript library called CSS Sandpaper that allows you to use (near) standard CSS code for rotations even in older IE versions.
Once you’ve added CSS Sandpaper to your site, you should then be able to write the following CSS code for IE6–8:
-sand-transform: rotate(40deg);
Much easier than the traditional filter
style you'd normally need to use in IE.
Also note an additional quirk specifically with IE9 (and only IE9), which supports both the standard transform
and the old style IE -ms-filter
. If you have both of them specified, this can result in IE9 getting completely confused and rendering just a solid black box where the element would have been. The best solution to this is to avoid the filter
style by using the Sandpaper polyfill mentioned above.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Note that as of Microsoft SQL Server 2016, UTF-8 is supported by bcp
, BULK_INSERT
, and OPENROWSET
.
Addendum 2016-12-21: SQL Server 2016 SP1 now enables Unicode Compression (and most other previously Enterprise-only features) for all versions of MS SQL including Standard and Express. This is not the same as UTF-8 support, but it yields a similar benefit if the goal is disk space reduction for Western alphabets.
This is a variation to get all checked checkboxes in all_location_id
without using an "if" statement
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
The main difference between them you can find as follows:
HashSet
HashMap
It turns out, I was using the fetch
method incorrectly.
fetch
expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.
I was wrapping the intended object within a second object, which did not get me any desired result.
Here's how it looks on a high level:
fetch('API_ENDPOINT', OBJECT)
.then(function(res) {
return res.json();
})
.then(function(resJson) {
return resJson;
})
I structured my object as such:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Origin': '',
'Host': 'api.producthunt.com'
},
body: JSON.stringify({
'client_id': '(API KEY)',
'client_secret': '(API SECRET)',
'grant_type': 'client_credentials'
})
Also be advised, that while Java is in general very beginner friendly, getting into JavaEE, Servlets, Facelets, Eclipse integration, JSP and getting everything in Tomcat up and running is not. Certainly not the easiest way to build a website and probably way overkill for most things.
On top of that you may need to host your website yourself, because most webspace providers don't provide Servlet Containers. If you just want to check it out for fun, I would try Ruby or Python, which are much more cooler things to fiddle around with. But anyway, to provide at least something relevant to the question, here's a nice Servlet tutorial: link
If you are using a templateSelection and ajax, some of these other answers may not work. It seems that creating a new option
element and setting the value
and text
will not satisfy the template method when your data objects use other values than id and text.
Here is what worked for me:
$("#selectElem").select2({
ajax: { ... },
data: [YOUR_DEFAULT_OBJECT],
templateSelection: yourCustomTemplate
}
Check out the jsFiddle here: https://jsfiddle.net/shanabus/f8h1xnv4
In my case, I had to processResults
in since my data did not contain the required id
and text
fields. If you need to do this, you will also need to run your initial selection through the same function. Like so:
$(".js-select2").select2({
ajax: {
url: SOME_URL,
processResults: processData
},
data: processData([YOUR_INIT_OBJECT]).results,
minimumInputLength: 1,
templateSelection: myCustomTemplate
});
function processData(data) {
var mapdata = $.map(data, function (obj) {
obj.id = obj.Id;
obj.text = '[' + obj.Code + '] ' + obj.Description;
return obj;
});
return { results: mapdata };
}
function myCustomTemplate(item) {
return '<strong>' + item.Code + '</strong> - ' + item.Description;
}
Try this code
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}
pip
for installation of packages in Python 3Step 1: Install Python 3. Yes, by default an application file pip3.exe
is already located there in the path (E.g.
):
C:/Users/name/AppData/Local/Programs/Python/Python36-32/Scripts
Step 2: Go to
>Control Panel (Local Machine) > System > Advanced system settings >
>Click on `Environment Variables` >
Set a New User Variable, for this click `New` >
Write new 'Variable name' as "PYTHON_SCRIPTS" >
Copy that path of `pip3.exe` and paste within variable value > `OK` >
>Below again find out and click on `Path` under 'system variables' >
Edit this path >
Within 'Variable value' append and paste the same path of `pip3.exe` after putting a ';' >
Click `OK`/`Apply` and come out.
Step 3: Now, open cmd
bash/shell by Pressing key Windows+R
.
> Write 'pip3' and press 'Enter'. If pip3 is recognized you can go ahead.
Step 4: In this same cmd
> Write path of the `pip3.exe` followed by `/pip install 'package name'`
As Example just write:
C:/Users/name/AppData/Local/Programs/Python/Python36-32/Scripts/pip install matplotlib
Press Enter
now. The Package matplotlib
will start getting downloaded.
Further, for upgrading any package
Open cmd
bash/shell again, then
type that path of
pip3.exe
followed by/pip install --upgrade 'package name'
PressEnter
.
As Example just write:
C:/Users/name/AppData/Local/Programs/Python/Python36-32/Scripts/pip install --upgrade matplotlib
Upgrading of the package will start
:)
One solution is to use JavaScript to add the required CSS classes after the page is ready. For example, styling django form output with bootstrap classes (jQuery used for brevity):
<script type="text/javascript">
$(document).ready(function() {
$('#some_django_form_id').find("input[type='text'], select, textarea").each(function(index, element) {
$(element).addClass("form-control");
});
});
</script>
This avoids the ugliness of mixing styling specifics with your business logic.
The question is old, but it seems that there are people who have the same concerns.
What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?
The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed. So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.
As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80), In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.
self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)
extension is
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: alpha)
}
}
However, the actual view was
Calculating it,
So, I was able to match the colors similarly by setting the UIColor values ??to 17, 17, 17 and alpha 0.8.
self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)
Or can anyone tell me what I'm missing?
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
Have you seen FlexSlider from WooThemes? I've used it on several recent projects with great success. It's touch enabled too so it will work on both mouse-based browsers as well as touch-based browsers in iOS and Android.
it is php version the problem, had the same issue upgraded my php version to 5.6 solved the problem
For the example case above, it is usually omitted, yes. However, either way is syntactically correct.
Try this
div_x000D_
{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background:red;_x000D_
transition: all 1s ease-in-out;_x000D_
-webkit-transition: all 1s ease-in-out;_x000D_
-moz-transition: all 1s ease-in-out;_x000D_
-o-transition: all 1s ease-in-out;_x000D_
-ms-transition: all 1s ease-in-out;_x000D_
position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
transform: translate(3em,0);_x000D_
-webkit-transform: translate(3em,0);_x000D_
-moz-transform: translate(3em,0);_x000D_
-o-transform: translate(3em,0);_x000D_
-ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
Update - better version 18th July 2019.
Final summary, even though I've moved on to powershell for most windows console work anyway, but I decided to wrap this old cmd issue up, I had to get on a cmd console today, and the lack of this feature really struck me. This one finally works with spaces as well, where my previous answer would fail.
In addition, this one now is also able to use ~ as a prefix for other home sub-folders too, and it swaps forward-slashes to back-slashes as well. So here it is;
Step 1. Create these doskey macros, somewhere they get picked up every time cmd starts up.
DOSKEY cd=cdtilde.bat $*
DOSKEY cd~=chdir /D "%USERPROFILE%"
DOSKEY cd..=chdir ..
Step 2. Create the cdtilde.bat file and put it somewhere in your PATH
@echo off
set dirname=""
set dirname=%*
set orig_dirname=%*
:: remove quotes - will re-attach later.
set dirname=%dirname:\"=%
set dirname=%dirname:/"=%
set dirname=%dirname:"=%
:: restore dirnames that contained only "/"
if "%dirname%"=="" set dirname=%orig_dirname:"=%
:: strip trailing slash, if longer than 3
if defined dirname if NOT "%dirname:~3%"=="" (
if "%dirname:~-1%"=="\" set dirname="%dirname:~0,-1%"
if "%dirname:~-1%"=="/" set dirname="%dirname:~0,-1%"
)
set dirname=%dirname:"=%
:: if starts with ~, then replace ~ with userprofile path
if %dirname:~0,1%==~ (
set dirname="%USERPROFILE%%dirname:~1%"
)
set dirname=%dirname:"=%
:: replace forward-slashes with back-slashes
set dirname="%dirname:/=\%"
set dirname=%dirname:"=%
chdir /D "%dirname%"
Tested fine with;
cd ~ (traditional habit)
cd~ (shorthand version)
cd.. (shorthand for going up..)
cd / (eg, root of C:)
cd ~/.config (eg, the .config folder under my home folder)
cd /Program Files (eg, "C:\Program Files")
cd C:/Program Files (eg, "C:\Program Files")
cd \Program Files (eg, "C:\Program Files")
cd C:\Program Files (eg, "C:\Program Files")
cd "C:\Program Files (eg, "C:\Program Files")
cd "C:\Program Files" (eg, "C:\Program Files")
Oh, also it allows lazy quoting, which I found useful, even when spaces are in the folder path names, since it wraps all of the arguments as if it was one long string. Which means just an initial quote also works, or completely without quotes also works.
All other stuff below may be ignored now, it is left for historical reasons - so I dont make the same mistakes again
old update 19th Oct 2018.
In case anyone else tried my approach, my original answer below didn't handle spaces, eg, the following failed.
> cd "c:\Program Files"
Files""]==["~"] was unexpected at this time.
I think there must be a way to solve that. Will post again if I can improve my answer. (see above, I finally got it all working the way I wanted it to.)
My Original Answer, still needed work... 7th Oct 2018.
I was just trying to do it today, and I think I got it, this is what I think works well;
First, some doskey macros;
DOSKEY cd=cdtilde.bat $*
DOSKEY cd~=chdir /D "%USERPROFILE%"
DOSKEY cd..=chdir ..
and then then a bat file in my path;
cdtilde.bat
@echo off
if ["%1"]==["~"] (
chdir /D "%USERPROFILE%"
) else (
chdir /D %*
)
All these seem to work fine;
cd ~ (traditional habit)
cd~ (shorthand version)
cd.. (shorthand for going up..)
The short version is that you cannot use variable-width patterns in lookbehinds using Python's re
module. There is no way to change this:
>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
re.sub("(?<=fo+)bar(?=baz)", "quux", string)
File "C:\Development\Python25\lib\re.py", line 150, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "C:\Development\Python25\lib\re.py", line 241, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:
>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)
This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.
I don't think it's necessary to use semi-quotes around the variables, try:
curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"
%2f
is the escape code for a /
.
http://www.december.com/html/spec/esccodes.html
Also, do you need to specify a port? ( just checking :) )
Just use the following:
doublevalue+"";
This will work for any data type.
Example:
Double dd=10.09;
String ss=dd+"";
It's weird ... I've got the exact same error, coming from a different thing. When I create my controller I passed the $location parameter, like this :
App.controller('MessageController', function ($scope, $http, $log, $location, $attrs, MessageFactory, SocialMessageFactory) {
// controller code
});
This was proven to be a bug when we use third party libraries or pure JS to manipulate some specifics (here window.location) the next digest of angular will blow this error.
So I simply removed the $location from the controller creation parameter, and it worked again, without this error.
Or if you absolutely need to use the $location from angular, you have to remove every single <a href="#">link</a>
in the links of your template page, and rather write href="". Worked for me.
Hope it can help one day.
Without having selected a language type for your file there are no styles defined. Comment and block comment are language specific style preferences. If that's a PITA...
To select for multi-line editing you can use
shift
+ alt
+ down arrow
I was having a similar issue with a property being null or undefined.
This ended up being that IE's document mode was being defaulted to IE7 Standards. This was due to the compatibility mode being automatically set to be used for all intranet sites (Tools > Compatibility View Setting > Display Intranet Sites in Compatibility View).
Abramov's goal - and everyone's ideally - is simply to encapsulate complexity (and async calls) in the place where it's most appropriate.
Where's the best place to do that in the standard Redux dataflow? How about:
map HTTP request header Content-Type
, handle request body.
@RequestParam
? application/x-www-form-urlencoded
,
@RequestBody
? application/json
,
@RequestPart
? multipart/form-data
,
RequestParam (Spring Framework 5.1.9.RELEASE API)
map to query parameters, form data, and parts in multipart requests.
RequestParam
is likely to be used with name-value form fields
RequestBody (Spring Framework 5.1.9.RELEASE API)
bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the
content type
of the request. (e.g. JSON, XML)
RequestPart (Spring Framework 5.1.9.RELEASE API)
used to associate the part of a "
multipart/form-data
" request
RequestPart
is likely to be used with parts containing more complex content
HttpMessageConverter (Spring Framework 5.1.9.RELEASE API)
a converter that can convert from and to HTTP requests and responses.
All Known Implementing Classes: ..., AbstractJsonHttpMessageConverter, AbstractXmlHttpMessageConverter, ...
I found this advice:
There are a few steps to solve your problem:
First thing to do is Clear items from the Office Clipboard. If the Microsoft Office Clipboard is not displayed in the task pane, click Office Clipboard on the Edit menu. On the Office Clipboard task pane, do one of the following: To clear all items, click Clear All .
Next thing is to switch off the clipboard show option. To do this, what you can do is to again display the Clipboard menu (select Office Clipboard from Edit Menu). And in the selection button "Options" at the bottom of the screen, select this particular option: "Collect Without Showing Office Clipboard"
and now, you are relieved of the bug.
Hope this helps.
here. I have the problem, but it's sporadic. I just tried the technique, and I don't see the problem, but since it's sporadic I won't know for a while if it's gone for good.
it doenst work for me but it prints the correct element to the console
this is the code:
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
console.log(el); //print element to console
el.dispatchEvent(ev);
}
click(400, 400);
This is really similar to another question. How should I load files into my Java application?
How should I load my files into my Java Application?
You do not want to load your files in by:
C:\your\project\file.txt
this is bad!
You should use getResourceAsStream.
InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);
And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.
I think this is the syntax you are looking for:
if [ -z != $errorstatus ]
then
commands
else
commands
fi
Why not use padding with negative margins? Something like this:
<div class="parent">
<div class="child1">
</div>
<div class="child2">
</div>
</div>
And then
.parent {
padding-top: 1em;
}
.child1 {
margin-top: -1em;
height: 1em;
}
.child2 {
margin-top: 0;
height: 100%;
}
You may try
document.getElementById('name').style.borderColor='#e52213';
document.getElementById('name').style.border='solid';
There is a gem called active_record_union that might be what you are looking for.
It's example usages is the following:
current_user.posts.union(Post.published)
current_user.posts.union(Post.published).where(id: [6, 7])
current_user.posts.union("published_at < ?", Time.now)
user_1.posts.union(user_2.posts).union(Post.published)
user_1.posts.union_all(user_2.posts)
Byte[] -> String: use system.convert.tobase64string
Convert.ToBase64String(byte[] data)
String -> Byte[]: use system.convert.frombase64string
Convert.FromBase64String(string data)
You can get the version of the jquery by simply printing object.jquery
, the object
can be any object created by you using $
.
For example: if you have created a <div>
element as following
var divObj = $("div");
then by printing divObj.jquery
will show you the version like 1.7.1
Basically divObj
inherits all the property of $()
or jQuery()
i.e if you try to print jQuery.fn.jquery
will also print the same version like 1.7.1
Using nargs parameter in argparse's add_argument method
I use nargs='*'
as an add_argument parameter. I specifically used nargs='*'
to the option to pick defaults if I am not passing any explicit arguments
Including a code snippet as example:
Example: temp_args1.py
Please Note: The below sample code is written in python3. By changing the print statement format, can run in python2
#!/usr/local/bin/python3.6
from argparse import ArgumentParser
description = 'testing for passing multiple arguments and to get list of args'
parser = ArgumentParser(description=description)
parser.add_argument('-i', '--item', action='store', dest='alist',
type=str, nargs='*', default=['item1', 'item2', 'item3'],
help="Examples: -i item1 item2, -i item3")
opts = parser.parse_args()
print("List of items: {}".format(opts.alist))
Note: I am collecting multiple string arguments that gets stored in the list - opts.alist
If you want list of integers, change the type parameter on parser.add_argument
to int
Execution Result:
python3.6 temp_agrs1.py -i item5 item6 item7
List of items: ['item5', 'item6', 'item7']
python3.6 temp_agrs1.py -i item10
List of items: ['item10']
python3.6 temp_agrs1.py
List of items: ['item1', 'item2', 'item3']
this will also work
data.groupby(data['date'].dt.year)
that the OpenSSL extension enabled and the directory languages with "br"? first checks the data.
This method should handle filenames which have any number/combination of spaces in them...
svn status /home/websites/website1 | grep -Z "^?" | sed s/^?// | sed s/[[:space:]]*// | xargs -i svn add \"{}\"
Here is an explanation of what that command does:
Use the -i argument to xargs to handle being able to import files names with spaces into 'svn add' - basically, -i sets {} to be used as a placeholder so we can put the " characters around the filename used by 'svn add'.
An advantage of this method is that this should handle filenames with spaces in them.
You'll need to decide how you'd like to handle exceptions thrown by the encrypt
method.
Currently, encrypt
is declared with throws Exception
- however, in the body of the method, exceptions are caught in a try/catch block. I recommend you either:
throws Exception
clause from encrypt
and handle exceptions internally (consider writing a log message at the very least); or,encrypt
, and surround the call to encrypt
with a try/catch instead (i.e. in actionPerformed
).Regarding the compilation error you refer to: if an exception was thrown in the try
block of encrypt
, nothing gets returned after the catch
block finishes. You could address this by initially declaring the return value as null
:
public static byte[] encrypt(String toEncrypt) throws Exception{
byte[] encrypted = null;
try {
// ...
encrypted = ...
}
catch(Exception e){
// ...
}
return encrypted;
}
However, if you can correct the bigger issue (the exception-handling strategy), this problem will take care of itself - particularly if you choose the second option I've suggested.
Have come across such issue. The root cause is the .m2 folder. You gotta make sure that whatever you're trying to access is present there in your .m2 folder (this is your local repo). If the stuff is there then you're good. This is usually present inside of users folder on your system (be it mac/linux or even windows)
add name attribute to your md-input. if it doesn't solve the problem, please post your template
Just add this line :
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16
iOS8 requires these images
Just ignore everything but digits.
Here is what I use:
// USA phones should contain at least 10 digits. For Ukrainian phones it's OK to have only 9 digits, without leading 0 and country code prefix: [+380] 88 888-88-88.
String.prototype.isValidPhone = function(digitsCount) {
var str = this.trim().match(/\d/g);
return str && str.length >= (digitsCount || 10); // default is at least 10 digits
}
You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the dot()
function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.
Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @
infix-operator for matrix multiplication, thanks to pep 465.
Edit: Regarding your comment:
Yes. The whole of numpy is based on arrays.
Yes. linalg.norm(v)
is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.
To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.
An example in ipython:
In [1]: import math
In [2]: import numpy as np
In [3]: a = np.array([4,2,7])
In [4]: np.linalg.norm(a)
Out[4]: 8.3066238629180749
In [5]: math.sqrt(sum([n**2 for n in a]))
Out[5]: 8.306623862918075
In [6]: b = a/np.linalg.norm(a)
In [7]: np.linalg.norm(b)
Out[7]: 1.0
Note that In [5]
is an alternative way to calculate the length. In [6]
shows normalizing the vector.
Simply like this:
ALTER TABLE tablename AUTO_INCREMENT = value;
reference: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
You can create your own conversion function:
static long ToLong(string lNumber)
{
if (string.IsNullOrEmpty(lNumber))
throw new Exception("Not a number!");
char[] chars = lNumber.ToCharArray();
long result = 0;
bool isNegative = lNumber[0] == '-';
if (isNegative && lNumber.Length == 1)
throw new Exception("- Is not a number!");
for (int i = (isNegative ? 1:0); i < lNumber.Length; i++)
{
if (!Char.IsDigit(chars[i]))
{
if (chars[i] == '.' && i < lNumber.Length - 1 && Char.IsDigit(chars[i+1]))
{
var firstDigit = chars[i + 1] - 48;
return (isNegative ? -1L:1L) * (result + ((firstDigit < 5) ? 0L : 1L));
}
throw new InvalidCastException($" {lNumber} is not a valid number!");
}
result = result * 10 + ((long)chars[i] - 48L);
}
return (isNegative ? -1L:1L) * result;
}
It can be improved further:
x is the target angle. y is the source or starting angle:
atan2(sin(x-y), cos(x-y))
It returns the signed delta angle. Note that depending on your API the order of the parameters for the atan2() function might be different.
Persist should be called only on new entities, while merge
is meant to reattach detached entities.
If you're using the assigned generator, using merge
instead of persist
can cause a redundant SQL statement.
Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
You forgot to return the map. this code will resolve the issue.
The below only works if the iframe content is from the same parent domain.
The following jquery script works for me. Tested on Chrome and IE8. The inner iframe references a page that is on the same domain as the parent page.
In this particular case, I am hiding an element with a specific class in the inner iframe.
Basically, you just append a style
element to the head section of the document loaded in a frame:
frame.addEventListener("load", ev =>
const new_style_element = document.createElement("style");
new_style_element.textContent = ".my-class { display: none; }"
ev.target.contentDocument.head.appendChild(new_style_element);
});
You can also instead of style
use a link
element, for referencing a stylesheet resource.
This is a procedure to configure run release version
1- Change build variants to release version.
Collections.addAll provides the shortest (one-line) receipt
Having
String[] array = {"foo", "bar", "baz"};
Set<String> set = new HashSet<>();
You can do as below
Collections.addAll(set, array);
mute=1
or muted=1
as suggested by @Fab will work. However, if you wish to enable autoplay with sound you should add allow="autoplay"
to your embedded <iframe>
.
<iframe type="text/html" src="https://www.youtube.com/embed/-ePDPGXkvlw?autoplay=1" frameborder="0" allow="autoplay"></iframe>
This is officially supported and documented in Google's Autoplay Policy Changes 2017 post
Iframe delegation A feature policy allows developers to selectively enable and disable use of various browser features and APIs. Once an origin has received autoplay permission, it can delegate that permission to cross-origin iframes with a new feature policy for autoplay. Note that autoplay is allowed by default on same-origin iframes.
<!-- Autoplay is allowed. --> <iframe src="https://cross-origin.com/myvideo.html" allow="autoplay"> <!-- Autoplay and Fullscreen are allowed. --> <iframe src="https://cross-origin.com/myvideo.html" allow="autoplay; fullscreen">
When the feature policy for autoplay is disabled, calls to play() without a user gesture will reject the promise with a NotAllowedError DOMException. And the autoplay attribute will also be ignored.
As mentioned before you can not mock static methods with mockito.
If changing your testing framework is not an option you can do the following:
Create an interface for DriverManager, mock this interface, inject it via some kind of dependency injection and verify on that mock.
Well, my solution is sort of hack, but it works and I am using it.
1vw = 1% of viewport width
1vh = 1% of viewport height
1vmin = 1vw or 1vh, whichever is smaller
1vmax = 1vw or 1vh, whichever is larger
h1 {
font-size: 5.9vw;
}
h2 {
font-size: 3.0vh;
}
p {
font-size: 2vmin;
}
Using spark sql query..just incase if it helps anyone!
import org.apache.spark.sql.SparkSession
import org.apache.spark.SparkConf
import org.apache.spark.sql.functions._
import org.apache.spark.SparkContext
import java.util.stream.Collectors
val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()
df.createOrReplaceTempView("steps")
val sum = spark.sql("select sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28
SELECT Stuff(
(SELECT N', ' + Name FROM Names FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'')
you can use the FOR JSON syntax
i.e.
SELECT per.ID,
Emails = JSON_VALUE(
REPLACE(
(SELECT _ = em.Email FROM Email em WHERE em.Person = per.ID FOR JSON PATH)
,'"},{"_":"',', '),'$[0]._'
)
FROM Person per
And the result will become
Id Emails
1 [email protected]
2 NULL
3 [email protected], [email protected]
This will work even your data contains invalid XML characters
the '"},{"":"' is safe because if you data contain '"},{"":"', it will be escaped to "},{\"_\":\"
You can replace ', ' with any string separator
You can use the new STRING_AGG function
Try pressing Ctrl + Alt + Space
(which toggles between suggestion and standard completion modes)
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
This workflow works best for me:
git checkout -b develop
...make some changes...
...notice master has been updated...
...commit changes to develop...
git checkout master
git pull
...bring those changes back into develop...
git checkout develop
git rebase master
...make some more changes...
...commit them to develop...
...merge them into master...
git checkout master
git pull
git merge develop
you'd better reference angular document, becuase the version[1.4.9] has update to below that make it could support data-ng-cloak directive.
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
Something like this if you're into regex, not sure of the exact syntax for the replace tho!
MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
This is a useful article which graphically shows the explanation of the reset command.
https://git-scm.com/docs/git-reset
Reset --hard can be quite dangerous as it overwrites your working copy without checking, so if you haven't commited the file at all, it is gone.
As for Source tree, there is no way I know of to undo commits. It would most likely use reset under the covers anyway
It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)
Use request.args
to get parsed contents of query string:
from flask import request
@app.route(...)
def login():
username = request.args.get('username')
password = request.args.get('password')
THis issue has been fixed with new mysql connectors, please use http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38
I used to get this error after updating the connector jar, issue resolved.
Arrays (called list
in python) use the []
notation. {}
is for dict
(also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
I hope this query will help you
INSERT INTO `dTable` (`field1`, `field2`)
SELECT field1, field2 FROM `sTable`
WHERE `sTable`.`field1` NOT IN (SELECT `field1` FROM `dTable`)
Just for the record, I've ran into the same issue today but this time the page was embedded in an object, not an iframe (since it was an XHTML 1.1 document). Here's how it works with objects:
document
.getElementById('targetFrame')
.contentDocument
.defaultView
.targetFunction();
(sorry for the ugly line breaks, didn't fit in a single line)
You can try manipula
package, which implement all of C# LINQ methods and save its syntax:
https://github.com/litichevskiydv/manipula
https://www.npmjs.com/package/manipula
Your example selectedFruits.select(fruit=>fruit.id);
will be implemented with manipula as
Manipula.from(selectedFruits).select(fruit=>fruit.id);
ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)
if you make this int i[3] then i takes values i[0] i[1] i[2]
for your problem try this code structure
double[] array = new double[50];
for (int i = 0; i < 24; i++) {
}
for (int j = 25; j < 50; j++) {
}
I have fixed this problem by modifying app build.gradle file.
For Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
For Gradle Plugin 1.5
android {
defaultConfig {
generatedDensities = []
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
}
In a word, you can't.
3.65
cannot be represented exactly as a float
. The number that you're getting is the nearest number to 3.65
that has an exact float
representation.
The difference between (older?) Python 2 and 3 is purely due to the default formatting.
I am seeing the following both in Python 2.7.3 and 3.3.0:
In [1]: 3.65
Out[1]: 3.65
In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'
For an exact decimal datatype, see decimal.Decimal
.
Most of the time you need to create a Service to perform something in the background, and your visible Activity
simply controls this Service
. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activity
can finish
as usual and the Service
will still be running.
A simpler approach is to capture the Back
button press and call moveTaskToBack(true) as follows:
// 2.0 and above
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack
can be used as a quick alternative on occasion.
NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed
method, and these recommendations on how to handle the Back button.
There is a NuGet package named StrongNamer by Daniel Plaisted that seems to do the trick.
Is the simplest solution that I've found so far.
There are also a number of other NuGet packages to fix the strong naming problem such as Brutal.Dev.StrongNameSigner by Werner van Deventer, but I have not tested that one or any of the others.
These files will successfully open sshd and run service so you can ssh in locally. (you are using cyberduck aren't you?)
Dockerfile
FROM swiftdocker/swift
MAINTAINER Nobody
RUN apt-get update && apt-get -y install openssh-server supervisor
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
EXPOSE 22
CMD ["/usr/bin/supervisord"]
supervisord.conf
[supervisord]
nodaemon=true
[program:sshd]
command=/usr/sbin/sshd -D
to build / run start daemon / jump into shell.
docker build -t swift3-ssh .
docker run -p 2222:22 -i -t swift3-ssh
docker ps # find container id
docker exec -i -t <containerid> /bin/bash
For python2, It's better to use e.message
to get the exception message, this will avoid possible UnicodeDecodeError
. But yes e.message
will be empty for some kind of exceptions like OSError
, in which case we can add a exc_info=True
to our logging function to not miss the error.
For python3, I think it's safe to use str(e)
.
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
How about instead of height, you use something like below one
#child0 {
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s linear;
position: absolute;
}
#parent0:hover #child0 {
visibility: visible;
opacity: 1;
position: relative;
}
Works great as well. Please do add prefixes. Hope this helps someone.
PS: if you still need height 0 to height something black magic, you can add height: 0;
to #child0
and then add height: inherit
to #parent0:hover #child0
. Simultaneously, you can add transition for height individually or just you all.
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
If you use performSelectorInBackground:withObject:
to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details – see "Using NSObject to Spawn a Thread" in Apple's Threading Programming Guide.
You'd probably be better off using Grand Central Dispatch, though:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self getResultSetFromDB:docids];
});
GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.
Updated with a hat tip to Chris Nolet, who suggested a change that makes the above code simpler and keeps up with Apple's latest GCD code examples.
Your @POST
method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:
@XmlRootElement
public class MyJaxBean {
@XmlElement public String param1;
@XmlElement public String param2;
}
Then your @POST
method would look like the following:
@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
System.out.println("param1 = " + input.param1);
System.out.println("param2 = " + input.param2);
}
This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input
in this case. The actual message would look something like:
POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com
{"param1":"hello","param2":"world"}
Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.
HTML <FORM>
The parameters would be annotated using @FormParam:
@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
@FormParam("param2") String param2) {
...
}
The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:
POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25
param1=hello¶m2=world
The content is URL encoded in this case.
If you do not know the names of the FormParam's you can do the following:
@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
...
}
HTTP Headers
You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:
@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
@HeaderParam("param2") String param2) {
...
}
Here's what the HTTP message would look like. Note that this POST does not have a body.
POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world
I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.
HTTP Query Parameters
This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.
@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
@QueryParam("param2") String param2) {
...
}
Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:
POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com
You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.
HTTP Path Parameters
Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:
@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
@PathParam("param2") String param2) {
...
}
The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.
POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com
This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.
As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM
-based HTML pages, then use @FormParam
. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer
implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM
encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.
Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.
In addition to forcats::fct_infreq, mentioned by @HolgerBrandl, there is forcats::fct_rev, which reverses the factor order.
theTable <- data.frame(
Position=
c("Zoalkeeper", "Zoalkeeper", "Defense",
"Defense", "Defense", "Striker"),
Name=c("James", "Frank","Jean",
"Steve","John", "Tim"))
p1 <- ggplot(theTable, aes(x = Position)) + geom_bar()
p2 <- ggplot(theTable, aes(x = fct_infreq(Position))) + geom_bar()
p3 <- ggplot(theTable, aes(x = fct_rev(fct_infreq(Position)))) + geom_bar()
gridExtra::grid.arrange(p1, p2, p3, nrow=3)
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columnIndex].Visible = false;
}
HeaderText
for the GridViewColumn
and then find the column using that HeaderText
.
protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
((DataControlField)UsersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Email")
.SingleOrDefault()).Visible = false;
}
If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url
command:
git remote get-url origin
(nice pendant of git remote set-url origin <newurl>
)
See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf
).
(Merged by Junio C Hamano -- gitster
-- in commit e437cbd, 05 Oct 2015)
remote: add get-url subcommand
Expanding
insteadOf
is a part ofls-remote --url
and there is no way to expandpushInsteadOf
as well.
Add aget-url
subcommand to be able to query both as well as a way to get all configured urls.
If you use the Eclipse IDE with the SVN plugin you can do as follows:
This will revert the files to the revision that you want. Just keep in mind that SVN will see the changes as a new commit. That is, the change gets a new revision number, and there is no link between the old revision and the new one. You should specify in the commit comments that you are reverting those files to a specific revision.
Add commons-collections4-x.x.jar file in your build path and try it again. It will work.
You can download it from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0
You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:
WITH cte AS (
SELECT[foo], [bar],
row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
FROM TABLE
)
DELETE cte WHERE [rn] > 1
Play around with it and see what you get.
(Edit: In an attempt to be helpful, someone edited the ORDER BY
clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc
)
Well, weeks ago I made a very similiar question (Get CDN url from uploaded file via Storage): I wanted the CDN url to show the image in my view (as you are requiring ).
However, after review the package API I confirmed that there is no way do this task. So, my solution was avoid using flysystem
. In my case, I needed to play with RackSpace. So, finally decide to create my use package and make my own storage package using The PHP SDK for OpenStack.
By this way, you have full access for functions that you need like getPublicUrl()
in order to get the public URL from a cdn container:
/** @var DataObject $file */
$file = \OpenCloud::container('cdn')->getObject('screenshots/1.jpg');
// $url: https://d224d291-8316ade.ssl.cf1.rackcdn.com/screenshots/1.jpg
$url = (string) $file->getPublicUrl(UrlType::SSL);
In conclusion, if need to take storage service to another level, then flysystem
is not enough. For local
purposes, you can try @nXu's solution
A ClassCastException
ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example
Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;
This works because an apple 'is a' fruit. However if we reverse this.
Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;
This will throw a ClasCastException because a Fruit is not (always) an Apple.
It is good practice to guard any explicit casts with an instanceof
check first:
if (myApple instanceof Fruit) {
Fruit myFruit = (Fruit)myApple;
}
You just need to redefine the DataSource. So if you have for example DataGridView's DataSource that contains a, b, i c:
DataGridView.DataSource = a, b, c
And suddenly you update the DataSource so you have just a and b, you would need to redefine your DataSource:
DataGridView.DataSource = a, b
I hope you find this useful.
Thank you.
With ES6, we now have a simple way to create an Array from a NodeList: the Array.from()
function.
// nl is a NodeList
let myArray = Array.from(nl)
You can only break
a block scope if you label it. For example:
myBlock: {
var a = 0;
break myBlock;
a = 1; // this is never run
};
a === 0;
You cannot break a block scope from within a function in the scope. This means you can't do stuff like:
foo: { // this doesn't work
(function() {
break foo;
}());
}
You can do something similar though with functions:
function myFunction() {myFunction:{
// you can now use break myFunction; instead of return;
}}
Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.
Clik Android Sdk Location
Select & Browse your Android SDK Location (Like: C:\Android\sdk)
Uncheck USE EMBEDDED JDK LOCATION
Here is the method that I finally came up with after struggling:
Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*
To make the output cleaner (only path), use:
(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname
To get only the first result, use:
(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname | Select -First 1
Now for the important stuff:
To search only for files/directories do not use -File
or -Directory
(see below why). Instead use this for files:
Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
and remove the -eq $false
for directories. Do not leave a trailing wildcard like bin/*
.
Why not use the built in switches? They are terrible and remove features randomly. For example, in order to use -Include
with a file, you must end the path with a wildcard. However, this disables the -Recurse
switch without telling you:
Get-ChildItem -File -Recurse -Path ./bin/* -Include *.lib
You'd think that would give you all *.lib
s in all subdirectories, but it only will search top level of bin
.
In order to search for directories, you can use -Directory
, but then you must remove the trailing wildcard. For whatever reason, this will not deactivate -Recurse
. It is for these reasons that I recommend not using the builtin flags.
You can shorten this command considerably:
Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
becomes
gci './path*/' -s -Include 'name*' | where {$_.PSIsContainer -eq $false}
Get-ChildItem
is aliased to gci
-Path
is default to position 0, so you can just make first argument path-Recurse
is aliased to -s
-Include
does not have a shorthandIn Servlet technology if you want to pass any input to a particular servlet then you need to pass in init param like below code.
<servlet>
<servlet-name>DBController</servlet-name>
<servlet-class>com.test.controller.DBController</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>John</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DBController</servlet-name>
<url-pattern>/DBController</url-pattern>
</servlet-mapping>
If you want to pass some in put that is common for all servlets then that time you need to configure context param. Example
<context-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</context-param>
SO exactly like this when ever we are working with Spring MVC we need to provide some information to Predefined servlet provided by Spring that is DispatcherServlet through init param. So the configuration is as fallows, here we are providing the spring-servlet.xml as init parameter to DispatcherServlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Spring MVC App</display-name>
<servlet>
<servlet-name>SpringController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringController</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
Again we need some context param. That is applicable for whole application. So we can provide the root context that is applicationcontext.xml The configuration is like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationcontext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringController</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Basically when you hit 'return' on a function the function will stop and will not continue your iteration, so what you need to do is put it all on a list and then add it as a children of a widget
you can do something like this:
Widget getTextWidgets(List<String> strings)
{
List<Widget> list = new List<Widget>();
for(var i = 0; i < strings.length; i++){
list.add(new Text(strings[i]));
}
return new Row(children: list);
}
or even better, you can use .map() operator and do something like this:
Widget getTextWidgets(List<String> strings)
{
return new Row(children: strings.map((item) => new Text(item)).toList());
}
A SysOps guy once taught me the Three-Fingered Claw technique:
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try()
your statement and code on.
(based on flying sheep comment).
yell
: print the script name and all arguments to stderr
:
$0
is the path to the script ;$*
are all arguments. >&2
means >
redirect stdout to & pipe 2
. pipe 1
would be stdout
itself. die
does the same as yell
, but exits with a non-0 exit status, which means “fail”. try
uses the ||
(boolean OR
), which only evaluates the right side if the left one failed.
$@
is all arguments again, but different. What if you specified the default value to return, instead of using default(T)?
public static T GetQueryString<T>(string key, T defaultValue) {...}
It makes calling it easier too:
var intValue = GetQueryString("intParm", Int32.MinValue);
var strValue = GetQueryString("strParm", "");
var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified
The downside being you need magic values to denote invalid/missing querystring values.
Whereas most of the existing answers are great, I would like to include an answer using a traditional for loop, which should also be considered here. The OP requests an answer which is ES5/ES6 compatible, and the traditional for loop applies :)
The problem with using array functions in this scenario, is that they don't mutate objects, but in this case, mutation is a requirement. The performance gain of using a traditional for loop is just a (huge) bonus.
const findThis = 2;
const items = [{id:1, ...}, {id:2, ...}, {id:3, ...}];
for (let i = 0, l = items.length; i < l; ++i) {
if (items[i].id === findThis) {
items[i].iAmChanged = true;
break;
}
}
Although I am a great fan of array functions, don't let them be the only tool in your toolbox. If the purpose is mutating the array, they are not the best fit.
Switching to another branch in git. Straightforward answer,
git-checkout - Switch branches or restore working tree files
git fetch origin <----this will fetch the branch
git checkout branch_name <--- Switching the branch
Before switching the branch make sure you don't have any modified files, in that case, you can commit the changes or you can stash it.
A convenient function for saving plots is ggsave()
, which can automatically guess the device type based on the file extension, and smooths over differences between devices. You save with a certain size and units like this:
ggsave("mtcars.png", width = 20, height = 20, units = "cm")
In R markdown, figure size can be specified by chunk:
```{r, fig.width=6, fig.height=4}
plot(1:5)
```
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
Unexpected end of file
means that something else was expected before the PHP parser reached the end of the script.
Judging from your HUGE file, it's probably that you're missing a closing brace (}
) from an if
statement.
Please at least attempt the following things:
;
in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?>
vs <?php echo $this->layouts->print_includes() ?>
. It's not required, so don't use it (or do, just do one or the other).server {
server_name www.mysite2.name;
return 301 $scheme://mysite2.name$request_uri;
}
server {
#This config is based on https://github.com/daylerees/laravel-website-configs/blob/6db24701073dbe34d2d58fea3a3c6b3c0cd5685b/nginx.conf
server_name mysite2.name;
# The location of our project's public directory.
root /usr/share/nginx/mysite2/live/public/;
# Point index to the Laravel front controller.
index index.php;
location / {
# URLs to attempt, including pretty ones.
try_files $uri $uri/ /index.php?$query_string;
}
# Remove trailing slash to please routing system.
if (!-d $request_filename) {
rewrite ^/(.+)/$ /$1 permanent;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
# # With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Then the only output in the browser was a Laravel error: “Whoops, looks like something went wrong.”
Do NOT run chmod -R 777 app/storage
(note). Making something world-writable is bad security.
chmod -R 755 app/storage
works and is more secure.
So, two years after I originally answered this question I come back to see that it has pretty much turned into a big mess. I feel it's about time I come back to it and make my answer truly correct since it is the most upvoted + accepted.
For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.
My original answer was this:
// not correct, use answer below
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Which might work for a lot of cases, including for the OP, but as pointed out in the comments and in other answers, will clear radio/checkbox elements from any value attributes.
A more correct answer (but not perfect) is:
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name
Using the :text
, :radio
, etc. selectors by themselves is considered bad practice by jQuery as they end up evaluating to *:text
which makes it take much longer than it should. I do prefer the whitelist approach and wish I had used it in my original answer. Anyhow, by specifying the input
part of the selector, plus the cache of the form element, this should make it the best performing answer here.
This answer might still have some flaws if people's default for select elements is not an option that has a blank value, but it is certainly as generic as it is going to get and this would need to be handled on a case-by-case basis.
This works well
You can also directly get selected value using following code
<select ng-options='t.name for t in templates'
ng-change='selectedTemplate(t.url)'></select>
script.js
$scope.selectedTemplate = function(pTemplate) {
//Your logic
alert('Template Url is : '+pTemplate);
}
You can use the Sum
function, but you'll have to convert the strings to integers, like so:
int total = monValues.Sum(x => Convert.ToInt32(x));
For Android Studio add the following to your top-level build.gradle
file within the allprojects
block
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
Use a comma to specify two (or more) different rules:
@media screen and (max-width: 995px),
screen and (max-height: 700px) {
...
}
From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.
Check out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.
Example code snippet from the link (which is itself from this MSDN sample code project):
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
Quoting:
If
AccessTheWebAsync
doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.
string urlContents = await client.GetStringAsync();
More details are in the link.
let a = {};_x000D_
let b = {};_x000D_
_x000D_
a.prop1 = 2;_x000D_
a.prop2 = { prop3: 2 };_x000D_
_x000D_
b.prop1 = 2;_x000D_
b.prop2 = { prop3: 3 };_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// false_x000D_
b.prop2 = { prop3: 2};_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// true
_x000D_
In Ruby, the Hash#select is a right option. If you work with Rails, you can use Hash#slice and Hash#slice!. e.g. (rails 3.2.13)
h1 = {:a => 1, :b => 2, :c => 3, :d => 4}
h1.slice(:a, :b) # return {:a=>1, :b=>2}, but h1 is not changed
h2 = h1.slice!(:a, :b) # h1 = {:a=>1, :b=>2}, h2 = {:c => 3, :d => 4}
The @Url.Action()
method is proccess on the server-side
, so you cannot pass a client-side
value to this function as a parameter. You can concat the client-side
variables with the server-side
url generated by this method, which is a string on the output. Try something like this:
var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
The @Url.Action("Display", "Customer")
is processed on the server-side
and the rest of the string is processed on the client-side
, concatenating the result of the server-side
method with the client-side
.
I understand it’s an old question – however I would like to add an example where cost is same but one query is better than the other.
As you observed in the question, % shown in execution plan is not the only yardstick for determining best query. In the following example, I have two queries doing the same task. Execution Plan shows both are equally good (50% each). Now I executed the queries with SET STATISTICS IO ON
which shows clear differences.
In the following example, the query 1 uses seek
whereas Query 2 uses scan
on the table LWManifestOrderLineItems. When we actually checks the execution time however it is find that Query 2 works better.
Also read When is a Seek not a Seek? by Paul White
QUERY
---Preparation---------------
-----------------------------
DBCC FREEPROCCACHE
GO
DBCC DROPCLEANBUFFERS
GO
SET STATISTICS IO ON --IO
SET STATISTICS TIME ON
--------Queries---------------
------------------------------
SELECT LW.Manifest,LW.OrderID,COUNT(DISTINCT LineItemID)
FROM LWManifestOrderLineItems LW
INNER JOIN ManifestContainers MC
ON MC.Manifest = LW.Manifest
GROUP BY LW.Manifest,LW.OrderID
ORDER BY COUNT(DISTINCT LineItemID) DESC
SELECT LW.Manifest,LW.OrderID,COUNT( LineItemID) LineCount
FROM LWManifestOrderLineItems LW
WHERE LW.Manifest IN (SELECT Manifest FROM ManifestContainers)
GROUP BY LW.Manifest,LW.OrderID
ORDER BY COUNT( LineItemID) DESC
Statistics IO
Execution Plan
On Ubuntu; using mkvirtualenv -p python3 env_name
loads the virtualenv with python3.
Inside the env, use python --version
to verify.
As a one-liner into vim:
:set tabstop=4 shiftwidth=4
For permanent setup, add these lines to ~/.vimrc:
set tabstop=4
set shiftwidth=4
NOTE: Add set expandtab
if you prefer 4-spaces indentation, instead of a tab indentation.
The if
attribute does not exist for <copy>
. It should be applied to the <target>
.
Below is an example of how you can use the depends
attribute of a target and the if
and unless
attributes to control execution of dependent targets. Only one of the two should execute.
<target name="prepare-copy" description="copy file based on condition"
depends="prepare-copy-true, prepare-copy-false">
</target>
<target name="prepare-copy-true" description="copy file based on condition"
if="copy-condition">
<echo>Get file based on condition being true</echo>
<copy file="${some.dir}/true" todir="." />
</target>
<target name="prepare-copy-false" description="copy file based on false condition"
unless="copy-condition">
<echo>Get file based on condition being false</echo>
<copy file="${some.dir}/false" todir="." />
</target>
If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}"
instead of if="copy-condition"
.
In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.
If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate
.
!ls # to find the directory you're in ,
%cd ./samplefolder #if you wanna go into a folder (say samplefolder)
or if you wanna go out of the current folder
%cd ../
and then navigate to the required folder/file accordingly
What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.
The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.
You could try the following, however it will also load all the keys into memory
Object.keys(o).forEach(function(key) {
var val = o[key];
logic();
});
However since Object.keys
is a native method it may allow for better optimisation.
As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.
var async = {};
async.forEach = function(o, cb) {
var counter = 0,
keys = Object.keys(o),
len = keys.length;
var next = function() {
if (counter < len) cb(o[keys[counter++]], next);
};
next();
};
async.forEach(obj, function(val, next) {
// do things
setTimeout(next, 100);
});
Try this code for to trim
a String
Public Function AllTrim(ByVal GeVar As String) As String
Dim i As Integer
Dim e As Integer
Dim NewStr As String = ""
e = Len(GeVar)
For i = 1 To e
If Mid(GeVar, i, 1) <> " " Then
NewStr = NewStr + Mid(GeVar, i, 1)
End If
Next i
AllTrim = NewStr
' MsgBox("alltrim = " & NewStr)
End Function
I created a small NodeJS script based on donut's answer. Store the following in a file called get-facebook-access-token.js:
const fetch = require('node-fetch');
const open = require('open');
const api_version = 'v9.0';
const app_id = '';
const app_secret = '';
const short_lived_token = '';
const page_name = '';
const getPermanentAccessToken = async () => {
try {
const long_lived_access_token = await getLongLivedAccessToken();
const account_id = await getAccountId(long_lived_access_token);
const permanent_page_access_token = await getPermanentPageAccessToken(
long_lived_access_token,
account_id
);
checkExpiration(permanent_page_access_token);
} catch (reason) {
console.error(reason);
}
};
const getLongLivedAccessToken = async () => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${short_lived_token}`
);
const body = await response.json();
return body.access_token;
};
const getAccountId = async (long_lived_access_token) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/me?access_token=${long_lived_access_token}`
);
const body = await response.json();
return body.id;
};
const getPermanentPageAccessToken = async (
long_lived_access_token,
account_id
) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/${account_id}/accounts?access_token=${long_lived_access_token}`
);
const body = await response.json();
const page_item = body.data.find(item => item.name === page_name);
return page_item.access_token;
};
const checkExpiration = (access_token) => {
open(`https://developers.facebook.com/tools/debug/accesstoken/?access_token=${access_token}&version=${api_version}`);
}
getPermanentAccessToken();
Fill in the constants and then run:
npm install node-fetch
npm install open
node get-facebook-access-token.js
After running the script a page is opened in the browser that shows the token and how long it is valid.
Using this way You will do a endless Loop on Your JS. to do a better way you can use the following
var on_submit_function = function(evt){
evt.preventDefault(); //The form wouln't be submitted Yet.
(...yourcode...)
$(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
$(this).submit();
}
$('form').on('submit', on_submit_function); //Registering on submit.
I hope it helps! Thanks!
Surround that select with parentheses.
SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;
Because you might be using jdk1.5+ and there it is auto converting to int. So in your code its first returning Integer and then auto converted to int.
your code is same as
int abc = new Integer(123);
An array length
is not the number of elements in a array, it is the highest index + 1
. length
property will report correct element count only if there are valid elements in consecutive indices.
var a = [];
a[23] = 'foo';
a.length; // 24
Saying that, there is no way to exclude undefined elements from count without using any form of a loop.
The best way to configure the standard headers for your project is by setting the compilerPath
property to the configurations in your c_cpp_properties.json
file. It is not recommended to add system include paths to the includePath
property.
Another option if you prefer not to use c_cpp_properties.json
is to set the C_Cpp.default.compilerPath
setting.
Neither hacking PYTHONPATH
nor sys.path
is a good idea due to the before mentioned reasons. And for linking the current project into the site-packages folder there is actually a better way than python setup.py develop
, as explained here:
pip install --editable path/to/project
If you don't already have a setup.py in your project's root folder, this one is good enough to start with:
from setuptools import setup
setup('project')
String str = " Text with multiple spaces ";
str = org.apache.commons.lang3.StringUtils.normalizeSpace(str);
// str = "Text with multiple spaces"
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
In my case I just removed .csv from the end. I am using ubuntu.
pd.read_csv("/home/mypc/Documents/pcap/s2csv")
I used (the suggested answer from above)
sudo apt-get install eclipse eclipse-cdt g++
but ONLY after then also doing
sudo eclipse -clean
Hope that also helps.
Remember to look if your column can be null. You can do that using
mysql> desc my_table;
If your column cannot be null, when you set the value to null it will be the cast value to it.
Here a example
mysql> create table example ( age int not null, name varchar(100) not null );
mysql> insert into example values ( null, "without num" ), ( 2 , null );
mysql> select * from example;
+-----+-------------+
| age | name |
+-----+-------------+
| 0 | without num |
| 2 | |
+-----+-------------+
2 rows in set (0.00 sec)
mysql> select * from example where age is null or name is null;
Empty set (0.00 sec)
"mxc" is right. fetchType
just specifies when the relation should be resolved.
To optimize eager loading by using an outer join you have to add
@Fetch(FetchMode.JOIN)
to your field. This is a hibernate specific annotation.
sshpass
is broken if you try to use it inside a Sublime Text build target, inside a Makefile. Instead of sshpass
, you can use passh
: https://github.com/clarkwang/passh
With sshpass
you would do:
sshpass -p pa$$word ssh user@host
With passh
you would do:
passh -p pa$$word ssh user@host
Note: Do not forget to use -o StrictHostKeyChecking=no
. Otherwise, the connection will hang on the first time you use it. For example:
passh -p pa$$word ssh -o StrictHostKeyChecking=no user@host
References:
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
One thing i would like to add
In a signed int
, which is the default value in mysql
, 1 bit
will be used to represent sign
. -1 for negative and 0 for positive.
So if your application insert only positive value it should better specify unsigned.
This is an aggregation problem, not a reshaping problem as the question originally suggested -- we wish to aggregate each column into a mean and standard deviation by ID. There are many packages that handle such problems. In the base of R it can be done using aggregate
like this (assuming DF
is the input data frame):
ag <- aggregate(. ~ ID, DF, function(x) c(mean = mean(x), sd = sd(x)))
Note 1: A commenter pointed out that ag
is a data frame for which some columns are matrices. Although initially that may seem strange, in fact it simplifies access. ag
has the same number of columns as the input DF
. Its first column ag[[1]]
is ID
and the ith column of the remainder ag[[i+1]]
(or equivalanetly ag[-1][[i]]
) is the matrix of statistics for the ith input observation column. If one wishes to access the jth statistic of the ith observation it is therefore ag[[i+1]][, j]
which can also be written as ag[-1][[i]][, j]
.
On the other hand, suppose there are k
statistic columns for each observation in the input (where k=2 in the question). Then if we flatten the output then to access the jth statistic of the ith observation column we must use the more complex ag[[k*(i-1)+j+1]]
or equivalently ag[-1][[k*(i-1)+j]]
.
For example, compare the simplicity of the first expression vs. the second:
ag[-1][[2]]
## mean sd
## [1,] 36.333 10.2144
## [2,] 32.250 4.1932
## [3,] 43.500 4.9497
ag_flat <- do.call("data.frame", ag) # flatten
ag_flat[-1][, 2 * (2-1) + 1:2]
## Obs_2.mean Obs_2.sd
## 1 36.333 10.2144
## 2 32.250 4.1932
## 3 43.500 4.9497
Note 2: The input in reproducible form is:
Lines <- "ID Obs_1 Obs_2 Obs_3
1 43 48 37
1 27 29 22
1 36 32 40
2 33 38 36
2 29 32 27
2 32 31 35
2 25 28 24
3 45 47 42
3 38 40 36"
DF <- read.table(text = Lines, header = TRUE)
320
And the segments look like this
{64}@{255}
64 + 1 + 255 = 320
You should also read this if you are validating emails
http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
For MacPython installations, I found an effective solution to fixing the problem with setuptools (easy_install) in this blog post:
http://droidism.com/getting-running-with-django-and-macpython-26-on-leopard
One handy tip includes finding out which version of python is active in the terminal:
which python
a little bit code from my side (custom function for Array):
Array.prototype.in_array = function (array) {
var $i = 0;
var type = typeof array;
while (this[$i]) {
if ((type == ('number') || type == ('string')) && array == this[$i]) {
return true;
} else if (type == 'object' && array instanceof Array && array.in_array(this[$i])) {
return true
}
$i++;
}
return false;
};
var array = [1, 2, 3, "a", "b", "c"];
//if string in array
if (array.in_array('b')) {
console.log("in array");
}
//if number in array
if (array.in_array(3)) {
console.log("in array");
}
// if one from array in array
if (array.in_array([1, 'b'])) {
console.log("in array");
}
I think this link is pretty good.
Sample output from that link:
mysql> SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
-> FROM book_mast
-> GROUP BY cate_id;
+---------+---------------------------+-----------------------+
| cate_id | COUNT(DISTINCT(pub_lang)) | ROUND(AVG(no_page),2) |
+---------+---------------------------+-----------------------+
| CA001 | 2 | 264.33 |
| CA002 | 1 | 433.33 |
| CA003 | 2 | 256.67 |
| CA004 | 3 | 246.67 |
| CA005 | 3 | 245.75 |
+---------+---------------------------+-----------------------+
5 rows in set (0.00 sec)
I tried differently for the same issue and worked .
Go to your project location in hard drive. ex: /home/user/workspace/project/settings and Delete this file org.eclipse.core.resources.prefs
For full details check out bellow link
http://errorkode.com/viewtopic.php?f=20&t=8&sid=40cff1661bf0ace12878d6d6fb7e75ac
I like an example from Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates - Head First Design Patterns
book.
Example:
let's assume you created home theatre and finally you would like to watch a movie. So you have to do:
Amplifier amplifier = new Amplifier();
CdPlayer cdPlayer = new CdPlayer();
DvdPlayer dvdPlayer = new DvdPlayer();
Lights lights = new Lights();
PopcornPopper popcornPopper = new PopcornPopper();
Projector projector = new Projector();
Screen screen = new Screen();
popcornPopper.turnOn();
popcornPopper.pop();
amplifier.turnOn();
amplifier.setVolume(10);
lights.turnOn();
lights.dim(10);
screen.up();
dvdPlayer.turnOn();
dvdPlayer.play();
what happens when movie is over? You have to do the same but in reverse order so complexity of watch and end movie is becoming very complex. Facade pattern says that you can create a facade and let user just call one method instead of calling all of this. Let's create facade:
public class HomeTheatherFacade {
Amplifier amplifier;
DvdPlayer dvdPlayer;
CdPlayer cdPlayer;
Projector projector;
Lights lights;
Screen screen;
PopcornPopper popcornPopper;
public HomeTheatherFacade(Amplifier amplifier, DvdPlayer dvdPlayer, CdPlayer cdPlayer, Projector projector, Lights lights, Screen screen, PopcornPopper popcornPopper) {
this.amplifier = amplifier;
this.dvdPlayer = dvdPlayer;
this.cdPlayer = cdPlayer;
this.projector = projector;
this.lights = lights;
this.screen = screen;
this.popcornPopper = popcornPopper;
}
public void watchMovie(String movieTitle) {
popcornPopper.turnOn();
popcornPopper.pop();
amplifier.turnOn();
amplifier.setVolume(10);
lights.turnOn();
lights.dim(10);
screen.up();
dvdPlayer.turnOn();
dvdPlayer.play();
}
public void endMovie() {
dvdPlayer.turnOff();
screen.down();
lights.turnOff();
amplifier.turnOff();
}
}
and now instead of calling all of this you can just call watchMovie
and endMovie
methods:
public class HomeTheatherFacadeTest {
public static void main(String[] args){
Amplifier amplifier = new Amplifier();
CdPlayer cdPlayer = new CdPlayer();
DvdPlayer dvdPlayer = new DvdPlayer();
Lights lights = new Lights();
PopcornPopper popcornPopper = new PopcornPopper();
Projector projector = new Projector();
Screen screen = new Screen();
HomeTheatherFacade homeTheatherFacade = new HomeTheatherFacade(amplifier, dvdPlayer, cdPlayer, projector, lights, screen, popcornPopper);
homeTheatherFacade.watchMovie("Home Alone");
homeTheatherFacade.endMovie();
}
}
So:
"The Facade Pattern provides a unified interface to a set of interfaces in a subsytem. Facade defines a higher level interface that makes the subsystem easier to use."
If you are using CocoaPods and you want to disable Bitcode for all libraries, use the following command in the Podfile
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
end
end
end
Here are shortcuts for the IPython Notebook.
Ctrl-m i
interrupts the kernel. (that is, the sole letter i after Ctrl-m
)
According to this answer, I
twice works as well.
if you want to get the index position of the outliers idx_list
will return it.
def reject_outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/mdev if mdev else 0.
data_range = np.arange(len(data))
idx_list = data_range[s>=m]
return data[s<m], idx_list
data_points = np.array([8, 10, 35, 17, 73, 77])
print(reject_outliers(data_points))
after rejection: [ 8 10 35 17], index positions of outliers: [4 5]
print ["Not a palindrome","Is a palindrome"][s == ''.join([s[len(s)-i-1] for i in range(len(s))])]
This is the typical way of writing single line code
I was previously using the top-voted answer, but it needs a bit of cleanup, so here it is redone for Xcode 4, with some improvements.
I've researched every file in this list, but several of them do not exist in Apple's official Xcode documentation, so I had to go on Apple mailing lists.
Apple continues to add undocumented files, potentially corrupting our live projects. This IMHO is unacceptable, and I've now started logging bugs against it each time they do so. I know they don't care, but maybe it'll shame one of them into treating developers more fairly.
If you need to customize, here's a gist you can fork: https://gist.github.com/3786883
#########################
# .gitignore file for Xcode4 and Xcode5 Source projects
#
# Apple bugs, waiting for Apple to fix/respond:
#
# 15564624 - what does the xccheckout file in Xcode5 do? Where's the documentation?
#
# Version 2.6
# For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects
#
# 2015 updates:
# - Fixed typo in "xccheckout" line - thanks to @lyck for pointing it out!
# - Fixed the .idea optional ignore. Thanks to @hashier for pointing this out
# - Finally added "xccheckout" to the ignore. Apple still refuses to answer support requests about this, but in practice it seems you should ignore it.
# - minor tweaks from Jona and Coeur (slightly more precise xc* filtering/names)
# 2014 updates:
# - appended non-standard items DISABLED by default (uncomment if you use those tools)
# - removed the edit that an SO.com moderator made without bothering to ask me
# - researched CocoaPods .lock more carefully, thanks to Gokhan Celiker
# 2013 updates:
# - fixed the broken "save personal Schemes"
# - added line-by-line explanations for EVERYTHING (some were missing)
#
# NB: if you are storing "built" products, this WILL NOT WORK,
# and you should use a different .gitignore (or none at all)
# This file is for SOURCE projects, where there are many extra
# files that we want to exclude
#
#########################
#####
# OS X temporary files that should never be committed
#
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.DS_Store
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.Trashes
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
*.swp
#
# *.lock - this is used and abused by many editors for many different things.
# For the main ones I use (e.g. Eclipse), it should be excluded
# from source-control, but YMMV.
# (lock files are usually local-only file-synchronization on the local FS that should NOT go in git)
# c.f. the "OPTIONAL" section at bottom though, for tool-specific variations!
#
# In particular, if you're using CocoaPods, you'll want to comment-out this line:
*.lock
#
# profile - REMOVED temporarily (on double-checking, I can't find it in OS X docs?)
#profile
####
# Xcode temporary files that should never be committed
#
# NB: NIB/XIB files still exist even on Storyboard projects, so we want this...
*~.nib
####
# Xcode build files -
#
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "DerivedData"
DerivedData/
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "build"
build/
#####
# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)
#
# This is complicated:
#
# SOMETIMES you need to put this file in version control.
# Apple designed it poorly - if you use "custom executables", they are
# saved in this file.
# 99% of projects do NOT use those, so they do NOT want to version control this file.
# ..but if you're in the 1%, comment out the line "*.pbxuser"
# .pbxuser: http://lists.apple.com/archives/xcode-users/2004/Jan/msg00193.html
*.pbxuser
# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode1v3
# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode2v3
# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file
*.perspectivev3
# NB: also, whitelist the default ones, some projects need to use these
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3
####
# Xcode 4 - semi-personal settings
#
# Apple Shared data that Apple put in the wrong folder
# c.f. http://stackoverflow.com/a/19260712/153422
# FROM ANSWER: Apple says "don't ignore it"
# FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode
# Up to you, but ... current advice: ignore it.
*.xccheckout
#
#
# OPTION 1: ---------------------------------
# throw away ALL personal settings (including custom schemes!
# - unless they are "shared")
# As per build/ and DerivedData/, this ought to have a trailing slash
#
# NB: this is exclusive with OPTION 2 below
xcuserdata/
# OPTION 2: ---------------------------------
# get rid of ALL personal settings, but KEEP SOME OF THEM
# - NB: you must manually uncomment the bits you want to keep
#
# NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,
# or manually install git over the top of the OS X version
# NB: this is exclusive with OPTION 1 above
#
#xcuserdata/**/*
# (requires option 2 above): Personal Schemes
#
#!xcuserdata/**/xcschemes/*
####
# Xcode 4 workspaces - more detailed
#
# Workspaces are important! They are a core feature of Xcode - don't exclude them :)
#
# Workspace layout is quite spammy. For reference:
#
# /(root)/
# /(project-name).xcodeproj/
# project.pbxproj
# /project.xcworkspace/
# contents.xcworkspacedata
# /xcuserdata/
# /(your name)/xcuserdatad/
# UserInterfaceState.xcuserstate
# /xcshareddata/
# /xcschemes/
# (shared scheme name).xcscheme
# /xcuserdata/
# /(your name)/xcuserdatad/
# (private scheme).xcscheme
# xcschememanagement.plist
#
#
####
# Xcode 4 - Deprecated classes
#
# Allegedly, if you manually "deprecate" your classes, they get moved here.
#
# We're using source-control, so this is a "feature" that we do not want!
*.moved-aside
####
# OPTIONAL: Some well-known tools that people use side-by-side with Xcode / iOS development
#
# NB: I'd rather not include these here, but gitignore's design is weak and doesn't allow
# modular gitignore: you have to put EVERYTHING in one file.
#
# COCOAPODS:
#
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
#!Podfile.lock
#
# RUBY:
#
# c.f. http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
#
#!Gemfile.lock
#
# IDEA:
#
# c.f. https://www.jetbrains.com/objc/help/managing-projects-under-version-control.html?search=workspace.xml
#
#.idea/workspace.xml
#
# TEXTMATE:
#
# -- UNVERIFIED: c.f. http://stackoverflow.com/a/50283/153422
#
#tm_build_errors
####
# UNKNOWN: recommended by others, but I can't discover what these files are
#
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
I think this will be helpful.
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
applicationVariants.all { variant ->
variant.outputs.each { output ->
project.ext { appName = 'MyAppName' }
def formattedDate = new Date().format('yyyyMMddHHmmss')
def newName = output.outputFile.name
newName = newName.replace("app-", "$project.ext.appName-")
newName = newName.replace("-release", "-release" + formattedDate)
output.outputFile = new File(output.outputFile.parent, newName)
}
}
}
}
productFlavors {
flavor1 {
}
flavor2 {
proguardFile 'flavor2-rules.pro'
}
}
This solution doesn't need web.config file changes or catch-all routes.
First, create a controller like this;
public class ErrorController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Regular Error";
return View();
}
public ActionResult NotFound404()
{
ViewBag.Title = "Error 404 - File not Found";
return View("Index");
}
}
Then create the view under "Views/Error/Index.cshtml" as;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>We're sorry, page you're looking for is, sadly, not here.</p>
Then add the following in the Global asax file as below:
protected void Application_Error(object sender, EventArgs e)
{
// Do whatever you want to do with the error
//Show the custom error page...
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
{
routeData.Values["action"] = "Index";
}
else
{
// Handle 404 error and response code
Response.StatusCode = 404;
routeData.Values["action"] = "NotFound404";
}
Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
errorsController.Execute(rc);
Response.End();
}
If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors>
</httpErrors>
</system.webServer>
Use async and await (es6):
function taskAsync(paramets){
return new Promise((reslove,reject)=>{
//your logic after reslove(respoce) or reject(error)
})
}
async function fName(){
let arry=['list of items'];
for(var i=0;i<arry.length;i++){
let result=await(taskAsync('parameters'));
}
}
If you must, this is how you can do it in a for loop:
mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
endstring += s
but you should consider using join()
:
''.join(mylist)
Divisor
to be non-zeroAssuming the UTC is not included in the string then:
date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00'; //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date; //Should get '2011-01-01 10:00:00 EST' or something like that
Or you could use the DateTime object.
It might be better to see the standard designed by W3.org. Here is the address: http://www.w3.org/
A "DIV" tag can wrap "P" tag whereas, a "P" tag can not wrap "DIV" tag-so far I know this difference. There may be more other differences.
Try calling the image in a <DIV>
tag, which will allow a smoother and faster loading time. Take note that because this is a background image, you can also put text over the image between the <DIV></DIV>
tags. This works great for custom store/shop listings as well...to post a cool " Sold Out! " overlay, or whatever you might want.
Here is the pic/text- sided by side version, which can be used for blog post and article listing:
<div class="whatever_container">
<h2>Title/Header Here</h2>
<div id="image-container-name"style="background-image:url('images/whatever-this-is-named.jpg');background color:#FFFFFF;height:75px;width:20%;float:left;margin:0px 25px 0px 5px;"></div>
<p>All of your text goes here next to the image.</p></div>
I came here because currently the WordPress table block doesn't support the colspan parameter and i thought i will replace it using CSS. This was my solution, assuming that the columns are the same width:
table {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
table td {_x000D_
width: 50%;_x000D_
background: #dbdbdb;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
table tr:nth-child(2n+1) {_x000D_
position:relative;_x000D_
display:block;_x000D_
height:20px;_x000D_
background:green;_x000D_
}_x000D_
_x000D_
table tr:nth-child(2n+1) td {_x000D_
position:absolute;_x000D_
left:0;_x000D_
right:-100%;_x000D_
width: auto;_x000D_
top:0;_x000D_
bottom:0;_x000D_
background:red;_x000D_
text-align:center;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>row</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cell</td>_x000D_
<td>cell</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cell</td>_x000D_
<td>cell</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Create an XML layout first in your project's res/layout/main.xml
folder:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/addBtn"
android:text="Add New Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="addItems"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
</LinearLayout>
This is a simple layout with a button on the top and a list view on the bottom. Note that the ListView
has the id @android:id/list
which defines the default ListView
a ListActivity
can use.
public class ListViewDemo extends ListActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
}
android.R.layout.simple_list_item_1
is the default list item layout supplied by Android, and you can use this stock layout for non-complex things.
listItems
is a List which holds the data shown in the ListView. All the insertion and removal should be done on listItems
; the changes in listItems
should be reflected in the view. That's handled by ArrayAdapter<String> adapter
, which should be notified using:
adapter.notifyDataSetChanged();
An Adapter is instantiated with 3 parameters: the context, which could be your activity/listactivity
; the layout of your individual list item; and lastly, the list, which is the actual data to be displayed in the list.
.crossed {
width: 200px;
height: 200px;
border:solid 1px;
background-color: rgb(210, 137, 226);
background-image: repeating-linear-gradient(
45deg,
transparent,
transparent 15px,
#ccc 10px,
#ccc 20px
),
repeating-linear-gradient(
135deg,
transparent,
transparent 15px,
#ccc 10px,
#ccc 20px
);
}
_x000D_
<div class='crossed'>Hello world</div>
_x000D_
I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.
write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
cmd /c Pause | Out-Null
Read-Host -Prompt "Press Enter to continue"
This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.
Function Pause ($Message = "Press any key to continue . . . ") {
if ((Test-Path variable:psISE) -and $psISE) {
$Shell = New-Object -ComObject "WScript.Shell"
$Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
}
else {
Write-Host -NoNewline $Message
[void][System.Console]::ReadKey($true)
Write-Host
}
}
While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.
Get your Dataset into a List ..... I have a repository pattern and here is an example of getting a dataset from an old school asmx web service private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;
public Get_Client_Repository()
: this(new CISOnlineSRVDEV.ServiceSoapClient())
{
}
public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
{
_ServiceSoapClient = serviceSoapClient;
}
public IEnumerable<IClient> GetClient(IClient client)
{
// **** Calling teh web service with passing in the clientId and returning a dataset
DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
client.ClientId,
client.AhcccsId,
client.LastName,
client.FirstName,
"");//client.BirthDate.ToString()); //TODO: NEED TO FIX
// USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
select new Client()
{
RbhaId = c[5].ToString(),
ClientId = c[2].ToString(),
AhcccsId = c[6].ToString(),
LastName = c[0].ToString(), // Add another field called Sex M/F c[4]
FirstName = c[1].ToString(),
BirthDate = c[3].ToDateTime() //extension helper ToDateTime()
}).ToList<IClient>();
return clients;
}
Then in the Controller I'm doing this
IClient client = (IClient)TempData["Client"];
// Instantiate and instance of the repository
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);
// Call the View up passing in the data from the list
return View(model);
Then in the View it is easy :
@model IEnumerable<CISOnlineMVC.DAL.IClient>
@{
ViewBag.Title = "CLIENT ALL INFORMATION";
}
<h2>CLIENT ALL INFORMATION</h2>
<table>
<tr>
<th></th>
<th>Last Name</th>
<th>First Name</th>
<th>Client ID</th>
<th>DOB</th>
<th>Gender</th>
<th>RBHA ID</th>
<th>AHCCCS ID</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
</td>
<td>
@item.LastName
</td>
<td>
@item.FirstName
</td>
<td>
@item.ClientId
</td>
<td>
@item.BirthDate
</td>
<td>
Gender @* ADD in*@
</td>
<td>
@item.RbhaId
</td>
<td>
@item.AhcccsId
</td>
</tr>
}
</table>
Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :
- offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.
On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :
- clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.
ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:
- scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.
UPDATE: TensorFlow supports Python 3.6 on Windows since version 1.2.0 (see the release notes)
TensorFlow only supports Python 3.5 64-bit as of now. Support for Python 3.6 is a work in progress and you can track it here as well as chime in the discussion.
The only alternative to use Python 3.6 with TensorFlow on Windows currently is building TF from source.
If you don't want to uninstall your Anaconda distribution for Python 3.6 and install a previous release you can create a conda environment for Python=3.5 as in:
conda create --name tensorflow python=3.5
activate tensorflow
pip install tensorflow-gpu
Take a look at this one (c) Tanel Poder
. You may either run it from your glogin.sql (so these settings will update each time you connect, or just run it manually. Notice host title
command - it changes your sql*plus console window title with session information - extremely useful with many windows open simultaneously.
-- the Who am I script
def mysid="NA"
def _i_spid="NA"
def _i_cpid="NA"
def _i_opid="NA"
def _i_serial="NA"
def _i_inst="NA"
def _i_host="NA"
def _i_user="&_user"
def _i_conn="&_connect_identifier"
col i_username head USERNAME for a20
col i_sid head SID for a5 new_value mysid
col i_serial head SERIAL# for a8 new_value _i_serial
col i_cpid head CPID for a15 new_value _i_cpid
col i_spid head SPID for a15 new_value _i_spid
col i_opid head OPID for a5 new_value _i_opid
col i_host_name head HOST_NAME for a25 new_value _i_host
col i_instance_name head INST_NAME for a12 new_value _i_inst
col i_ver head VERSION for a10
col i_startup_day head STARTED for a8
col _i_user noprint new_value _i_user
col _i_conn noprint new_value _i_conn
col i_myoraver noprint new_value myoraver
select
s.username i_username,
i.instance_name i_instance_name,
i.host_name i_host_name,
to_char(s.sid) i_sid,
to_char(s.serial#) i_serial,
(select substr(banner, instr(banner, 'Release ')+8,10) from v$version where rownum = 1) i_ver,
(select substr(substr(banner, instr(banner, 'Release ')+8),
1,
instr(substr(banner, instr(banner, 'Release ')+8),'.')-1)
from v$version
where rownum = 1) i_myoraver,
to_char(startup_time, 'YYYYMMDD') i_startup_day,
p.spid i_spid,
trim(to_char(p.pid)) i_opid,
s.process i_cpid,
s.saddr saddr,
p.addr paddr,
lower(s.username) "_i_user",
upper('&_connect_identifier') "_i_conn"
from
v$session s,
v$instance i,
v$process p
where
s.paddr = p.addr
and
sid = (select sid from v$mystat where rownum = 1);
-- Windows CMD.exe specific stuff
-- host title %CP% &_i_user@&_i_conn [sid=&mysid ser#=&_i_serial spid=&_i_spid inst=&_i_inst host=&_i_host cpid=&_i_cpid opid=&_i_opid]
host title %CP% &_i_user@&_i_conn [sid=&mysid #=&_i_serial]
-- host doskey /exename=sqlplus.exe desc=set lines 80 sqlprompt ""$Tdescribe $*$Tset lines 299 sqlprompt "SQL> "
-- short xterm title
-- host echo -ne "\033]0;&_i_user@&_i_inst &mysid[&_i_spid]\007"
-- long xterm title
--host echo -ne "\033]0;host=&_i_host inst=&_i_inst sid=&mysid ser#=&_i_serial spid=&_i_spid cpid=&_i_cpid opid=&_i_opid\007"
def myopid=&_i_opid
def myspid=&_i_spid
def mycpid=&_i_cpid
-- undef _i_spid _i_inst _i_host _i_user _i_conn _i_cpid
Sample output:
17:39:35 SYSTEM@saz-dev> @sandbox
Connected.
18:29:02 SYSTEM@sandbox> @me
USERNAME INST_NAME HOST_NAME SID SERIAL# VERSION STARTED SPID OPID CPID SADDR PADDR
-------------------- ------------ ------------------------- ----- -------- ---------- -------- --------------- ----- --------------- -------- --------
SYSTEM xe OARS-SANDBOX 34 175 11.2.0.2.0 20130318 3348 30 6108:7776 6F549590 6FF51020
1 row selected.
Elapsed: 00:00:00.04
There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.
Assuming
d <- read.table(text = "263807.0 1582
196190.5 1016
586689.0 3479
")
names(d) <- c("min", "count2.freq")
> d
min count2.freq
1 263807.0 1582
2 196190.5 1016
3 586689.0 3479
To add the desired division as a third variable I would use transform()
> d <- transform(d, new = min / count2.freq)
> d
min count2.freq new
1 263807.0 1582 166.7554
2 196190.5 1016 193.1009
3 586689.0 3479 168.6373
If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want
## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]
## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]
## 3. via `$`
d$new <- d$min / d$count2.freq
All of these can be used at the prompt too, but which is easier to read:
d <- transform(d, new = min / count2.freq)
or
d$new <- d$min / d$count2.freq ## or any of the above examples
Hopefully you think like I do and the first version is better ;-)
The reason we don't use the syntactic sugar of tranform()
et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform()
et al work just fine. But buried in function calls or within a call to one of the apply()
family of functions they can and often do break.
Likewise, be careful using numeric indices (## 2.
above); if you change the ordering of your data, you will select the wrong variables.
If you are just wanting to do the division (rather than insert the result back into the data frame, then use with()
, which allows us to isolate the simple expression you wish to evaluate
> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373
This is again much cleaner code than the equivalent
> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373
as it explicitly states that "using d
, execute the code min / count2.freq
. Your preference may be different to mine, so I have shown all options.
I wonder how many solutions this problem have (or have not), I tried most of the above, nothing worked, the only solution that worked is to set the python language server to Jedi, instead of Microsoft in the settings.json file:
"python.languageServer": "Jedi"
Generate a hash, maybe with a secret only you know, then store it in your DB so it can be associated with the user. Should work quite well.
You can change the hook to wipe everything clean.
# Danger! Wipes local data!
# Remove all local changes to tracked files
git reset --hard HEAD
# Remove all untracked files and directories
git clean -dfx
git pull ...
If the true intent of the question is the comparison between dicts (rather than printing differences), the answer is
dict1 == dict2
This has been mentioned before, but I felt it was slightly drowning in other bits of information. It might appear superficial, but the value comparison of dicts has actually powerful semantics. It covers
The last point again appears trivial, but is acutally interesting as it means that all of this applies recursively to nested dicts as well. E.g.
m1 = {'f':True}
m2 = {'f':True}
m3 = {'a':1, 2:2, 3:m1}
m4 = {'a':1, 2:2, 3:m2}
m3 == m4 # True
Similar semantics exist for the comparison of lists. All of this makes it a no-brainer to e.g. compare deep Json structures, alone with a simple "==".
overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.
overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.
overflow: hidden;
would remove both scrollbars
This is the solution, which is worked for me.
<p:commandButton id="b1" value="Save" process="userGroupSetupForm"
actionListener="#{userGroupSetupController.saveData()}"
update="growl userGroupList userGroupSetupForm" />
Here, process="userGroupSetupForm" atrribute is mandatory for Ajax call. actionListener is calling a method from @ViewScope Bean. Also updating growl message, Datatable: userGroupList and Form: userGroupSetupForm.
There is an explicit cast on CString to LPCTSTR, so you can do (provided unicode is not specified):
CString str;
// ....
const char* cstr = (LPCTSTR)str;
best way is to create an accessor like this:
/**
* @var object $db : map to database connection.
*/
public static $db= null;
/**
* db Function for initializing variable.
* @return object
*/
public static function db(){
if( !isset(static::$db) ){
static::$db= new \Helpers\MySQL( array(
"hostname"=> "localhost",
"username"=> "root",
"password"=> "password",
"database"=> "db_name"
)
);
}
return static::$db;
}
then you can do static::db(); or self::db(); from anywhere.
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
Solution found here : https://sourceforge.net/p/ipt-netflow/bugs-requests-patches/53/
The solution is : $(CURDIR)
You can use it like that :
CUR_DIR = $(CURDIR)
## Start :
start:
cd $(CUR_DIR)/path_to_folder
If you have access to the cross domain server and don't want to make any code changes on server side, you can use a library called - 'xdomain'.
How it works:
Step 1: server 1: include the xdomain library and configure the cross domain as a slave:
<script src="js/xdomain.min.js" slave="https://crossdomain_server/proxy.html"></script>
Step 2: on cross domain server, create a proxy.html file and include server 1 as a master:
proxy.html:
<!DOCTYPE HTML>
<script src="js/xdomain.min.js"></script>
<script>
xdomain.masters({
"https://server1" : '*'
});
</script>
Step 3:
Now, you can make an AJAX call to the proxy.html as endpoint from server1. This is bypass the CORS request. The library internally uses iframe solution which works with Credentials and all possible methods: GET, POST etc.
Query ajax code:
$.ajax({
url: 'https://crossdomain_server/proxy.html',
type: "POST",
data: JSON.stringify(_data),
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.done(_success)
.fail(_failed)
By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.
Ctrl+T in Visual Studio 2017.
Since the beginning, Swift has provided some facilities for making ObjC and C more Swifty, adding more with each version. Now, in Swift 3, the new "import as member" feature lets frameworks with certain styles of C API -- where you have a data type that works sort of like a class, and a bunch of global functions to work with it -- act more like Swift-native APIs. The data types import as Swift classes, their related global functions import as methods and properties on those classes, and some related things like sets of constants can become subtypes where appropriate.
In Xcode 8 / Swift 3 beta, Apple has applied this feature (along with a few others) to make the Dispatch framework much more Swifty. (And Core Graphics, too.) If you've been following the Swift open-source efforts, this isn't news, but now is the first time it's part of Xcode.
Your first step on moving any project to Swift 3 should be to open it in Xcode 8 and choose Edit > Convert > To Current Swift Syntax... in the menu. This will apply (with your review and approval) all of the changes at once needed for all the renamed APIs and other changes. (Often, a line of code is affected by more than one of these changes at once, so responding to error fix-its individually might not handle everything right.)
The result is that the common pattern for bouncing work to the background and back now looks like this:
// Move to a background thread to do some long running work
DispatchQueue.global(qos: .userInitiated).async {
let image = self.loadOrGenerateAnImage()
// Bounce back to the main thread to update the UI
DispatchQueue.main.async {
self.imageView.image = image
}
}
Note we're using .userInitiated
instead of one of the old DISPATCH_QUEUE_PRIORITY
constants. Quality of Service (QoS) specifiers were introduced in OS X 10.10 / iOS 8.0, providing a clearer way for the system to prioritize work and deprecating the old priority specifiers. See Apple's docs on background work and energy efficiency for details.
By the way, if you're keeping your own queues to organize work, the way to get one now looks like this (notice that DispatchQueueAttributes
is an OptionSet
, so you use collection-style literals to combine options):
class Foo {
let queue = DispatchQueue(label: "com.example.my-serial-queue",
attributes: [.serial, .qosUtility])
func doStuff() {
queue.async {
print("Hello World")
}
}
}
Using dispatch_after
to do work later? That's a method on queues, too, and it takes a DispatchTime
, which has operators for various numeric types so you can just add whole or fractional seconds:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
print("Are we there yet?")
}
You can find your way around the new Dispatch API by opening its interface in Xcode 8 -- use Open Quickly to find the Dispatch module, or put a symbol (like DispatchQueue
) in your Swift project/playground and command-click it, then brouse around the module from there. (You can find the Swift Dispatch API in Apple's spiffy new API Reference website and in-Xcode doc viewer, but it looks like the doc content from the C version hasn't moved into it just yet.)
See the Migration Guide for more tips.
Take care to provide only 1 setter and getter for any attribute. The best way to approach is to write down the definition of all the attributes then use eclipse generate setter and getter utility rather than doing it manually. The option comes on right click-> source -> Generate Getter and Setter.
You probably don't want to pass the car
object as a parameter, try just passing car.id
. What do you get when you inspect(params)
after clicking "Add to cart"?
In the docker containers(centos based images) it is located at
/etc/mysql/my.cnf
All,
Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.
step1. 1st stop your databases
service mysqld stop
step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"
vi /etc/my.cnf
[mysqld] skip-grant-tables
step3. 3rd start mysql
service mysqld start
step4. select mysql default database
mysql -u root
mysql>use mysql;
step4. set a new password
mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root'
;
step5 restart mysql database
service mysqld restart
mysql -u root -p
enjoy :)
You can refer related question here - How to make width and height of iframe same as its parent div?
To set dynamic height -
And codes - https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8
you can also use vertice :
private static final int verticesColors[] = {
Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, 0xFF000000, 0xFF000000, 0xFF000000
};
float verts[] = {
point1.x, point1.y, point2.x, point2.y, point3.x, point3.y
};
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, verts.length, verts, 0, null, 0, verticesColors, 0, null, 0, 0, new Paint());