Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I had this problem when moving my .edmx
database first model from one project to another.
I simply did the following:
app.config
or web.config
Best way to make drop down list:
grid.Column("PriceType",canSort:true,header: "PriceType",format: @<span>
<span id="[email protected]">@item.PriceTypeDescription</span>
@Html.DropDownList("PriceType"+(int)item.ShoppingCartID,new SelectList(MvcApplication1.Services.ExigoApiContext.CreateODataContext().PriceTypes.Select(s => new { s.PriceTypeID, s.PriceTypeDescription }).AsEnumerable(),"PriceTypeID", "PriceTypeDescription",Convert.ToInt32(item.PriceTypeId)), new { @class = "PriceType",@style="width:120px;display:none",@selectedvalue="selected"})
</span>),
You want to change the I am working in ABC company.
to I am working in ABC company.
. These are the same strings, so I don't see a reason to, but you can accomplish this by using the JavaScript innerHTML
or textContent
.
element.innerHTML
is a property that defines the HTML inside an element. If you type element.innerHTML = "<strong>This is bold</strong>
, it'll make the text "This is bold" bold text.
element.textContent
, on the other hand, sets the text in an element. If you use element.textContent = "<strong>This is bold</strong>
, The text "This is bold" will not be bold. The user will literally see the text "This is bold
In your case, you can use either one. I'll use .textContent
. The code to change the <p>
element is below.
function get_content(){
document.getElementById("txt").textContent = "I am working in ABC company.";
}
<input type="button" onclick="get_content()" value="Get Content"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>
This, unfortunately, will not change it because it'll change it to the same exact text. You can chance that by changing the string "I am working in ABC company." to something else.
To make all lines taller, to look the same as the line with the superscript, define a larger line-height
for the entire paragraph
<p style='line-height:150%'>
or whatever value gives the effect you desire.
It may look strange, but that's how you described your requirements.
EDIT: In order to make all lines look the same when only one needs more vertical space than the others, ALL lines in the paragraph will have to be taller.
This, as I said, may not an attractive solution. Maybe something can be done with a span making just the text with the sub/superscript smaller, apart from that I don't believe what you want can be achieved. But I'd like to see someone else's solution.
EDIT2: Incidentally, I've tried a small html file containing
<html>
<head>
<title>line-height</title>
<style>
p {
line-height : 1.5em;
width : 25em;
}
</style>
</head>
<body>
<p>Mary had a little lamb, its fleece<sup>1</sup> was white as snow,
and everywhere that Mary went, the lamb<sub>2</sub> was sure to go.
</p>
</body>
</html>
And the lines are all the same height in FF3.0.14 and Konqueror (I can't speak for other browsers)
You can use the below code in the parent page.
<script>
window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}
</script>
here is a working version :
function countbackgrounds() {
var book = SpreadsheetApp.getActiveSpreadsheet();
var range_input = book.getRange("B3:B4");
var range_output = book.getRange("B6");
var cell_colors = range_input.getBackgroundColors();
var color = "#58FA58";
var count = 0;
for( var i in cell_colors ){
Logger.log(cell_colors[i][0])
if( cell_colors[i][0] == color ){ ++count }
}
range_output.setValue(count);
}
Ecu, if you do myObj.a
, then it looks for the property named a of myObj.
If you do myObj[a] =b
then it looks for the a.valueOf()
property of myObj.
rlang::has_name()
can do this too:
foo = list(a = 1, bb = NULL)
rlang::has_name(foo, "a") # TRUE
rlang::has_name(foo, "b") # FALSE. No partial matching
rlang::has_name(foo, "bb") # TRUE. Handles NULL correctly
rlang::has_name(foo, "c") # FALSE
As you can see, it inherently handles all the cases that @Tommy showed how to handle using base R and works for lists with unnamed items. I would still recommend exists("bb", where = foo)
as proposed in another answer for readability, but has_name
is an alternative if you have unnamed items.
EDIT :
According to the ItemAnimator documentation :
This class defines the animations that take place on items as changes are made to the adapter.
So unless you add your items one by one to your RecyclerView
and refresh the view at each iteration, I don't think ItemAnimator
is the solution to your need.
Here is how you can animate the RecyclerView
items when they appear using a CustomAdapter :
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>
{
private Context context;
// The items to display in your RecyclerView
private ArrayList<String> items;
// Allows to remember the last item shown on screen
private int lastPosition = -1;
public static class ViewHolder extends RecyclerView.ViewHolder
{
TextView text;
// You need to retrieve the container (ie the root ViewGroup from your custom_item_layout)
// It's the view that will be animated
FrameLayout container;
public ViewHolder(View itemView)
{
super(itemView);
container = (FrameLayout) itemView.findViewById(R.id.item_layout_container);
text = (TextView) itemView.findViewById(R.id.item_layout_text);
}
}
public CustomAdapter(ArrayList<String> items, Context context)
{
this.items = items;
this.context = context;
}
@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_item_layout, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
holder.text.setText(items.get(position));
// Here you apply the animation when the view is bound
setAnimation(holder.itemView, position);
}
/**
* Here is the key method to apply the animation
*/
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
}
And your custom_item_layout would look like this :
<FrameLayout
android:id="@+id/item_layout_container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/item_layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
</FrameLayout>
For more information about CustomAdapters and RecyclerView
, refer to this training on the official documentation.
Problems on fast scroll
Using this method could cause problems with fast scrolling. The view could be reused while the animation is been happening. In order to avoid that is recommendable to clear the animation when is detached.
@Override
public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder)
{
((CustomViewHolder)holder).clearAnimation();
}
On CustomViewHolder:
public void clearAnimation()
{
mRootLayout.clearAnimation();
}
Old answer :
Give a look at Gabriele Mariotti's repo, I'm pretty sure you'll find what you need. He provides simple ItemAnimators for the RecyclerView, such as SlideInItemAnimator or SlideScaleItemAnimator.
<VirtualHost *:80>
ServerName www.YOURDOMAIN.COM
ServerAlias YOURDOMAIN.COM
DocumentRoot /var/www/YOURDOMAIN.COM/public_html
ErrorLog /var/www/YOURDOMAIN.COM/error.log
CustomLog /var/www/YOURDOMAIN.COM/requests.log combined
DocumentRoot /var/www/YOURDOMAIN.COM/public_html
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/YOURDOMAIN.COM/public_html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
In case you need to check against any amount of whitespace, not just single space, you can do this:
To strip string of extra white space (also condences whitespace in the middle to one space):
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
The infix operator %>%
is not part of base R, but is in fact defined by the package magrittr
(CRAN) and is heavily used by dplyr
(CRAN).
It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.
What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris
gets passed to head()
:
library(magrittr)
iris %>% head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
Thus, iris %>% head()
is equivalent to head(iris)
.
Often, %>%
is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris
is passed to head()
, then the result of that is passed to summary()
.
iris %>% head() %>% summary()
Thus iris %>% head() %>% summary()
is equivalent to summary(head(iris))
. Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.
Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:
var array = [];
calendars.forEach(function(item) {
array.push(item.id);
});
console.log(array);
You can also use the map()
method to generate an Array filled with the results of calling the specified function on each element. Something like:
var array = calendars.map(function(item) {
return item.id;
});
console.log(array);
And, since ECMAScript 2015 has been released, you may start seeing examples using let
or const
instead of var
and the =>
syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):
let array = calendars.map(item => item.id);
console.log(array);
try like this (no pun intended btw)
script {
try {
sh 'do your stuff'
} catch (Exception e) {
echo 'Exception occurred: ' + e.toString()
sh 'Handle the exception!'
}
}
The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)
No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>
function search() {_x000D_
var Blah = document.getElementById("Blah").value;_x000D_
location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
}
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
Here's a tricky way to do this - select the cells that you want to replace and in Excel 2010 select F5 to bring up the "goto" box. Hit the "special" button. Select "blanks" - this should select all the cells that are blank. Enter NULL or whatever you want in the formula box and hit ctrl + enter to apply to all selected cells. Easy!
Return response headers with a reference parameter:
<?php
$data=array('device_token'=>'5641c5b10751c49c07ceb4',
'content'=>'????test'
);
$rtn=curl_to_host('POST', 'http://test.com/send_by_device_token', array(), $data, $resp_headers);
echo $rtn;
var_export($resp_headers);
function curl_to_host($method, $url, $headers, $data, &$resp_headers)
{$ch=curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $GLOBALS['POST_TO_HOST.LINE_TIMEOUT']?$GLOBALS['POST_TO_HOST.LINE_TIMEOUT']:5);
curl_setopt($ch, CURLOPT_TIMEOUT, $GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']?$GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']:20);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, 1);
if ($method=='POST')
{curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
foreach ($headers as $k=>$v)
{$headers[$k]=str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $k)))).': '.$v;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$rtn=curl_exec($ch);
curl_close($ch);
$rtn=explode("\r\n\r\nHTTP/", $rtn, 2); //to deal with "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK...\r\n\r\n..." header
$rtn=(count($rtn)>1 ? 'HTTP/' : '').array_pop($rtn);
list($str_resp_headers, $rtn)=explode("\r\n\r\n", $rtn, 2);
$str_resp_headers=explode("\r\n", $str_resp_headers);
array_shift($str_resp_headers); //get rid of "HTTP/1.1 200 OK"
$resp_headers=array();
foreach ($str_resp_headers as $k=>$v)
{$v=explode(': ', $v, 2);
$resp_headers[$v[0]]=$v[1];
}
return $rtn;
}
?>
CASE course_enrollment_settings.base_price
is wrong here, it should be just CASE
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
WHEN course_enrollment_settings.base_price<101 THEN 2
WHEN course_enrollment_settings.base_price>100 AND
course_enrollment_settings.base_price<201 THEN 3
ELSE 6
END AS 'calc_base_price',
course_enrollment_settings.base_price
FROM
course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0
Some explanations. Your original query will be executed as :
SELECT
CASE 0
WHEN 0=0 THEN 1 -- condition evaluates to 1, then 0 (from CASE 0)compares to 1 - false
WHEN 0<1 THEN 2 -- condition evaluates to 1,then 0 (from CASE 0)compares to 1 - false
WHEN 0>100 and 0<201 THEN 3 -- evaluates to 0 ,then 0 (from CASE 0)compares to 0 - true
ELSE 6, ...
it's why you always get 3
After declaring the base url in config.php, (note, if you are still getting the same error, check autoload.php)
$config['base_url'] = "http://somesite.com/somedir/";
Check "autoload"
CodeIgniter file structure:
\application\config\autoload.php
And enable on autoload:
$autoload['helper'] = array(**'url',** 'file');
And it works.
If you need a counter in an for-each loop you have to count yourself. There is no built in counter as far as I know.
Nested fragments are not currently supported. Trying to put a fragment within the UI of another fragment will result in undefined and likely broken behavior.
Update: Nested fragments are supported as of Android 4.2 (and Android Support Library rev 11) : http://developer.android.com/about/versions/android-4.2.html#NestedFragments
NOTE (as per this docs): "Note: You cannot inflate a layout into a fragment when that layout includes a <fragment>
. Nested fragments are only supported when added to a fragment dynamically."
Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.
WAMP [ Windows, Apache, Mysql, Php]
XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS )
Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports.
WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP.
XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. )
IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.
With includes()
, no, but you can achieve the same thing with REGEX via test()
:
var value = /hello|hi|howdy/.test(str);
Or, if the words are coming from a dynamic source:
var words = array('hello', 'hi', 'howdy');
var value = new RegExp(words.join('|')).test(str);
The REGEX approach is a better idea because it allows you to match the words as actual words, not substrings of other words. You just need the word boundary marker \b
, so:
var str = 'hilly';
var value = str.includes('hi'); //true, even though the word 'hi' isn't found
var value = /\bhi\b/.test(str); //false - 'hi' appears but not as its own word
Just additional information to you guys:
take a look at the section "MP3 stuff and Metadata editors" in the page of PythonInMusic.
You can try like this:
Sum({Tablename.Columnname})
It will work without creating a summarize field in formulae.
Image class has PropertyItems and PropertyIdList properties. You can use them.
From Wikipedia (granularity):
Granularity is the extent to which a system is broken down into small parts, either the system itself or its description or observation. It is the extent to which a larger entity is subdivided. For example, a yard broken into inches has finer granularity than a yard broken into feet.
Coarse-grained systems consist of fewer, larger components than fine-grained systems; a coarse-grained description of a system regards large subcomponents while a fine-grained description regards smaller components of which the larger ones are composed.
This works for me in irb:
irb> (1..4).to_a
=> [1, 2, 3, 4]
I notice that:
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
from (irb):1
So perhaps you are missing the parentheses?
(I am running Ruby 1.8.6 patchlevel 114)
A FragmentActivity
is a subclass of Activity
that was built for the Android Support Package.
The FragmentActivity
class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager()
and getFragmentManager()
to getSupportLoaderManager()
and getSupportFragmentManager()
respectively.
Essentially console.log("Put a message here.")
if the browser has a supporting console.
Another typical debugging method is using alerts, alert("Put a message here.")
RE: Update II
This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.
Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print()
method for evaluating expressions and printing them out. Checkout this documentation.
These links might be of interest to you.
You can use this function
function getParmFromUrl(url, parm) {
var re = new RegExp(".*[?&]" + parm + "=([^&]+)(&|$)");
var match = url.match(re);
return(match ? match[1] : "");
}
Sometimes it's easier to do all the appending outside of pandas, then, just create the DataFrame in one shot.
>>> import pandas as pd
>>> simple_list=[['a','b']]
>>> simple_list.append(['e','f'])
>>> df=pd.DataFrame(simple_list,columns=['col1','col2'])
col1 col2
0 a b
1 e f
1 - Treat functions as objects.
2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.
The -H 'Cache-Control: no-cache'
argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.
curl "http://www.example.com?foo123"
You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s
, which will return the seconds since epoch.
curl "http://www.example.com?$(date +%s)"
iReports Custom Fields for columns (sum, average, etc)
Right-Click on Variables and click Create Variable
Click on the new variable
a. Notice the properties on the right
Rename the variable accordingly
Change the Value Class Name to the correct Data Type
a. You can search by clicking the 3 dots
Select the correct type of calculation
Change the Expression
a. Click the little icon
b. Select the column you are looking to do the calculation for
c. Click finish
Set Initial Value Expression to 0
Set the increment type to none
Set the Reset Type (usually report)
Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)
Select the new variable
Click finish
I have the following 2 suggested ways:
You can use isDisplayed()
as below:
driver.findElement(By.id("idOfElement")).isDisplayed();
You can define a method as shown below and call it:
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
}
catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
Now, you can do assertion as below to check either the element is present or not:
assertTrue(isElementPresent(By.id("idOfElement")));
Peg the pattern to find "\\.dbf"
at the end of the string using the $
character:
list.files(pattern = "\\.dbf$")
What is an authentication_token ?
This is a random string used by rails application to make sure that the user is requesting or performing an action from the app page, not from another app or site.
Why is an authentication_token is necessary ?
To protect your app or site from cross-site request forgery.
How to add an authentication_token to a form ?
If you are generating a form using form_for tag an authentication_token is automatically added else you can use <%= csrf_meta_tag %>
.
Just check: where value > '' -- not null and not empty
-- COLUMN CONTAINS A VALUE (ie string not null and not empty) :
-- (note: "<>" gives a different result than ">")
select iif(null > '', 'true', 'false'); -- false (null)
select iif('' > '', 'true', 'false'); -- false (empty string)
select iif(' ' > '', 'true', 'false'); -- false (space)
select iif(' ' > '', 'true', 'false'); -- false (tab)
select iif('
' > '', 'true', 'false'); -- false (newline)
select iif('xxx' > '', 'true', 'false'); -- true
--
--
-- NOTE - test that tab and newline is processed as expected:
select 'x x' -- tab
select 'x
x' -- newline
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode
method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
C or C++ does not provide this functionality, although I've needed it often.
The following code works, although it's best suited for non-sparse enums.
typedef enum { ONE, TWO, THREE } Numbers;
char *strNumbers[] = {"one","two","three"};
printf ("Value for TWO is %s\n",strNumbers[TWO]);
By non-sparse, I mean not of the form
typedef enum { ONE, FOUR_THOUSAND = 4000 } Numbers;
since that has huge gaps in it.
The advantage of this method is that it put the definitions of the enums and strings near each other; having a switch statement in a function spearates them. This means you're less likely to change one without the other.
You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.
Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html
The su
command does not execute anything, it just raise your privileges.
Try adb shell su -c YOUR_COMMAND
.
Had this problem in vs2017, I already got MVC via nuget but System.Web.Mvc didn't appear in the "Assemblies" list under "Add Reference".
The solution was to select "Extensions" under "Assemblies" in the "Add Reference" dialog.
If you want to print/write double value at console then use System.out.printf()
or System.out.format()
methods.
System.out.printf("\n$%10.2f",shippingCost);
System.out.printf("%n$%.2f",shippingCost);
Now a day use of gravity start
is best choise:
android:gravity="start"
For EditText (textarea):
<EditText
android:id="@+id/EditText02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="start"
android:inputType="textMultiLine"
/>
Spinner xml:
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
java:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private Spinner spinner;
private static final String[] paths = {"item 1", "item 2", "item 3"};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item,paths);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
switch (position) {
case 0:
// Whatever you want to happen when the first item gets selected
break;
case 1:
// Whatever you want to happen when the second item gets selected
break;
case 2:
// Whatever you want to happen when the thrid item gets selected
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
The reason that the error is occuring is because all the files are not being recognized as being in the same project directory. The easiest way to fix this is to simply create a new project.
File -> Project -> Console application -> Next -> select C or C++ -> Name the project and select the folder to create the project in -> then click finish.
Then to create the class and header files by clicking New -> Class. Give the class a name and uncheck "Use relative path." Make sure you are creating the class and header file in the same project folder.
After these steps, the left side of the IDE will display the Sources and Headers folders, with main.cpp, theclassname.cpp, and theclassname.h all conviently arranged.
I don't know about performance difference, but as you say, static nested class is not a part of an instance of the enclosing class. Seems just simpler to create a static nested class unless you really need it to be an inner class.
It's a bit like why I always make my variables final in Java - if they're not final, I know there's something funny going on with them. If you use an inner class instead of a static nested class, there should be a good reason.
This is a nice 5-minute screencast on how to do long polling using PHP & jQuery: http://screenr.com/SNH
Code is quite similar to dbr's example above.
INSERT INTO vendors (
name,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country,
customer_id
)
SELECT
name,
phone,
addressLine1,
addressLine2,
city,
state ,
postalCode,
country,
customer_id
FROM
customers;
If you're lucky enough to only support python 3.x, this really becomes a thing of beauty :)
We can chain the exceptions using raise from.
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('Smelly socks') from e
In this case, the exception your caller would catch has the line number of the place where we raise our exception.
Traceback (most recent call last):
File "test.py", line 2, in <module>
1 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise Exception('Smelly socks') from e
Exception: Smelly socks
Notice the bottom exception only has the stacktrace from where we raised our exception. Your caller could still get the original exception by accessing the __cause__
attribute of the exception they catch.
Or you can use with_traceback.
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('Smelly socks').with_traceback(e.__traceback__)
Using this form, the exception your caller would catch has the traceback from where the original error occurred.
Traceback (most recent call last):
File "test.py", line 2, in <module>
1 / 0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise Exception('Smelly socks').with_traceback(e.__traceback__)
File "test.py", line 2, in <module>
1 / 0
Exception: Smelly socks
Notice the bottom exception has the line where we performed the invalid division as well as the line where we reraise the exception.
There isn't one.
I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.
I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).
Update 2012
I've changed how I program over time. I now use camel case (thisIsASelector
) instead of hyphens now; I find the latter rather ugly. Use whatever you prefer, which may easily change over time.
Update 2013
It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn't a standard.
Update 2015
An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case
. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.
Update 2016 (you asked for it)
I've adopted the BEM standard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actually a standard (so my no
becomes a yes
perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.
Update 2019 (you asked for it)
After writing no CSS for quite a while, I started working at a place that uses OOCSS in one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.
I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.
OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromises because CSS just isn't that good.
Update 2020
A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.
Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:
SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;
So we have a table called Jokes with columns JScore and JDate.
You don't need to wrap it in a list with [..]
, just provide the subselection of the columns index:
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
as the index object is already regarded as list-like.
If you're recompiling a disassembled APK
with APK tool:
Just Set Memory Allocation a little bigger
set switch -Xmx1024m
to -Xmx2048m
java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"
you're good to go.. :)
You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload
From the Fragment
documentation:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
So I suggest you have look on the basic fragment training docs in the documentation. They're pretty comprehensive with an example and a walk-through guide.
In the Solution Explorer window, right click the project you want to use your class library from and click the 'Add Reference' menu item. Then if the class library is in the same solution file, go to the projects tab and select it; if it's not in the same tab, you can go to the Browse tab and find it that way.
Then you can use anything in that assembly.
There is also another easy way to check the latest version without going to NPM if you are using VS Code.
In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions
Below are the reasons of Error: redirect_uri_mismatch issue occurs :
Recommended to use domain URL
In Charles, go to Proxy>>Proxy Settings and select the SSL tab. Add your host to the list of Locations.
For example, if your secure call is going to https://secure.example.com, you can enter secure.example.com, or *.example.com.
Once the above is in place, you may need to right-click on the call in the main Charles window and select the SSL Proxying option.
Hope this helps.
To cite the Zen of Python:
Readability counts.
For example, Python 3.7 introduced dataclasses and Python 3.8 introduced fstring =.
There might be other features in Python 3.7 and Python 3.8 which are more important to you. The point is that PyPy does not support Python 3.7 or Python 3.8 at the moment.
Shameless self-advertisement: Killer Features by Python version - if you want to know more things you miss by using older Python versions
onSaveInstanceState()
is a method used to store data before pausing the activity.Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.
onRestoreInstanceState()
is method used to retrieve that data back.Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).
Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause()
method of Activity as a bundle & in onResume()
method call the onRestoreInstanceState()
method .
Please see :
How to use onSavedInstanceState example please
http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/
The Windows "AT" command is very similar to cron. It is available through the command line.
Lets assume you want a data frame with the following schema:
root
|-- k: string (nullable = true)
|-- v: integer (nullable = false)
You simply define schema for a data frame and use empty RDD[Row]
:
import org.apache.spark.sql.types.{
StructType, StructField, StringType, IntegerType}
import org.apache.spark.sql.Row
val schema = StructType(
StructField("k", StringType, true) ::
StructField("v", IntegerType, false) :: Nil)
// Spark < 2.0
// sqlContext.createDataFrame(sc.emptyRDD[Row], schema)
spark.createDataFrame(sc.emptyRDD[Row], schema)
PySpark equivalent is almost identical:
from pyspark.sql.types import StructType, StructField, IntegerType, StringType
schema = StructType([
StructField("k", StringType(), True), StructField("v", IntegerType(), False)
])
# or df = sc.parallelize([]).toDF(schema)
# Spark < 2.0
# sqlContext.createDataFrame([], schema)
df = spark.createDataFrame([], schema)
Using implicit encoders (Scala only) with Product
types like Tuple
:
import spark.implicits._
Seq.empty[(String, Int)].toDF("k", "v")
or case class:
case class KV(k: String, v: Int)
Seq.empty[KV].toDF
or
spark.emptyDataset[KV].toDF
It's a great idea to use cURL as suggested by rojoca.
Here is an example. You can monitor text.txt while the script is running in background:
<?php
function doCurl($begin)
{
echo "Do curl<br />\n";
$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = preg_replace('/\?.*/', '', $url);
$url .= '?begin='.$begin;
echo 'URL: '.$url.'<br>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo 'Result: '.$result.'<br>';
curl_close($ch);
}
if (empty($_GET['begin'])) {
doCurl(1);
}
else {
while (ob_get_level())
ob_end_clean();
header('Connection: close');
ignore_user_abort();
ob_start();
echo 'Connection Closed';
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
$begin = $_GET['begin'];
$fp = fopen("text.txt", "w");
fprintf($fp, "begin: %d\n", $begin);
for ($i = 0; $i < 15; $i++) {
sleep(1);
fprintf($fp, "i: %d\n", $i);
}
fclose($fp);
if ($begin < 10)
doCurl($begin + 1);
}
?>
Quite simple, with a *
wildcard.
cp -r Folder1/* Folder2/
But according to your example recursion is not needed so the following will suffice:
cp Folder1/* Folder2/
EDIT:
Or skip the mkdir Folder2
part and just run:
cp -r Folder1 Folder2
With all due respect to other posts, you have here a very simple solution, using CSS3 and jQuery, without using any further external resources nor files.
$('#submit').click(function(){_x000D_
$(this).addClass('button_loader').attr("value","");_x000D_
window.setTimeout(function(){_x000D_
$('#submit').removeClass('button_loader').attr("value","\u2713");_x000D_
$('#submit').prop('disabled', true);_x000D_
}, 3000);_x000D_
});
_x000D_
#submit:focus{_x000D_
outline:none;_x000D_
outline-offset: none;_x000D_
}_x000D_
_x000D_
.button {_x000D_
display: inline-block;_x000D_
padding: 6px 12px;_x000D_
margin: 20px 8px;_x000D_
font-size: 14px;_x000D_
font-weight: 400;_x000D_
line-height: 1.42857143;_x000D_
text-align: center;_x000D_
white-space: nowrap;_x000D_
vertical-align: middle;_x000D_
-ms-touch-action: manipulation;_x000D_
cursor: pointer;_x000D_
-webkit-user-select: none;_x000D_
-moz-user-select: none;_x000D_
-ms-user-select: none;_x000D_
background-image: none;_x000D_
border: 2px solid transparent;_x000D_
border-radius: 5px;_x000D_
color: #000;_x000D_
background-color: #b2b2b2;_x000D_
border-color: #969696;_x000D_
}_x000D_
_x000D_
.button_loader {_x000D_
background-color: transparent;_x000D_
border: 4px solid #f3f3f3;_x000D_
border-radius: 50%;_x000D_
border-top: 4px solid #969696;_x000D_
border-bottom: 4px solid #969696;_x000D_
width: 35px;_x000D_
height: 35px;_x000D_
-webkit-animation: spin 0.8s linear infinite;_x000D_
animation: spin 0.8s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin {_x000D_
0% { -webkit-transform: rotate(0deg); }_x000D_
99% { -webkit-transform: rotate(360deg); }_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
0% { transform: rotate(0deg); }_x000D_
99% { transform: rotate(360deg); }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="submit" class="button" type="submit" value="Submit" />
_x000D_
You can get the current timestamp appended with a file extension in the following way:
String fileName = new Date().getTime() + ".txt";
Where A
is your 2D array:
import numpy as np
A[np.isnan(A)] = 0
The function isnan
produces a bool array indicating where the NaN
values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.
The quick generic answer:
std::vector<double> vec(carray,carray+carray_size);
or question specific:
std::vector<double> w_(w,w+len);
based on above: Don't forget that you can treat pointers as iterators
Try this:
string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
It took far too long but I finally found this document on Migrating MSBuild-Integrated solutions to Automatic Package Restore and I was able to resolve the issue using the methods described here.
'.nuget'
solution directory along from the solutionnuget.targets
from your .csproj
or .vbproj
files. Though not officially supported, the document links to a PowerShell script if you have a lot of projects which need to be cleaned up. I manually edited mine by hand so I can't give any feedback regarding my experience with it.When editing your files by hand, here's what you'll be looking for:
Solution File (.sln)
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{F4AEBB8B-A367-424E-8B14-F611C9667A85}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.exe = .nuget\NuGet.exe
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Project File (.csproj / .vbproj)
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
Vim's <leader>
key is a way of creating a namespace for commands you want to define. Vim already maps most keys and combinations of Ctrl + (some key), so <leader>(some key)
is where you (or plugins) can add custom behavior.
For example, if you find yourself frequently deleting exactly 3 words and 7 characters, you might find it convenient to map a command via nmap <leader>d 3dw7x
so that pressing the leader key followed by d will delete 3 words and 7 characters. Because it uses the leader key as a prefix, you can be (relatively) assured that you're not stomping on any pre-existing behavior.
The default key for <leader>
is \
, but you can use the command :let mapleader = ","
to remap it to another key (,
in this case).
Usevim's page on the leader key has more information.
I found some of the solutions here to be slow and/or confusing (and some of them don't handle ties correctly) so I wrote my own data.table
based function auc_roc() in my R package mltools.
library(data.table)
library(mltools)
preds <- c(.1, .3, .3, .9)
actuals <- c(0, 0, 1, 1)
auc_roc(preds, actuals) # 0.875
auc_roc(preds, actuals, returnDT=TRUE)
Pred CountFalse CountTrue CumulativeFPR CumulativeTPR AdditionalArea CumulativeArea
1: 0.9 0 1 0.0 0.5 0.000 0.000
2: 0.3 1 1 0.5 1.0 0.375 0.375
3: 0.1 1 0 1.0 1.0 0.500 0.875
You can also solve this problem by creating an array of values and assigning that array:
newheaders <- c("a", "b", "c", ... "x")
colnames(data) <- newheaders
For Python 3 the following will work.
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
Try
$(document).on('change','#multiid',function(){
alert('Change Happened');
});
As your select-box is generated from the code, so you have to use event delegation, where in place of $(document)
you can have closest parent element.
Or
$(document.body).on('change','#multiid',function(){
alert('Change Happened');
});
Update:
Second one works fine, there is another change of selector to make it work.
$('#addbasket').on('change','#multiid',function(){
alert('Change Happened');
});
Ideally we should use $("#addbasket")
as it's the closest parent element [As i have mentioned above].
Add this to the scope - https://www.googleapis.com/auth/userinfo.profile
And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json
It has loads of stuff - including name, public profile url, gender, photo etc.
My awk-less, sed-less, Perl-less, Python-less POSIX-compliant alternative:
find . -type f | rev | cut -d. -f1 | rev | tr '[:upper:]' '[:lower:]' | sort | uniq --count | sort -rn
The trick is that it reverses the line and cuts the extension at the beginning.
It also converts the extensions to lower case.
Example output:
3689 jpg
1036 png
610 mp4
90 webm
90 mkv
57 mov
12 avi
10 txt
3 zip
2 ogv
1 xcf
1 trashinfo
1 sh
1 m4v
1 jpeg
1 ini
1 gqv
1 gcs
1 dv
If using a BeansWrapper with an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:
For example, the following will work in Freemarker (since at least version 2.3.19):
<#list map.entrySet() as entry>
<input type="hidden" name="${entry.key}" value="${entry.value}" />
</#list>
In Struts2, for instance, an extension of the BeanWrapper is used with the exposure level defaulted to allow this manner of iteration.
There is no hex code for transparency. For CSS, you can use either transparent
or rgba(0, 0, 0, 0)
.
Follow the above image to edit rows from 200 to 100,000 Rows
Check out the request module.
It's more full featured than node's built-in http client.
var request = require('request');
var propertiesObject = { field1:'test1', field2:'test2' };
request({url:url, qs:propertiesObject}, function(err, response, body) {
if(err) { console.log(err); return; }
console.log("Get response: " + response.statusCode);
});
Just to add. If you right-click on an eclipse project and select Properties
, select the Java Build Path
link on the left. Then select the Source
Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src
folder is the classpath folder.
Use the below code in your rounded_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="1dp"
android:color="#2f6699" />
<corners
android:radius="10dp"
/>
</shape>
This should work
The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..
E.g.
a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}
I normally set paths in
~/.bashrc
However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7
and it was sufficient for me.
you can also define multiple java_home's and have only one of them active (rest commented).
suppose in your bashrc file, you have
export JAVA_HOME=......jdk1.7
#export JAVA_HOME=......jdk1.8
notice 1.8 is commented. Once you do
source ~/.bashrc
jdk1.7 will be in path.
you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.
If you have Div as follows in one Iframe
<iframe id="ifrmReportViewer" name="ifrmReportViewer" frameborder="0" width="980"
<div id="EndLetterSequenceNoToShow" runat="server"> 11441551 </div> Or
<form id="form1" runat="server">
<div style="clear: both; width: 998px; margin: 0 auto;" id="divInnerForm">
Some Text
</div>
</form>
</iframe>
Then you can find the text of those Div using the following code
var iContentBody = $("#ifrmReportViewer").contents().find("body");
var endLetterSequenceNo = iContentBody.find("#EndLetterSequenceNoToShow").text();
var divInnerFormText = iContentBody.find("#divInnerForm").text();
I hope this will help someone.
How can I set the TTL/TTI/Eviction policy/XXX feature?
Directly through your cache provider. The cache abstraction is... well, an abstraction not a cache implementation
So, if you use EHCache, use EHCache's configuration to configure the TTL.
You could also use Guava's CacheBuilder to build a cache, and pass this cache's ConcurrentMap view to the setStore method of the ConcurrentMapCacheFactoryBean.
Providing you know these vim commands:
1G -> go to first line in file
G -> go to last line in file
then, the following make more sense, are more unitary and easier to remember IMHO:
d1G -> delete starting from the line you are on, to the first line of file
dG -> delete starting from the line you are on, to the last line of file
Cheers.
For the record: The following snippet can help you to get details about input, textarea, select, button, a tags through a temp title when hover them.
$( 'body' ).on( 'mouseover', 'input, textarea, select, button, a', function() {
var $tag = $( this );
var $form = $tag.closest( 'form' );
var title = this.title;
var id = this.id;
var name = this.name;
var value = this.value;
var type = this.type;
var cls = this.className;
var tagName = this.tagName;
var options = [];
var hidden = [];
var formDetails = '';
if ( $form.length ) {
$form.find( ':input[type="hidden"]' ).each( function( index, el ) {
hidden.push( "\t" + el.name + ' = ' + el.value );
} );
var formName = $form.prop( 'name' );
var formTitle = $form.prop( 'title' );
var formId = $form.prop( 'id' );
var formClass = $form.prop( 'class' );
formDetails +=
"\n\nFORM NAME: " + formName +
"\nFORM TITLE: " + formTitle +
"\nFORM ID: " + formId +
"\nFORM CLASS: " + formClass +
"\nFORM HIDDEN INPUT:\n" + hidden.join( "\n" );
}
var tempTitle =
"TAG: " + tagName +
"\nTITLE: " + title +
"\nID: " + id +
"\nCLASS: " + cls;
if ( 'SELECT' === tagName ) {
$tag.find( 'option' ).each( function( index, el ) {
options.push( el.value );
} );
tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type +
"\nSELECT OPTIONS:\n\t" + options;
} else if ( 'A' === tagName ) {
tempTitle +=
"\nHTML: " + $tag.html();
} else {
tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type;
}
tempTitle += formDetails;
$tag.prop( 'title', tempTitle );
$tag.on( 'mouseout', function() {
$tag.prop( 'title', title );
} )
} );
There is a free nuget package (Pdf2Image), which allows the extraction of pdf pages to jpg files or to a collection of images (List ) in just one line
string file = "c:\\tmp\\test.pdf";
List<System.Drawing.Image> images = PdfSplitter.GetImages(file, PdfSplitter.Scale.High);
PdfSplitter.WriteImages(file, "c:\\tmp", PdfSplitter.Scale.High, PdfSplitter.CompressionLevel.Medium);
All source is also available on github Pdf2Image
Firebase stores a sequence of values in this format:
"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1"
"-K-Y_RqDV_zbNLPJYnOA": "Value 2"
"-K-Y_SBoKvx6gAabUPDK": "Value 3"
If that is how you have them, you are getting the wrong type. The above structure is represented as a Map
, not as a List
:
mFirebaseRef = new Firebase(FIREBASE_URL);
mFirebaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
List<Object> values = td.values();
//notifyDataSetChanged();
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Anaconda comes with the conda
package manager which is designed to handle these kinds of upgrades. Start by updating conda itself to get the most recent package lists:
conda update conda
And then install the version of scikit-learn you want
conda install scikit-learn=0.17
All necessary dependencies will be upgraded as well. If you have trouble with conda on Windows, there are some relevant FAQ here: http://docs.continuum.io/anaconda/faq
Zero
=> Everything Okay
Positive
=> Something I expected could potentially go wrong went wrong (bad command-line, can't find file, could not connect to server)
Negative
=> Something I didn't expect at all went wrong (system error - unanticipated exception - externally forced termination e.g. kill -9
)
(values greater than 128 are actually negative, if you regard them as 8-bit signed binary, or twos complement)
There's a load of good standard exit-codes here
Another solution:
public class CountryInfoResponse {
private List<Object> geonames;
}
Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.
Inspired by Radek and Spencer... On Rails 4(.0.2 - Ruby 2.1.0 ), I was able to append this to config/boot.rb:
# config/boot.rb
# ...existing code
require 'rails/commands/server'
module Rails
# Override default development
# Server port
class Server
def default_options
super.merge(Port: 3100)
end
end
end
All other configuration in default_options are still set, and command-line switches still override defaults.
You can try with following command:
sudo service mongod start
Move semantics is about transferring resources rather than copying them when nobody needs the source value anymore.
In C++03, objects are often copied, only to be destroyed or assigned-over before any code uses the value again. For example, when you return by value from a function—unless RVO kicks in—the value you're returning is copied to the caller's stack frame, and then it goes out of scope and is destroyed. This is just one of many examples: see pass-by-value when the source object is a temporary, algorithms like sort
that just rearrange items, reallocation in vector
when its capacity()
is exceeded, etc.
When such copy/destroy pairs are expensive, it's typically because the object owns some heavyweight resource. For example, vector<string>
may own a dynamically-allocated memory block containing an array of string
objects, each with its own dynamic memory. Copying such an object is costly: you have to allocate new memory for each dynamically-allocated blocks in the source, and copy all the values across. Then you need deallocate all that memory you just copied. However, moving a large vector<string>
means just copying a few pointers (that refer to the dynamic memory block) to the destination and zeroing them out in the source.
First of all, that's a forward slash. And no, you can't have any in regexes unless you escape them. To escape them, put a backslash (\
) in front of it.
someString.replace(/\//g, "-");
From your description I assume you are on windows machine and your home is abc
So Now : Cause
When you run this command
keytool -genkey -alias tomcat -keyalg RSA
because you are not specifying an explicit keystore it will try to generate (and in your case as you are getting exception so to update) keystore C:\users\abc>.keystore
and of course you need to provide old password for .keystore while I believe you are providing your version (a new one).
Solution
Either delete .keystore
from C:\users\abc>
location and try the command
or try following command which will create a new xyzkeystore:
keytool -genkey -keystore xyzkeystore -alias tomcat -keyalg RSA
Note: -genkey
is old now rather use -genkeypair
althought both work equally.
This is a slight touch up to Glen Maynard's solution, which I think is the right way to do it. It just adds the padding element.
def hextobin(self, hexval):
'''
Takes a string representation of hex data with
arbitrary length and converts to string representation
of binary. Includes padding 0s
'''
thelen = len(hexval)*4
binval = bin(int(hexval, 16))[2:]
while ((len(binval)) < thelen):
binval = '0' + binval
return binval
Pulled it out of a class. Just take out self,
if you're working in a stand-alone script.
My UI has a vertical scrolling list of thumbs within a thumbbar The goal was to make the current thumb right in the center of the thumbbar. I started from the approved answer, but found that there were a few tweaks to truly center the current thumb. hope this helps someone else.
markup:
<ul id='thumbbar'>
<li id='thumbbar-123'></li>
<li id='thumbbar-124'></li>
<li id='thumbbar-125'></li>
</ul>
jquery:
// scroll the current thumb bar thumb into view
heightbar = $('#thumbbar').height();
heightthumb = $('#thumbbar-' + pageid).height();
offsetbar = $('#thumbbar').scrollTop();
$('#thumbbar').animate({
scrollTop: offsetthumb.top - heightbar / 2 - offsetbar - 20
});
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
Old question, but I had this issue as well, so after assigning the Text property, calling Refresh()
will update the text.
Label1.Text = "Du har nu lånat filmen:" + test;
Refresh();
The subversion client itself is available on Windows. See here for certified binaries from CollabNet.
CollabNet Subversion Command-Line Client v1.6.9 (for Windows)
This installer only includes the command-line client and an auto-update component.
Even though I can't understand it's possible not to love Tortoise! :)
Note:
The above link is for newer products - you can find version 1.11.1 through 1.7.19 at Older Subversion Releases
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
DATE()
for all rows, including those, that don't matchIt is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
Unless you need to access more memory that 32b addressing will allow you, the benefits will be small, if any.
When running on 64b CPU, you get the same memory interface no matter if you are running 32b or 64b code (you are using the same cache and same BUS).
While x64 architecture has a few more registers which allows easier optimizations, this is often counteracted by the fact pointers are now larger and using any structures with pointers results in a higher memory traffic. I would estimate the increase in the overall memory usage for a 64b application compared to a 32b one to be around 15-30 %.
EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.
armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.
armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.
If choice
is available, use this:
choice /C X /T 10 /D X > nul
where /T 10
is the number of seconds to delay.
Note the syntax can vary depending on your Windows version, so use CHOICE /?
to be sure.
Start pgAdmin, connect to the server, click on the database name, and select the statistics tab. You will see the size of the database at the bottom of the list.
Then if you click on another database, it stays on the statistics tab so you can easily see many database sizes without much effort. If you open the table list, it shows all tables and their sizes.
There is no need to set the delimiter by breaking it up in pieces like you have done.
Here is a complete program you can compile and run:
import java.util.Arrays;
public class SplitExample {
public static final String PLAYER = "1||1||Abdul-Jabbar||Karim||1996||1974";
public static void main(String[] args) {
String[] data = PLAYER.split("\\|\\|");
System.out.println(Arrays.toString(data));
}
}
If you want to use split with a pattern, you can use Pattern.compile
or Pattern.quote
.
To see compile
and quote
in action, here is an example using all three approaches:
import java.util.Arrays;
import java.util.regex.Pattern;
public class SplitExample {
public static final String PLAYER = "1||1||Abdul-Jabbar||Karim||1996||1974";
public static void main(String[] args) {
String[] data = PLAYER.split("\\|\\|");
System.out.println(Arrays.toString(data));
Pattern pattern = Pattern.compile("\\|\\|");
data = pattern.split(PLAYER);
System.out.println(Arrays.toString(data));
pattern = Pattern.compile(Pattern.quote("||"));
data = pattern.split(PLAYER);
System.out.println(Arrays.toString(data));
}
}
The use of patterns is recommended if you are going to split often using the same pattern. BTW the output is:
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
Edit /etc/sudoers
file either manually or using the visudo application.
Remember: System reads /etc/sudoers
file from top to the bottom, so you could overwrite a particular setting by putting the next one below.
So to be on the safe side - define your access setting at the bottom.
Following works perfectly for me: -*click on COMMAND and click on APPLY SOURCE FORMATTING - *And click on Clean Up HTML
Thank you PEKA
In Windows 10 PC, it is saved at:
C:\Users\<user>\.gradle\caches\modules-2\files-2.1\
Well, to answer the immediate question:
>>> s = "http://www.domain.com/?s=some&two=20"
The rfind
method returns the index of right-most substring:
>>> s.rfind("&")
29
You can take all elements up to a given index with the slicing operator:
>>> "foobar"[:4]
'foob'
Putting the two together:
>>> s[:s.rfind("&")]
'http://www.domain.com/?s=some'
If you are dealing with URLs in particular, you might want to use built-in libraries that deal with URLs. If, for example, you wanted to remove two
from the above query string:
First, parse the URL as a whole:
>>> import urlparse, urllib
>>> parse_result = urlparse.urlsplit("http://www.domain.com/?s=some&two=20")
>>> parse_result
SplitResult(scheme='http', netloc='www.domain.com', path='/', query='s=some&two=20', fragment='')
Take out just the query string:
>>> query_s = parse_result.query
>>> query_s
's=some&two=20'
Turn it into a dict
:
>>> query_d = urlparse.parse_qs(parse_result.query)
>>> query_d
{'s': ['some'], 'two': ['20']}
>>> query_d['s']
['some']
>>> query_d['two']
['20']
Remove the 'two'
key from the dict:
>>> del query_d['two']
>>> query_d
{'s': ['some']}
Put it back into a query string:
>>> new_query_s = urllib.urlencode(query_d, True)
>>> new_query_s
's=some'
And now stitch the URL back together:
>>> result = urlparse.urlunsplit((
parse_result.scheme, parse_result.netloc,
parse_result.path, new_query_s, parse_result.fragment))
>>> result
'http://www.domain.com/?s=some'
The benefit of this is that you have more control over the URL. Like, if you always wanted to remove the two
argument, even if it was put earlier in the query string ("two=20&s=some"
), this would still do the right thing. It might be overkill depending on what you want to do.
The accepted answer refers to a Wikipedia article when discussing the valid local-part of an email address, but Wikipedia is not an authority on this.
IETF RFC 3696 is an authority on this matter, and should be consulted at section 3. Restrictions on email addresses on page 5:
Contemporary email addresses consist of a "local part" separated from a "domain part" (a fully-qualified domain name) by an at-sign ("@"). The syntax of the domain part corresponds to that in the previous section. The concerns identified in that section about filtering and lists of names apply to the domain names used in an email context as well. The domain name can also be replaced by an IP address in square brackets, but that form is strongly discouraged except for testing and troubleshooting purposes.
The local part may appear using the quoting conventions described below. The quoted forms are rarely used in practice, but are required for some legitimate purposes. Hence, they should not be rejected in filtering routines but, should instead be passed to the email system for evaluation by the destination host.
The exact rule is that any ASCII character, including control characters, may appear quoted, or in a quoted string. When quoting is needed, the backslash character is used to quote the following character. For example
Abc\@[email protected]
is a valid form of an email address. Blank spaces may also appear, as in
Fred\ [email protected]
The backslash character may also be used to quote itself, e.g.,
Joe.\\[email protected]
In addition to quoting using the backslash character, conventional double-quote characters may be used to surround strings. For example
"Abc@def"@example.com "Fred Bloggs"@example.com
are alternate forms of the first two examples above. These quoted forms are rarely recommended, and are uncommon in practice, but, as discussed above, must be supported by applications that are processing email addresses. In particular, the quoted forms often appear in the context of addresses associated with transitions from other systems and contexts; those transitional requirements do still arise and, since a system that accepts a user-provided email address cannot "know" whether that address is associated with a legacy system, the address forms must be accepted and passed into the email environment.
Without quotes, local-parts may consist of any combination of
alphabetic characters, digits, or any of the special characters! # $ % & ' * + - / = ? ^ _ ` . { | } ~
period (".") may also appear, but may not be used to start or end the local part, nor may two or more consecutive periods appear. Stated differently, any ASCII graphic (printing) character other than the at-sign ("@"), backslash, double quote, comma, or square brackets may appear without quoting. If any of that list of excluded characters are to appear, they must be quoted. Forms such as
[email protected] customer/[email protected] [email protected] !def!xyz%[email protected] [email protected]
are valid and are seen fairly regularly, but any of the characters listed above are permitted.
As others have done, I submit a regex that works for both PHP and JavaScript to validate email addresses:
/^[a-z0-9!'#$%&*+\/=?^_`{|}~-]+(?:\.[a-z0-9!'#$%&*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-zA-Z]{2,}$/i
This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).
Suppose your data was : He said "This is how it is done".
Then the actual data should look like "He said \"This is how it is done\"."
.
This ensures that the \"
is treated as "(Quotation mark)
and not as JSON formatting. This is called escape character
.
This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.
Try this
$arr = ['This is a sample','This is also a "sample"'];
echo json_encode($arr);
OUTPUT:
["This is a sample","This is also a \"sample\""]
What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.
If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
And in the directive:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// You actions here
console.log("I got the new value! ", newValue);
}
}, true);
}
};
});
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.
Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.
DELIMITER isn't really a MySQL language command, it's a client command.
DELIMITER $$
/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$
/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count FROM employees where department=the_department;
END$$
/*DELIMITER is set to it's default*/
DELIMITER ;
I know this is an old thread, but thought I may add on a little extra. In my case I was wanting to pass on the text, val and some other data attr. In this case its better to store the whole option as a prev value rather than just the val.
Example code below:
var $sel = $('your select');
$sel.data("prevSel", $sel.clone());
$sel.on('change', function () {
//grab previous select
var prevSel = $(this).data("prevSel");
//do what you want with the previous select
var prevVal = prevSel.val();
var prevText = prevSel.text();
alert("option value - " + prevVal + " option text - " + prevText)
//reset prev val
$(this).data("prevSel", $(this).clone());
});
EDIT:
I forgot to add .clone() onto the element. in not doing so when you try to pull back the values you end up pulling in the new copy of the select rather than the previous. Using the clone() method stores a copy of the select instead of an instance of it.
use .serializeArray() to get the data in array format and then convert it into an object:
function getFormObj(formId) {
var formObj = {};
var inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
formObj[input.name] = input.value;
});
return formObj;
}
Yes it is correct. you can do it with an inner class.
A couple of ideas:
Remove half of your code (maybe via commenting it out).
Is the problem still there? Great, you've narrowed down the possibilities! Repeat.
Is the problem not there? Ok, look at the half you commented out!
Are you using any version control system (eg, Git)? If so, git checkout
some of your more recent commits. When was the problem introduced? Look at the commit to see exactly what code changed when the problem first arrived.
It's not necessary, it's optional, just as public
on interface methods.
See the JLS on this:
http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html
9.1.1.1 abstract Interfaces Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.
And
9.4 Abstract Method Declarations
[...]
For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.
I found some issue about that kind of error
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
Your
<img src="/home/tony/london.jpg" />
will work for a HTML file read from disk, as it will assume the URL is file:///home/...
. For a file served from a webserver though, the URL will become something like: http://www.yourdomain.com/home/tony/london.jpg
, which can be an invalid URL and not what you really mean.
For about how to serve and where to place your static files, check out this document. Basicly, if you're using django's development server, you want to show him the place where your media files live, then make your urls.py
serve those files (for example, by using some /static/
url prefix).
Will require you to put something like this in your urls.py
:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
In production environment you want to skip this and make your http server (apache, lighttpd, etc) serve static files.
MY solution in maven 3.5.4 ,use nexus, in eclipse:
<dependency>
<groupId>yilin.sheng</groupId>
<artifactId>webspherecore</artifactId>
<version>LATEST</version>
</dependency>
then in eclipse: atl + F5
, and choose the force update of snapshots/release
it works for me.
this is how you can create an array of boolean in TS and initialize it with false:
var array: boolean[] = [false, false, false]
or another approach can be:
var array2: Array<boolean> =[false, false, false]
you can specify the type after the colon which in this case is boolean array
chmod +x foo.sh
#!/bin/sh
or some such.sudo pwd
You can use this code:
<embed src="http://domain.com/your_pdf.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">
Or use Google Docs embeddable PDF viewer:
<iframe src="http://docs.google.com/gview?url=http://domain.com/your_pdf.pdf&embedded=true"
style="width:600px; height:500px;" frameborder="0"></iframe>
A parent class should not have knowledge of child classes. You can implement a method calculate()
and override it in every subclass:
class Person {
String name;
void getName(){...}
void calculate();
}
and then
class Student extends Person{
String class;
void getClass(){...}
@Override
void calculate() {
// do something with a Student
}
}
and
class Teacher extends Person{
String experience;
void getExperience(){...}
@Override
void calculate() {
// do something with a Student
}
}
By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.
In your example you can make Person
abstract and the use getName()
on instanced of Student
and Teacher
.
You can get the host ip using alpine image
docker run --rm alpine ip route | awk 'NR==1 {print $3}'
This would be more consistent as you're always using alpine to run the command.
Similar to Mariano's answer you can use same command to set an environment variable
DOCKER_HOST=$(docker run --rm alpine ip route | awk 'NR==1 {print $3}') docker-compose up
Another approach to put the below line only when require to get data from server,Append the below line along with your ajax url.
'?_='+Math.round(Math.random()*10000)
You can set the format in aspx, just add the property "DateFormatString" in your BoundField.
DataFormatString="{0:dd/MM/yyyy hh:mm:ss}"
You should look at the shelve and pickle modules. If you need to store a lot of data it may be better to use a database
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
Note that the parameters are passed as a tuple.
The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%
), because
Kind of an anonymous lookup table rather than a long switch statement:
return (const char *[]) {
"bananas & monkeys",
"Round and orange",
"APPLE",
}[enumVal];
If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead
var keys = []
var obj = {
'key1' : 'value1',
'key2' : 'value2',
'key3' : 'value3',
}
for (var key in obj){
keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])
Care must be taken that i
is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
var num = 0;
var str = "";
Even if your i
variable is integer, +
operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1
, in order to get 2
in addition with 1
try using (i-1+2)
. Use of ()
-parenthesis will not be necessary.
-
(minus operator) cannot be misunderstood and you will not get unexpected result/s.
Here is the example works fine in oracle
select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');
If you have the PATH in your .bashrc file and are still getting
conda: command not found
Your terminal might not be looking for the bash file.
Type
bash
in the terminal to insure you are in bash and then try:
conda --version
This is how I did it:
Your items (rows) must have unique ids so you can update them later. Set the tag of every view when the list is getting the view from adapter. (You can also use key tag if the default tag is used somewhere else)
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = super.getView(position, convertView, parent);
view.setTag(getItemId(position));
return view;
}
For the update check every element of list, if a view with given id is there it's visible so we perform the update.
private void update(long id)
{
int c = list.getChildCount();
for (int i = 0; i < c; i++)
{
View view = list.getChildAt(i);
if ((Long)view.getTag() == id)
{
// update view
}
}
}
It's actually easier than other methods and better when you dealing with ids not positions! Also you must call update for items which get visible.
This is the shortest/cleanest answer that I've found working with Angular 4 AOT
Source: https://github.com/angular/angular/issues/12631#issuecomment-274260009
@Injectable()
export class WindowWrapper extends Window {}
export function getWindow() { return window; }
@NgModule({
...
providers: [
{provide: WindowWrapper, useFactory: getWindow}
]
...
})
export class AppModule {
constructor(w: WindowWrapper) {
console.log(w);
}
}
char * const a;
means that the pointer is constant and immutable but the pointed data is not.
You could use const_cast
(in C++) or c-style cast to cast away the constness in this case as data itself is not constant.
const char * a;
means that the pointed data cannot be written to using the pointer a.
Using a const_cast
(C++) or c-style cast to cast away the constness in this case causes Undefined Behavior.
I always just use NOW():
INSERT INTO table (lastModifiedTime) VALUES (NOW())
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_now
Bonus answer since this use-case brought me here:
In the case where you need to do this as some other user
echo "some output" | sudo -u some_user tee /some/path/some_file
Note that the echo will happen as you and the file write will happen as "some_user" what will NOT work is if you were to run the echo as "some_user" and redirect the output with >> "some_file" because the file redirect will happen as you.
Hint: tee also supports append with the -a flag, if you need to replace a line in a file as another user you could execute sed as the desired user.
I read solution from official website of Gson at here
And this code for you:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("servers");
String[] arrName = new Gson().fromJson(jsonArray, String[].class);
List<String> lstName = new ArrayList<>();
lstName = Arrays.asList(arrName);
for (String str : lstName) {
System.out.println(str);
}
Result show on monitor:
8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1
Here's an improvement, grabbing just the directory to stdout:
java -XshowSettings:properties -version 2>&1 \
| sed '/^[[:space:]]*java\.home/!d;s/^[[:space:]]*java\.home[[:space:]]*=[[:space:]]*//'
OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.
Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.
Open your folder which you want to upload. drag and drop on the listing in browser. See the image here.
basename
does remove the directory prefix of a path:
$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example
I propose a script for removing randomly picked up items off a list until it is empty:
Maintain a set
and remove randomly picked up element (with choice
) until list is empty.
s=set(range(1,6))
import random
while len(s)>0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
you can also use the full filename to your gem file:
gem install /full/path/to/your.gem
this works as well -- it's probably the easiest way
One can also do this with a compact version of @TomAugspurger's answer, like so:
df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])
jQuery("#your_div_id").remove(); will completely remove the corresponding elements from the HTML DOM. So if you want to show the div on another event without a refresh, it will not be possible to retrieve the removed elements back unless you use AJAX.
jQuery("#your_div_id").toggle("slow"); will also could make unexpected results. As an Example when you select some element on your div which generates another div with a close button(which uses the same close functionality just as your previous div) it could make undesired behaviour.
So without using AJAX, a good solution for the close button would be as follows
HTML____________
<div id="your_div_id">
<span class="close_div" onclick="close_div(1)">✖</span>
</div>
JQUERY__________
function close_div(id) {
if(id === 1) {
jQuery("#your_div_id").hide();
}
}
Now you can show the div, when another event occures as you wish... :-)
Try this
test2.removeAll(test1);
Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.
You can also use Perl for this:
perl -wnl -e '$.== NUM && print && exit;' some.file
Another option is to add another tag with flex: auto
style in between your tags that you want to fill in the remaining space.
https://jsfiddle.net/tsey5qu4/
The HTML:
<div class="parent">
<div class="left">Left</div>
<div class="fill-remaining-space"></div>
<div class="right">Right</div>
</div>
The CSS:
.fill-remaining-space {
flex: auto;
}
This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.
Found this...
bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'
If you need to know about different options of bcp flags...
==
shouldn't be used to compare objects in your if
. For NSString
use isEqualToString:
to compare them.
In a Unicode-aware language, the Unicode Punctuation character property is \p{P}
— which you can usually abbreviate \pP
and sometimes expand to \p{Punctuation}
for readability.
Are you using a Perl Compatible Regular Expression library?
KeyEvent.KEYCODE_HOME
can NOT be intercepted.
It would be quite bad if it would be possible.
(Edit): I just see Nicks answer, which is perfectly complete ;)
If you have xmllint
you can spawn a subprocess and use it. xmllint --format <file>
pretty-prints its input XML to standard output.
Note that this method uses an program external to python, which makes it sort of a hack.
def pretty_print_xml(xml):
proc = subprocess.Popen(
['xmllint', '--format', '/dev/stdin'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
(output, error_output) = proc.communicate(xml);
return output
print(pretty_print_xml(data))
If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;
SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO
UPDATE #TEMP
SET Column = "Changed"
GO
INSERT INTO Table
SELECT *
FROM #Temp
I can solve it by updating the tesseract_cmd variable with the bin/tesseract path in the pytesseract.py file
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
Several methods are covered in
"51} How can I echo lines in different colors in NT scripts?"
http://www.netikka.net/tsneti/info/tscmd051.htm
One of the alternatives: If you can get hold of QBASIC, using colors is relatively easy:
@echo off & setlocal enableextensions
for /f "tokens=*" %%f in ("%temp%") do set temp_=%%~sf
set skip=
findstr "'%skip%QB" "%~f0" > %temp_%\tmp$$$.bas
qbasic /run %temp_%\tmp$$$.bas
for %%f in (%temp_%\tmp$$$.bas) do if exist %%f del %%f
endlocal & goto :EOF
::
CLS 'QB
COLOR 14,0 'QB
PRINT "A simple "; 'QB
COLOR 13,0 'QB
PRINT "color "; 'QB
COLOR 14,0 'QB
PRINT "demonstration" 'QB
PRINT "By Prof. (emer.) Timo Salmi" 'QB
PRINT 'QB
FOR j = 0 TO 7 'QB
FOR i = 0 TO 15 'QB
COLOR i, j 'QB
PRINT LTRIM$(STR$(i)); " "; LTRIM$(STR$(j)); 'QB
COLOR 1, 0 'QB
PRINT " "; 'QB
NEXT i 'QB
PRINT 'QB
NEXT j 'QB
SYSTEM 'QB
A simple solution for a very common problem
// DECLARATION
HttpContext context = HttpContext.Current;
DataTable dt_ShoppingBasket = context.Session["Shopping_Basket"] as DataTable;
// TRY TO ADD rows with the info into the DataTable
try
{
// Add new Serial Code into DataTable dt_ShoppingBasket
dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());
// Assigns new DataTable to Session["Shopping_Basket"]
context.Session["Shopping_Basket"] = dt_ShoppingBasket;
}
catch (Exception)
{
// IF FAIL (EMPTY OR DOESN'T EXIST) -
// Create new Instance,
DataTable dt_ShoppingBasket= new DataTable();
// Add column and Row with the info
dt_ShoppingBasket.Columns.Add("Serial");
dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());
// Assigns new DataTable to Session["Shopping_Basket"]
context.Session["Shopping_Basket"] = dt_PanierCommande;
}
// PRINT TESTS
DataTable dt_To_Print = context.Session["Shopping_Basket"] as DataTable;
foreach (DataRow row in dt_To_Print.Rows)
{
foreach (var item in row.ItemArray)
{
Debug.WriteLine("DATATABLE IN SESSION: " + item);
}
}
You only need
request.getParameterMap()
for getting the POST and GET - Parameters.
The Method returns a Map<String,String[]>
.
You can read the parameters in the Map by
Map<String, String[]> map = request.getParameterMap();
//Reading the Map
//Works for GET && POST Method
for(String paramName:map.keySet()) {
String[] paramValues = map.get(paramName);
//Get Values of Param Name
for(String valueOfParam:paramValues) {
//Output the Values
System.out.println("Value of Param with Name "+paramName+": "+valueOfParam);
}
}
The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.
-a "From: Foo Bar <[email protected]>"
Could use CASE WHEN
to leave those with no ';' alone.
SELECT
CASE WHEN CHARINDEX(';', MyText) > 0 THEN
LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
MyText END
FROM MyTable
Are dictionaries ordered in Python 3.6+?
They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).
As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:
Make it so. "Dict keeps insertion order" is the ruling. Thanks!
This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.
How does the Python
3.6
dictionary implementation perform better[2] than the older one while preserving element order?
Essentially, by keeping two arrays.
The first array, dk_entries
, holds the entries (of type PyDictKeyEntry
) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).
The second, dk_indices
, holds the indices for the dk_entries
array (that is, values that indicate the position of the corresponding entry in dk_entries
). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices
and the corresponding entry is fetched by indexing dk_entries
. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t
(1
byte) to int32_t
/int64_t
(4
/8
bytes) on 32
/64
bit builds)
In the previous implementation, a sparse array of type PyDictKeyEntry
and size dk_size
had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size
full for performance reasons. (and the empty space still had PyDictKeyEntry
size!).
This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t
(X
depending on dict size) 2/3 * dk_size
s full is kept. The empty space changed from type PyDictKeyEntry
to intX_t
.
So, obviously, creating a sparse array of type PyDictKeyEntry
is much more memory demanding than a sparse array for storing int
s.
You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.
In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.
For example, the dictionary:
d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}
is currently stored as [keyhash, key, value]:
entries = [['--', '--', '--'], [-8522787127447073495, 'barry', 'green'], ['--', '--', '--'], ['--', '--', '--'], ['--', '--', '--'], [-9092791511155847987, 'timmy', 'red'], ['--', '--', '--'], [-6480567542315338377, 'guido', 'blue']]
Instead, the data should be organized as follows:
indices = [None, 1, None, None, None, 0, None, 2] entries = [[-9092791511155847987, 'timmy', 'red'], [-8522787127447073495, 'barry', 'green'], [-6480567542315338377, 'guido', 'blue']]
As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.
[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict
object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==
, !=
). dict
s currently don't offer any of those behaviors/methods.
[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.
Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.
There are two ways to handle exceptions in pytest
:
pytest.raises
to write assertions about raised exceptions@pytest.mark.xfail
pytest.raises
From the docs:
In order to write assertions about raised exceptions, you can use
pytest.raises
as a context manager
Examples:
Asserting just an exception:
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
with pytest.raises(ZeroDivisionError)
says that whatever is
in the next block of code should raise a ZeroDivisionError
exception. If no exception is raised, the test fails. If the test raises a different exception, it fails.
If you need to have access to the actual exception info:
import pytest
def f():
f()
def test_recursion_depth():
with pytest.raises(RuntimeError) as excinfo:
f()
assert "maximum recursion" in str(excinfo.value)
excinfo
is a ExceptionInfo
instance, which is a wrapper around the actual exception raised. The main attributes of interest are .type
, .value
and .traceback
.
@pytest.mark.xfail
It is also possible to specify a raises
argument to pytest.mark.xfail
.
import pytest
@pytest.mark.xfail(raises=IndexError)
def test_f():
l = [1, 2, 3]
l[10]
@pytest.mark.xfail(raises=IndexError)
says that whatever is
in the next block of code should raise an IndexError
exception. If an IndexError
is raised, test is marked as xfailed (x)
. If no exception is raised, the test is marked as xpassed (X)
. If the test raises a different exception, it fails.
Notes:
Using pytest.raises
is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail
with a check function is probably better for something like documenting unfixed bugs or bugs in dependencies.
You can pass a match
keyword parameter to the context-manager (pytest.raises
) to test that a regular expression matches on the string representation of an exception. (see more)
"This is a comment in vimrc. It does not have a closing quote
Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc
Dictionary does not define order of items. If you just need an item use Keys
or Values
properties of dictionary to pick one.
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
When you override OnCreateView
in your RouteSearchFragment
class, do you have the
if(view != null) {
return view;
}
code segment?
If so, removing the return statement should solve your problem.
You can keep the code and return the view if you don't want to regenerate view data, and onDestroyView() method you remove this view from its parent like so:
@Override
public void onDestroyView() {
super.onDestroyView();
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeAllViews();
}
}
}
SELECT COUNT(*) FROM table1 WHERE id = 1;
if COUNT(*) = 0
INSERT INTO table1(col1, col2, cole) VALUES(var1,var2,var3);
else if COUNT(*) > 0
UPDATE table1 SET col1 = var4, col2 = var5, col3 = var6 WHERE id = 1;
This script lists most of what you are looking for and can hopefully be modified to you needs. Note that it is creating a permanent table in there - you might want to change it. It is a subset from a larger script that also summarises backup and job information on various servers.
IF OBJECT_ID('tempdb..#DriveInfo') IS NOT NULL
DROP TABLE #DriveInfo
CREATE TABLE #DriveInfo
(
Drive CHAR(1)
,MBFree INT
)
INSERT INTO #DriveInfo
EXEC master..xp_fixeddrives
IF OBJECT_ID('[dbo].[Tmp_tblDatabaseInfo]', 'U') IS NOT NULL
DROP TABLE [dbo].[Tmp_tblDatabaseInfo]
CREATE TABLE [dbo].[Tmp_tblDatabaseInfo](
[ServerName] [nvarchar](128) NULL
,[DBName] [nvarchar](128) NULL
,[database_id] [int] NULL
,[create_date] datetime NULL
,[CompatibilityLevel] [int] NULL
,[collation_name] [nvarchar](128) NULL
,[state_desc] [nvarchar](60) NULL
,[recovery_model_desc] [nvarchar](60) NULL
,[DataFileLocations] [nvarchar](4000)
,[DataFilesMB] money null
,DataVolumeFreeSpaceMB INT NULL
,[LogFileLocations] [nvarchar](4000)
,[LogFilesMB] money null
,LogVolumeFreeSpaceMB INT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Tmp_tblDatabaseInfo]
SELECT
@@SERVERNAME AS [ServerName]
,d.name AS DBName
,d.database_id
,d.create_date
,d.compatibility_level
,CAST(d.collation_name AS [nvarchar](128)) AS collation_name
,d.[state_desc]
,d.recovery_model_desc
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 0 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS DataFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 0 and m.database_id = d.database_id) AS DataFilesMB
,NULL
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 1 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS LogFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 1 and m.database_id = d.database_id) AS LogFilesMB
,NULL
FROM sys.databases d
WHERE d.database_id > 4 --Exclude basic system databases
UPDATE [dbo].[Tmp_tblDatabaseInfo]
SET DataFileLocations =
CASE WHEN LEN(DataFileLocations) > 4 THEN LEFT(DataFileLocations,LEN(DataFileLocations)-2) ELSE NULL END
,LogFileLocations =
CASE WHEN LEN(LogFileLocations) > 4 THEN LEFT(LogFileLocations,LEN(LogFileLocations)-2) ELSE NULL END
,DataFilesMB =
CASE WHEN DataFilesMB > 0 THEN DataFilesMB * 8 / 1024.0 ELSE NULL END
,LogFilesMB =
CASE WHEN LogFilesMB > 0 THEN LogFilesMB * 8 / 1024.0 ELSE NULL END
,DataVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( DataFileLocations,1))
,LogVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( LogFileLocations,1))
select * from [dbo].[Tmp_tblDatabaseInfo]
The short answer is the iPhone supports H.264 video, High profile and AAC audio, in container formats .mov
, .mp4
, or MPEG Segment .ts
. MPEG Segment files are used for HTTP Live Streaming.
.mp4
container..ts
container files (see App Store Review Guidelines rule 2.5.7).On the iPhone, H.264 is the only game in town. [1]
There are several different feature tiers or "profiles" available in H.264. All modern iPhones (3GS and above) support the High profile. These profiles are basically three different levels of algorithm "tricks" used to compress the video. More tricks give better compression, but require more CPU or dedicated hardware to decode. This is a table that lists the differences between the different profiles.
[1] Interestingly, Apple's own Facetime uses the newer H.265 (HEVC) video codec. However right now (August 2017) there is no Apple-provided library that gives access to a HEVC codec to developers. This is expected to change at some point.
In talking about what video format the iPhone supports, a distinction should be made between what the hardware can support, and what the (much lower) limits are for playback when streaming over a network.
The only data given about hardware video support by Apple about the current generation of iPhones (SE, 6S, 6S Plus, 7, 7 Plus) is that they support
4K [3840x2160] video recording at 30 fps
1080p [1920x1080] HD video recording at 30 fps or 60 fps.
Obviously the phone can play back what it can record, so we can guess that 3840x2160 at 30 fps and 1920x1080 at 60 fps represent design limits of the phone. In addition, the screen size on the 6S Plus and 7 Plus is 1920x1080. So if you're interested in playback on the phone, it doesn't make sense to send over more pixels then the screen can draw.
However, streaming video is a different matter. Since networks are slow and video is huge, it's typical to use lower resolutions, bitrates, and frame rates than the device's theoretical maximum.
The most detailed document giving recommendations for streaming is TN2224 Best Practices for Creating and Deploying HTTP Live Streaming Media for Apple Devices. Figure 3 in that document gives a table of recommended streaming parameters:
As you can see, Apple recommends the relatively low resolution of 768x432 as the highest recommended resolution for streaming over a cellular network. Of course this is just a recommendation and YMMV.
The question is about video, but that video generally has one or more audio tracks with it. The iPhone supports a few audio formats, but the most modern and by far most widely used is AAC. The iPhone 7 / 7 Plus, 6S Plus / 6S, SE all support AAC bitrates of 8 to 320 Kbps.
The audio and video tracks go inside a container. The purpose of the container is to combine (interleave) the different tracks together, to store metadata, and to support seeking. The iPhone supports
The .mov
and .mp4
file formats are closely related (.mp4
is in fact based on .mov
), however .mp4
is an ISO standard that has much wider support.
As noted above, you have to use MPEG-TS for videos longer than 10 minutes.
It's easier with the enumitem package:
\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
\item foo
\item bar
\item baz
\end{itemize}
Even more compact:
\begin{itemize}[noitemsep,nolistsep]
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
The enumitem package provides a lot of features to customize bullets, numbering and lengths.
The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.
Instead of writing this,
<script type="text/javascript">
function changeImage(a) {
document.getElementById("img").src=a.src;
}
</script>
try:
<script type="text/javascript">
function changeImage(a) {
document.getElementById("img").src=a;
}
</script>
To show both:
<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: scroll; padding-bottom:10px;"> </div>
Hide X Axis:
<div style="height:250px; width:550px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;"> </div>
Hide Y Axis:
<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;"> </div>
There is also at least one library for doing native threading from within Node.js: node-webworker-threads
https://github.com/audreyt/node-webworker-threads
This basically implements the Web Worker browser API for node.js.
Convert the integer into a string and then you can use the STUFF function to insert in your colons into time string. Once you've done that you can convert the string into a time datatype.
SELECT CAST(STUFF(STUFF(STUFF(cast(23421155 as varchar),3,0,':'),6,0,':'),9,0,'.') AS TIME)
That should be the simplest way to convert it to a time without doing anything to crazy.
In your example you also had an int where the leading zeros are not there. In that case you can simple do something like this:
SELECT CAST(STUFF(STUFF(STUFF(RIGHT('00000000' + CAST(421151 AS VARCHAR),8),3,0,':'),6,0,':'),9,0,'.') AS TIME)
[Based on Android source code:]
At the C++ side, the SurfaceFlinger implements the captureScreen API. This is exposed over the binder IPC interface, returning each time a new ashmem area that contains the raw pixels from the screen. The actual screenshot is taken through OpenGL.
For the system C++ clients, the interface is exposed through the ScreenshotClient class, defined in <surfaceflinger_client/SurfaceComposerClient.h>
for Android < 4.1; for Android > 4.1 use <gui/SurfaceComposerClient.h>
Before JB, to take a screenshot in a C++ program, this was enough:
ScreenshotClient ssc;
ssc.update();
With JB and multiple displays, it becomes slightly more complicated:
ssc.update(
android::SurfaceComposerClient::getBuiltInDisplay(
android::ISurfaceComposer::eDisplayIdMain));
Then you can access it:
do_something_with_raw_bits(ssc.getPixels(), ssc.getSize(), ...);
Using the Android source code, you can compile your own shared library to access that API, and then expose it through JNI to Java. To create a screen shot form your app, the app has to have the READ_FRAME_BUFFER
permission.
But even then, apparently you can create screen shots only from system applications, i.e. ones that are signed with the same key as the system. (This part I still don't quite understand, since I'm not familiar enough with the Android Permissions system.)
Here is a piece of code, for JB 4.1 / 4.2:
#include <utils/RefBase.h>
#include <binder/IBinder.h>
#include <binder/MemoryHeapBase.h>
#include <gui/ISurfaceComposer.h>
#include <gui/SurfaceComposerClient.h>
static void do_save(const char *filename, const void *buf, size_t size) {
int out = open(filename, O_RDWR|O_CREAT, 0666);
int len = write(out, buf, size);
printf("Wrote %d bytes to out.\n", len);
close(out);
}
int main(int ac, char **av) {
android::ScreenshotClient ssc;
const void *pixels;
size_t size;
int buffer_index;
if(ssc.update(
android::SurfaceComposerClient::getBuiltInDisplay(
android::ISurfaceComposer::eDisplayIdMain)) != NO_ERROR ){
printf("Captured: w=%d, h=%d, format=%d\n");
ssc.getWidth(), ssc.getHeight(), ssc.getFormat());
size = ssc.getSize();
do_save(av[1], pixels, size);
}
else
printf(" screen shot client Captured Failed");
return 0;
}
Simple
var result = parseInt("1") + parseInt("2");
console.log(result ); // Outputs 3
Just write:
min-height: xxx;
overflow: hidden;
then div
will automatically take the height of the content.
You can try atoi() library function. Also sscanf() and sprintf() would help.
Here is a small example to show converting integer to character string:
main()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
Here for another Example
#include <stdio.h>
int main(void)
{
char text[] = "StringX";
int digit;
for (digit = 0; digit < 10; ++digit)
{
text[6] = digit + '0';
puts(text);
}
return 0;
}
/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/
When working with Dialogues, Facebook provide a 'show_error' attribute that defaults to no
but can be set to true
in a Development environment and is really helpful for debugging purposes.
show_error - If this is set to true, the error code and error description will be displayed in the event of an error.
Instructions of it's use can be found in the Facebook Docs.
I'd been debugging "An Error occurred. Please try later." dialogue before i found this attribute in the docs. Once i started using it, i could see the following message too:
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application.
In VSCode 1.24 you can do that.
Right click on EXPLORER
on the side bar and checked Outline
.