Another application that can be using the resources is apparently Android Studio's Kotlin REPL. I closed that, and then I could build again no problem.
A naive, CPU-intensive method to block execution for a number of milliseconds:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
I believe the 2GB limit is for 32-bit Java. I thought v1.6 was always 64 bit, but try forcing 64 bit mode just to see: add the -d64 option.
Best way I have used is to mount the VS 2010 Image or insert the Installation disc and run the uninstall
option, really works well
You can query Active directory via JNDI and run LDAP operations
http://docs.oracle.com/javase/tutorial/jndi/ldap/authentication.html
http://docs.oracle.com/javase/tutorial/jndi/ldap/operations.html
http://mhimu.wordpress.com/2009/03/18/active-directory-authentication-using-javajndi/
For an out-of-the-box working example, this is what I ended up using based on the previous answers.
using System.Reflection;
using System.Runtime.InteropServices;
label1.Text = "GUID: " + ((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute), false)).Value.ToUpper();
Alternatively, this way allows you to use it from a static class:
/// <summary>
/// public GUID property for use in static class </summary>
/// <returns>
/// Returns the application GUID or "" if unable to get it. </returns>
static public string AssemblyGuid
{
get
{
object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false);
if (attributes.Length == 0) { return String.Empty; }
return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value.ToUpper();
}
}
This is how I do this in order to work with LINQ.
DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));
If you only use dtOne.Date == dtTwo.Date
it wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)
Typical error on Windows because the default user directory is C:\user\<your_user>
, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u
is a Unicode escape. Any character not numeric after this produces an error.
To solve it, just double the backslashes: C:\\user\\<\your_user>...
Try adding in webpack, it solved the similar issue in my project. Specially the "presets" part.
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel',
query :{
presets:['react','es2015']
}
},
It will not work for first position so better solution is :
if ($counter != 0 && $counter % 3 == 0) {
echo 'image file';
}
Check it by yourself. I have tested it for adding class for every 4th element.
If you assign value 0 to item.selectedVariant
it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'
.
I encountered two issues related to the foregoing, when extracting text delimited by \
and /
, and found a solution that fits both, other than using new RegExp
, which requires \\\\
at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the //
is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second /
terminates the regular expression in spite of the escape character.
What does work for me is to represent /
as \x2F
, which is the hexadecimal representation of /
. I think that's more efficient and understandable than using new RegExp
, but of course it needs a comment to identify the hex code.
DECLARE
error_flag BOOLEAN := false;
BEGIN
error_flag := true;
--error_flag := 13;--expression is of wrong type
IF error_flag THEN
UPDATE table_a SET id= 8 WHERE id = 1;
END IF;
END;
I found the easiest way is to use the colormap
parameter in .plot()
with one of the preset color gradients:
df.plot(kind='bar', stacked=True, colormap='Paired')
You can find a large list of preset colormaps here.
I've just found a great tool for that need, it is called tabulate.
It prints tabular data and works with DataFrame
.
from tabulate import tabulate
import pandas as pd
df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))
+----+-----------+-------------+
| | col_two | column_3 |
|----+-----------+-------------|
| 0 | 0.0001 | ABCD |
| 1 | 1e-05 | ABCD |
| 2 | 1e-06 | long string |
| 3 | 1e-07 | ABCD |
+----+-----------+-------------+
Note:
To suppress row indices for all types of data, pass
showindex="never"
orshowindex=False
.
I think max value of int(11) is 4294967295
Laravel 5.3 use pluck($value, $key )
$value is displayed in your drop list and $key is id
controller
$products = Product::pluck('name', 'id');
return view('main.index', compact('products'));
view
{{ Form::select('id', $products, null, ['class' => 'form-control']) }}
Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:
SELECT e
FROM Employee e
WHERE e IN (SELECT emp
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
SELECT e
FROM Employee e
WHERE e.id IN (SELECT emp.id
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);
sq.select(sqEmp.get(Employee_.id)).where(
cb.equal(project.get(Project_.name),
cb.parameter(String.class, "project")));
c.select(emp).where(
cb.in(emp.get(Employee_.id)).value(sq));
TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();
There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html
IValueConverter implementation can be used. Converter class which takes inheritance from IValueConverter takes some parameters like value
(percentage) and parameter
(parent's width) and returns desired width value. In XAML file, component's width is set with the desired value:
public class SizePercentageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null)
return 0.7 * value.ToDouble();
string[] split = parameter.ToString().Split('.');
double parameterDouble = split[0].ToDouble() + split[1].ToDouble() / (Math.Pow(10, split[1].Length));
return value.ToDouble() * parameterDouble;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Don't need to implement this
return null;
}
}
XAML:
<UserControl.Resources>
<m:SizePercentageConverter x:Key="PercentageConverter" />
</UserControl.Resources>
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Width="{Binding Converter={StaticResource PercentageConverter}, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualWidth}"
Height="{Binding Converter={StaticResource PercentageConverter}, ConverterParameter=0.6, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualHeight}">
....
</ScrollViewer>
You can also use package plyr
, which is somehow more versatile:
library(plyr)
ddply(d, .(Name), summarize, Rate1=mean(Rate1), Rate2=mean(Rate2))
Name Rate1 Rate2
1 Aira 16.33333 47.00000
2 Ben 31.33333 50.33333
3 Cat 44.66667 54.00000
GetThreadId
returns the ID of a given native thread. There are ways to make it work with managed threads, I'm sure, all you need to find is the thread handle and pass it to that function.
GetCurrentThreadId
returns the ID of the current thread.
GetCurrentThreadId
has been deprecated as of .NET 2.0: the recommended way is the Thread.CurrentThread.ManagedThreadId
property.
it's simple, all the problems can be solved like this,
1) have escape always take you out of fullscreen mode (this doesn't apply to manually entering fullscreen through f11)
2) temporarily display a small banner saying fullscreen video mode is entered (by the browser)
3) block fullscreen action by default, just like has been done for pop-ups and local database in html5 and location api and etc, etc.
i don't see any problems with this design. anyone think i missed anything?
section {
position: relative;
width: 50%;
border: 1px solid;
}
h1 {
display: inline;
}
div {
position: relative;
float:right;
top: 0;
right: 0;
}
What you need is a date template filter.
e.g:
<td>Joined {{user.date_created|date:"F Y" }}<td>
This returns Joined December 2018
An easy solution is use the property zoom
:
input[type="checkbox"] {_x000D_
zoom: 1.5;_x000D_
}
_x000D_
<input type="checkbox" />
_x000D_
This Worked for me > In Eclipse NEON double clicked on Server tab which redirects server overview window
Here you can change port number based on your requirement for Tomcat Admin and HTTP port.
And restarted the server.
Hope this helps you.
Edit: I changed it to work for dynamically added elements using .on()
in jQuery 1.7 or above:
$(document).on("contextmenu", ".element", function(e){
alert('Context Menu event has fired!');
return false;
});
Demo: jsfiddle.net/Kn9s7/5
[Start of original post] This is what worked for me:
$('.element').bind("contextmenu",function(e){
alert('Context Menu event has fired!');
return false;
});
In case you are into multiple solutions ^^
Edit: Tim Down brings up a good point that it's not always going to be a right-click
that fires the contextmenu
event, but also when the context menu key is pressed (which is arguably a replacement for a right-click
)
With 4 lines, I import a rss to an array.
$feed = implode(file('http://yourdomains.com/feed.rss'));
$xml = simplexml_load_string($feed);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
For a more complex solution
$feed = new DOMDocument();
$feed->load('file.rss');
$json = array();
$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $key => $item) {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
$json['item'][$key]['title'] = $title;
$json['item'][$key]['description'] = $description;
$json['item'][$key]['pubdate'] = $pubDate;
$json['item'][$key]['guid'] = $guid;
}
echo json_encode($json);
The above did not work for me but this did
<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>
I found a solution that works exactly how I want.
I changed
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');
To
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Document', 'required');
}
.as_matrix()
. One short line:df.iloc[:,[1,2,3]].as_matrix()
array([[3, 2, 0.816497],
[0, 'NaN', 'NaN'],
[2, 51, 50.0]], dtype=object)
Here are the steps for your example:
import pandas as pd
columns = ['viz', 'a1_count', 'a1_mean', 'a1_std']
index = [0,1,2]
vals = {'viz': ['n','n','n'], 'a1_count': [3,0,2], 'a1_mean': [2,'NaN', 51], 'a1_std': [0.816497, 'NaN', 50.000000]}
df = pd.DataFrame(vals, columns=columns, index=index)
Gives:
viz a1_count a1_mean a1_std
0 n 3 2 0.816497
1 n 0 NaN NaN
2 n 2 51 50
Then:
x1 = df.iloc[:,[1,2,3]].as_matrix()
Gives:
array([[3, 2, 0.816497],
[0, 'NaN', 'NaN'],
[2, 51, 50.0]], dtype=object)
Where x1 is numpy.ndarray
.
NoGray is nice eye candy but there are a few usability considerations. Firstly, analog clocks are growing increasingly obscure, and younger people sometimes have a difficult time reading them. Secondly, dragging with a mouse to a specific time is a bit tedious, just like the time pickers that use a slider. Thirdly, keyboard interaction for this picker is a bit sporadic.
For a more usable time picker, check out the Any+Time™ Datepicker/Timepicker AJAX Calendar Widget. It's perhaps the fastest-and-easiest-to-use time picker available, because it uses simple buttons to select specific times with speed and ease.
An interesting test of usability is this: pick an odd time (say, 10:32pm), then see how long it takes to accurately select that time using various time pickers. You can probably do it faster with Any+Time™ than you could write out the time by hand--just try to find another picker you can say that about! Not to mention, Any+Time™ supports a countless variety of date/time formats, 12/24-hour clock, full CSS (or jQuery UI) customization and even time zones!
log4j.rootLogger=OFF
Hacky way:
You could increase the session timeout programmatically when a large up-/download is expected.
session.setMaxInactiveInterval(TWO_HOURS_IN_SECONDS)
When the process ends, you could set the timeout back to its default.
But.. when you are on Java EE, and the up-/download doesn't take a complete hour, the better way was to run the tasks asynchronous (via JMS e.g.).
When you create a new File
, you are supposed to provide the file name, not only the directory you want to put your file in.
Try with something like
File file = new File("D:/Data/" + item.getFileName());
An alternative using eval
so avoiding use of a subshell:
sudo -s eval 'whoami; whoami'
Note: The other answers using sudo -s
fail because the quotes are being passed on to bash and run as a single command so need to strip quotes with eval. eval
is better explained is this SO answer
Quoting within the commands is easier too:
$ sudo -s eval 'whoami; whoami; echo "end;"'
root
root
end;
And if the commands need to stop running if one fails use double-ampersands instead of semi-colons:
$ sudo -s eval 'whoami && whoamit && echo "end;"'
root
/bin/bash: whoamit: command not found
I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.
For anyone else finding this issue, I fixed it by moving the environment variable higher than others!
Actually you can do it with sink()
:
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
hence do:
file.show("outfile.txt")
# hello
# world
Open httpd.conf file in your text editor. Find this line:
Listen 80
and change it
Listen 8079
After change, save it and restart apache.
In My Aws Windows I Solved it and steps are
example
...
# socket=MYSQL
port=3306
[mysql]
no-beep=
default-character-set=utf8
# default-character-set=
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.=
#
# server_type=2
[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
# The next three options are mutually exclusive to SERVER_PORT below.
# skip-networking=
# enable-named-pipe=
# shared-memory=
...
Remember, you can only add a cookie for the current domain.
If you want to add a cookie for your Google account, do
browser.get('http://google.com')
for cookie in cookies:
browser.add_cookie(cookie)
Use "E"
See the section on Date and Time Patterns:
This is my best solution if I understood the question well:
Use of $object->first()
method to run the code inside if
statement once, that is when on the first loop. The same concept is true with $object->last()
.
@if($object->first())
<div class="panel user-list">
<table id="myCustomTable" class="table table-hover">
<thead>
<tr>
<th class="col-email">Email</th>
</tr>
</thead>
<tbody>
@endif
@foreach ($object as $data)
<tr class="gradeX">
<td class="col-name"><strong>{{ $data->email }}</strong></td>
</tr>
@endforeach
@if($object->last())
</tbody>
</table>
</div>
@endif
I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.
<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />
And this jQuery code:
$('.idNoEnter').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
Alternatively, if keydown is insufficient:
$('.idNoEnter').on('keypress keydown keyup', function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
Some notes:
Modifying various good answers here, the Enter key seems to work for keydown
on all the browsers. For the alternative, I updated bind()
to the on()
method.
I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.
You are checking whether the string contains all illegal characters. Change the ||
s to &&
s.
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
Just be careful of Bitmap type from java platform call like from comm1x's and Gnzlt's answers, because it might return null. I think it is also more flexible if the parameter can be any Number and use infix for readability, depends on your coding style.
infix fun Bitmap.rotate(degrees: Number): Bitmap? {
return Bitmap.createBitmap(
this,
0,
0,
width,
height,
Matrix().apply { postRotate(degrees.toFloat()) },
true
)
}
How to use?
bitmap rotate 90
// or
bitmap.rotate(90)
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
UPDATE myTable
SET myColumn = NULL
WHERE myCondition
As @KyssTao has been saying, help(dates.num2date)
says that the x
has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102
is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).
Use datestr2num
instead (see help(dates.datestr2num)
):
new_x = dates.datestr2num(date) # where date is '01/02/1991'
While you unfortunately cannot convert an existing member function pointer to a plain function pointer, you can create an adapter function template in a fairly straightforward way that wraps a member function pointer known at compile-time in a normal function like this:
template <class Type>
struct member_function;
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...)>
{
template <Ret(Type::*Func)(Args...)>
static Ret adapter(Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...) const>
{
template <Ret(Type::*Func)(Args...) const>
static Ret adapter(const Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
int (*func)(A&) = &member_function<decltype(&A::f)>::adapter<&A::f>;
Note that in order to call the member function, an instance of A
must be provided.
Do not use [^\w\s]
, this will remove letters with accents (like àèéìòù), not to mention to Cyrillic or Chinese, letters coming from such languages will be completed removed.
You really don't want remove these letters together with all the special characters. You have two chances:
[^èéòàùì\w\s]
.\p{...}
syntax.var str = "????::: résd,$%& adùf"
var search = XRegExp('([^?<first>\\pL ]+)');
var res = XRegExp.replace(str, search, '',"all");
console.log(res); // returns "????::: resd,adf"
console.log(str.replace(/[^\w\s]/gi, '') ); // returns " rsd adf"
console.log(str.replace(/[^\wèéòàùì\s]/gi, '') ); // returns " résd adùf"
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.js"></script>
_x000D_
Be sure to find out your current working directory, and write your filepath relative to it.
This code:
File here = new File(".");
System.out.println(here.getAbsolutePath());
... will print out that directory.
Also, unrelated to your question, try to use File.separator
to remain OS-independent. Backslashes work only on Windows.
I'd prefer to exit with double tap on the back button than with an exit Dialog.
In this solution, it show a toast when go back for the first time, warning that another back press will close the App. In this example less than 4 seconds.
private Toast toast;
private long lastBackPressTime = 0;
@Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(this, "Press back again to close this app", 4000);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}
Token from: http://www.androiduipatterns.com/2011/03/back-button-behavior.html
This forum on MSDN tells you.
Form.Close()
sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.If you do a
form1.Show()
orApplication.Run(new Form1())
, Dispose will be called whenClose()
is called.However, if you do
form1.ShowDialog()
to show the form modally, the form will not be disposed, and you'll need to callform1.Dispose()
yourself. I believe this is the only time you should worry about disposing the form yourself.
Its just to save a byte of data when we do javascript minification.
consider the below anonymous function
function (){}
To make the above as self invoking function we will generally change the above code as
(function (){}())
Now we added two extra characters (,)
apart from adding ()
at the end of the function which necessary to call the function. In the process of minification we generally focus to reduce the file size. So we can also write the above function as
!function (){}()
Still both are self invoking functions and we save a byte as well. Instead of 2 characters (,)
we just used one character !
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
<script type="text/javascript">
$(document).ready(function () {
var gridHeader = $('#<%=grdSiteWiseEmpAttendance.ClientID%>').clone(true); // Here Clone Copy of Gridview with style
$(gridHeader).find("tr:gt(0)").remove(); // Here remove all rows except first row (header row)
$('#<%=grdSiteWiseEmpAttendance.ClientID%> tr th').each(function (i) {
// Here Set Width of each th from gridview to new table(clone table) th
$("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
});
$("#GHead1").append(gridHeader);
$('#GHead1').css('position', 'top');
$('#GHead1').css('top', $('#<%=grdSiteWiseEmpAttendance.ClientID%>').offset().top);
});
</script>
<div class="row">
<div class="col-lg-12" style="width: auto;">
<div id="GHead1"></div>
<div id="divGridViewScroll1" style="height: 600px; overflow: auto">
<div class="table-responsive">
<asp:GridView ID="grdSiteWiseEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="8" HeaderStyle-Font-Names="Calibri" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
BackColor="#f0f5f5" OnRowDataBound="grdSiteWiseEmpAttendance_RowDataBound" HeaderStyle-ForeColor="#990000">
<Columns>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top" />
<RowStyle Font-Names="Calibri" ForeColor="#000000" />
</asp:GridView>
</div>
</div>
</div>
</div>
Here is a little snippet If you’re trying to check wether element contains a class, without using jQuery.
function hasClass(element, className) {
return element.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className);
}
This accounts for the fact that element might contain multiple class names separated by space.
OR
You can also assign this function to element prototype.
Element.prototype.hasClass = function(className) {
return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};
And trigger it like this (very similar to jQuery’s .hasClass()
function):
document.getElementById('MyDiv').hasClass('active');
Revert the project.pbxproj
svn revert --filename--
The BETWEEN operator is inclusive.
From Books Online:
BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.
DateTime Caveat
NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.
e.g. to get all values within June 2016 you'd need to run:
where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')
i.e.
where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'
Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:
where myDateTime >= '20160601' AND myDateTime < '20160701'
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
[Joke mode on]
You can fix this by adding this:
https://github.com/donavon/undefined-is-a-function
import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.
[joke mode off]
if sum of column is 0 then display empty
select if(sum(column)>0,sum(column),'')
from table
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"
Swift 4
I've had some minor issues when updating the ViewControllers view using UIDevice.current.orientation
, such as updating constraints of tableview cells during rotation or animation of subviews.
Instead of the above methods I am currently comparing the transition size to the view controllers view size. This seems like the proper way to go since one has access to both at this point in code:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
print("Will Transition to size \(size) from super view size \(self.view.frame.size)")
if (size.width > self.view.frame.size.width) {
print("Landscape")
} else {
print("Portrait")
}
if (size.width != self.view.frame.size.width) {
// Reload TableView to update cell's constraints.
// Ensuring no dequeued cells have old constraints.
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
Output on a iPhone 6:
Will Transition to size (667.0, 375.0) from super view size (375.0, 667.0)
Will Transition to size (375.0, 667.0) from super view size (667.0, 375.0)
That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid
and grab them via:
var uids = $(".uid").map(function() {
return this.value;
}).get();
Demo: http://jsfiddle.net/karim79/FtcnJ/
EDIT: say your output looks like the following (notice, IDs have changed to classes)
<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>
You can target the 'uid' relative to the clicked anchor like this:
$("a.aaf").click(function() {
alert($(this).next('.uid').val());
});
Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.
As it's an issue we face more than often, below are the steps to resolve it.
Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...
It should auto select Remote Tracking ? *origin/master. Press Merge.
Launch stage view in Eclipse.
Double click the files which initially showed conflict
In the conflict merge view, by selecting the left arrow for all the non-conflict + conflict changes from left to right, you can resolve all the conflicts.
Save the merged file.
Do a Team ? pull from Eclipse again.
You are all set :)
First, look here: http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C
My company has a C library our customers use. We use CxxTest (a C++ unit test library) to test the code. CppUnit will also work. If you're stuck in C, I'd recommend RCUNIT (but CUnit is good too).
Export the .ipa by checking the "with manifest plist checkbox" and provide the links requested.
Upload the .ipa file and .plist file to the same location of the server (which you provided when exporting .ipa/ which mentioned in the .plist file).
Create the Download Link as given below. url should link to your .plist file location.
itms-services://?action=download-manifest&url=https://yourdomainname.com/app.plist
Copy this link and paste it in safari browser in your iphone. It will ask to install :D
Create a html button using this full url
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace()
is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g
(global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
xmlns:tools="http://schemas.android.com/tools"
\n
for new line and \t
for space like tab.Example :
for \n : android:text="Welcome back ! \nPlease login to your account agilanbu"
for \t : android:text="Welcome back ! \tPlease login to your account agilanbu"
For converting an entire xml document to a pretty xml document
(ex: assuming you've extracted [unzipped] a LibreOffice Writer .odt or .ods file, and you want to convert the ugly "content.xml" file to a pretty one for automated git version control and git difftool
ing of .odt/.ods files, such as I'm implementing here)
import xml.dom.minidom
file = open("./content.xml", 'r')
xml_string = file.read()
file.close()
parsed_xml = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = parsed_xml.toprettyxml()
file = open("./content_new.xml", 'w')
file.write(pretty_xml_as_string)
file.close()
References:
- Thanks to Ben Noland's answer on this page which got me most of the way there.
Recently I am working with the 1.8.0_25 JDK version on Windows 8.1 and I had the same problem with this. But as PankaJ Jakhar said
The real solution for me was pretty simple:
The path I introduced for this variable was:
C:\Program Files\Java\jdk1.8.0_25\
And it works for me!
If you want to save data that is derived from a Javascript canvas.toDataURL()
function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:
<?php
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
?>
I would be inclined to include the year in the output. One way:
select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1
Another way (more standard SQL):
select extract(year from date_created) as yr, extract(month from date_created) as mon,
sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;
Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.
Use SQL Server Migration Assistant (SSMA)
In addition to MySQL it supports Oracle, Sybase and MS Access.
It appears to be quite smart and capable of handling even nontrivial transfers. It also got some command line interface (in addition to GUI) so theoretically it can be integrated into some batch load process.
This the current download link for MySQL version https://www.microsoft.com/en-us/download/details.aspx?id=54257
The current (June 2016) stable version 6.0.1 crashes with the current (5.3.6) MySQL ODBC driver while transferring data. Everything 64 bit. The 5.3 version with the 5.1.13 ODBC driver works fine.
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
I was in a process of switching from one version control service to another and needed to clone all repositories including all branches, tags and history.
To achieve above I did next:
git push origin '*:*'
.sh script used to checkout all branches to local repository:
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do
git branch --track ${branch#remotes/origin/} $branch
done
This works for me. Has a nice delayed action going on.
var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;
$(document).mousemove(function(e){
$mouseX = e.pageX;
$mouseY = e.pageY;
});
var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});
}, 30);
Nice and simples
Just go to File > Settings > Languages & Frameworks > Dart
Click on check box Enable Dart Support for project 'projectName' Paste the Dart SDK path.
This is how you get Dart SDK path, follow the given steps copy the Dart SDK Path, which is in Flutter SDK, Go to location where your Flutter SDK Situated, then,
Flutter/bin/cache/dart-sdk , till dart-sdk, copy the path and paste it.
I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(
//open upload window upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);
In JUnit 5 you can inject TestInfo
which simplifies test meta data providing to test methods. For example:
@Test
@DisplayName("This is my test")
@Tag("It is my tag")
void test1(TestInfo testInfo) {
assertEquals("This is my test", testInfo.getDisplayName());
assertTrue(testInfo.getTags().contains("It is my tag"));
}
See more: JUnit 5 User guide, TestInfo javadoc.
If you want to select only one of two nodes with union operator, you can use this solution:
(//bookstore/book/title | //bookstore/city/zipcode/title)[1]
This is how I did it in React:
import MyPDF from '../path/to/file.pdf';
<a href={myPDF} download="My_File.pdf"> Download Here </a>
It's important to override the default file name with download="name_of_file_you_want.pdf"
or else the file will get a hash number attached to it when you download.
I had the same problem. (My problem is with gradle 4.4 files)
Actually the problem is incorrect downloading of 4.4 gradle which already I had.
When I delete gradle 4.4 version
C:\Users\$Your_User\.gradle\wrapper\dists\gradle-4.4-all
Android studio again downloads gradle-4.4 and syncs with my project.
Now it had rectified with the help of Michelin Man
Thanks for your answer Michelin
Use the following code for getting lat and long using php. Here are two methods:
<?php
// Get lat and long by address
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
?>
edit - Google Maps requests must be over https
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.804400, -1.147250);
var mapOptions = {
zoom: 6,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
}
function codeAddress(address,tutorname,url,distance,prise,postcode) {
var address = address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
});
infowindow.open(map,marker);
} /*else {
alert('Geocode was not successful for the following reason: ' + status);
}*/
});
}
google.maps.event.addDomListener(window, 'load', initialize);
window.onload = function(){
initialize();
// your code here
<?php foreach($addr as $add) {
?>
codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
<?php } ?>
};
</script>
<div id="map-canvas12"></div>
Here is a pretty simple socket program. This is about as simple as sockets get.
for the client program(CPU 1)
import socket
s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"
You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.
For the server program(CPU 2)
import socket
s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send("Server approved connection\n")
print repr(addr[1]) + ": " + c.recv(1026)
c.close()
Run the server program and then the client one.
About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.
The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).
You can use the latest version of the jQuery library by any of the following.
Google Ajax API CDN (also supports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2"></script>
/jquery.min.js
Microsoft CDN (also aupports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
Ajax CDN Announcement, Microsoft Ajax CDN Documentation
jQuery CDN (via Media Temple)
<script type="text/javascript" src=" http://code.jquery.com/jquery-1.7.2.min.js"></script>
** Minified version
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
** Development (Full) version
If you want to cast it to specific type (e.g. within tests) you can use ReadAsAsync extension method:
object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));
or following for synchronous code:
object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;
Update: there is also generic option of ReadAsAsync<> which returns specific type instance instead of object-declared one:
YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();
I had to add X-Frame-Options for IE and Content-Security-Policy for other browsers. So i did something like following.
if allowed_domains.present?
request_host = URI.parse(request.referer)
_domain = allowed_domains.split(" ").include?(request_host.host) ? "#{request_host.scheme}://#{request_host.host}" : app_host
response.headers['Content-Security-Policy'] = "frame-ancestors #{_domain}"
response.headers['X-Frame-Options'] = "ALLOW-FROM #{_domain}"
else
response.headers.except! 'X-Frame-Options'
end
The implicit make rule for compiling a C program is
%.o:%.c
$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
where the $()
syntax expands the variables. As both CPPFLAGS
and CFLAGS
are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c
is a file in the current directory
make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"
will both call your compiler in exactly the same way, namely
gcc -I/usr/include -c -o foo.o foo.c
The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp
then try
make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"
then the compilations will be
g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp
as the C++ implicit rule also uses the CPPFLAGS
variable.
This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS
, if it's for a specific language put it in CFLAGS
, CXXFLAGS
etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99
to your C++ compiler!
You might then end up with something like this in your makefile
CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++
You actually had it correct in your third attempt.
<select ng-model="myselect" ng-options="o as o for o in options"></select>
See a working example here: http://plnkr.co/edit/xEERH2zDQ5mPXt9qCl6k?p=preview
The trick is that AngularJS writes the keys as numbers from 0 to n anyway, and translates back when updating the model.
As a result, the HTML will look incorrect but the model will still be set properly when choosing a value. (i.e. AngularJS will translate '0' back to 'var1')
The solution by Epokk also works, however if you're loading data asynchronously you might find it doesn't always update correctly. Using ngOptions will correctly refresh when the scope changes.
If you are using VS Code with flutter, you should find it in your app folder, under the android folder:
C:\myappFolder\android
You can run this in the terminal:
./gradlew signingReport
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
Vertical alignment only works on inline elements. If you float it, then I don't think it is treated as part of that stream of inline elements any more.
Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):
input {
width: 20px;
position: relative;
left: 200px;
vertical-align: middle;
}
label {
width: 200px;
position: relative;
left: -20px;
display: inline-block;
vertical-align: middle;
}
Fixed it with -no-pie
option in linker stage:
g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...
You can use flexbox to lay out your items:
#parent {_x000D_
display: flex;_x000D_
}_x000D_
#narrow {_x000D_
width: 200px;_x000D_
background: lightblue;_x000D_
/* Just so it's visible */_x000D_
}_x000D_
#wide {_x000D_
flex: 1;_x000D_
/* Grow to rest of container */_x000D_
background: lightgreen;_x000D_
/* Just so it's visible */_x000D_
}
_x000D_
<div id="parent">_x000D_
<div id="wide">Wide (rest of width)</div>_x000D_
<div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
This is basically just scraping the surface of flexbox. Flexbox can do pretty amazing things.
For older browser support, you can use CSS float and a width properties to solve it.
#narrow {_x000D_
float: right;_x000D_
width: 200px;_x000D_
background: lightblue;_x000D_
}_x000D_
#wide {_x000D_
float: left;_x000D_
width: calc(100% - 200px);_x000D_
background: lightgreen;_x000D_
}
_x000D_
<div id="parent">_x000D_
<div id="wide">Wide (rest of width)</div>_x000D_
<div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
For a new document: Settings -> Preferences -> New Document/Default Directory
-> New Document -> Format -> Windows/Mac/Unix
And for an already-open document: Edit -> EOL Conversion
There are lots of great answers which discuss differences in the use cases for each function. None of the answer discuss the differences in performance. That is reasonable cause various functions expects various input and produces various output, yet most of them have a general common objective to evaluate by series/groups. My answer is going to focus on performance. Due to above the input creation from the vectors is included in the timing, also the apply
function is not measured.
I have tested two different functions sum
and length
at once. Volume tested is 50M on input and 50K on output. I have also included two currently popular packages which were not widely used at the time when question was asked, data.table
and dplyr
. Both are definitely worth to look if you are aiming for good performance.
library(dplyr)
library(data.table)
set.seed(123)
n = 5e7
k = 5e5
x = runif(n)
grp = sample(k, n, TRUE)
timing = list()
# sapply
timing[["sapply"]] = system.time({
lt = split(x, grp)
r.sapply = sapply(lt, function(x) list(sum(x), length(x)), simplify = FALSE)
})
# lapply
timing[["lapply"]] = system.time({
lt = split(x, grp)
r.lapply = lapply(lt, function(x) list(sum(x), length(x)))
})
# tapply
timing[["tapply"]] = system.time(
r.tapply <- tapply(x, list(grp), function(x) list(sum(x), length(x)))
)
# by
timing[["by"]] = system.time(
r.by <- by(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)
# aggregate
timing[["aggregate"]] = system.time(
r.aggregate <- aggregate(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)
# dplyr
timing[["dplyr"]] = system.time({
df = data_frame(x, grp)
r.dplyr = summarise(group_by(df, grp), sum(x), n())
})
# data.table
timing[["data.table"]] = system.time({
dt = setnames(setDT(list(x, grp)), c("x","grp"))
r.data.table = dt[, .(sum(x), .N), grp]
})
# all output size match to group count
sapply(list(sapply=r.sapply, lapply=r.lapply, tapply=r.tapply, by=r.by, aggregate=r.aggregate, dplyr=r.dplyr, data.table=r.data.table),
function(x) (if(is.data.frame(x)) nrow else length)(x)==k)
# sapply lapply tapply by aggregate dplyr data.table
# TRUE TRUE TRUE TRUE TRUE TRUE TRUE
# print timings
as.data.table(sapply(timing, `[[`, "elapsed"), keep.rownames = TRUE
)[,.(fun = V1, elapsed = V2)
][order(-elapsed)]
# fun elapsed
#1: aggregate 109.139
#2: by 25.738
#3: dplyr 18.978
#4: tapply 17.006
#5: lapply 11.524
#6: sapply 11.326
#7: data.table 2.686
goto window properties set
window style = none;
u wont get close buttons...
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
Well, since this is such a hot topic... here is what works for me. I got errors if I didn't do it this way because Activate() will error out on you if you cannot see the window.
Xaml:
<Window ....
Topmost="True"
....
ContentRendered="mainWindow_ContentRendered"> .... </Window>
Codebehind:
private void mainWindow_ContentRendered(object sender, EventArgs e)
{
this.Topmost = false;
this.Activate();
_UsernameTextBox.Focus();
}
This was the only way for me to get the window to show on top. Then activate it so you can type in the box without having to set focus with the mouse. control.Focus() wont work unless the window is Active();
A possible solution is to think about it backwards: Accept a float as input and reject the input if the float is not an integer:
int n;
float f;
printf("Please enter an integer: ");
while(scanf("%f",&f)!=1 || (int)f != f)
{
...
}
n = f;
Though this does allow the user to enter something like 12.0, or 12e0, etc.
lencioni's answer is what I'd recommend. You can change the selector for the option ('#mySelect option:last')
to select the option with a specific value using "#mySelect option[value='yourDefaultValue']
". More on selectors.
If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/. Take a look the source if you want to see some more examples of working with select lists.
for python language, you can do like this
import pymysql
connection = pymysql.connect(host='localhost',
user='root',
db='mysql',
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
cursor.execute('SHOW PROCESSLIST')
for item in cursor.fetchall():
if item.get('Time') > 200:
_id = item.get('Id')
print('kill %s' % item)
cursor.execute('kill %s', _id)
connection.close()
If you want to drop column(s) from the target data frame, but the column(s) are required for the join, you can do the following:
df1 = df1.merge(df2[['a', 'b', 'key1']], how = 'left',
left_on = 'key2', right_on = 'key1').drop('key1')
The .drop('key1')
part will prevent 'key1' from being kept in the resulting data frame, despite it being required to join in the first place.
There are several ways to do it, but here is one solution (for 4 columns).
string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);
And a more verbose way is here:
ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");
ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");
ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");
ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});
"Do you know if there's a way to make this work with relative selections, so that the formula can be "dragged down"/applied across several cells in the same column?"
To make such selection relative simply use ROW formula for a row number in INDEX formula and COLUMN formula for column number in INDEX formula. To make this clearer here is the example:
=INDEX(named_range,ROW(A1),COLUMN(A1))
Assuming the named range starts at A1 this formula simply indexes that range by row and column number of referenced cell and since that reference is relative it changes when you drag the the cell down or to the side, which makes it possible to create whole array of cells easily.
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
W3C's recommendation:
If designing a form or database that will accept names from people with a variety of backgrounds, you should ask yourself whether you really need to have separate fields for given name and family name.
… Bear in mind that names in some cultures can be quite a lot longer than your own. … Avoid limiting the field size for names in your database. In particular, do not assume that a four-character Japanese name in UTF-8 will fit in four bytes – you are likely to actually need 12.
https://www.w3.org/International/questions/qa-personal-names
For database fields, VARCHAR(255)
is a safe default choice, unless you can actually come up with a good reason to use something else. For typical web applications, performance won't be a problem. Don't prematurely optimize.
I also found that when I uninstalled nunit v3.2.1, the nunit framework reference for v3.2.1 was still in my project in solution explorer. Solution Explorer > ProjectName > References
If you right click it will show the version. Remove this Then Right click on References > Add Reference.
Search for the version 2.x version and add then rebuild solution.
That worked for me!
Using Visual Studio 2019, I followed below steps to make the project name change successful:
So imagine everyone is trying to go to the bathroom and there's only a certain number of keys to the bathroom. Now if there's not enough keys left, that person needs to wait. So think of semaphore as representing those set of keys available for bathrooms (the system resources) that different processes (bathroom goers) can request access to.
Now imagine two processes trying to go to the bathroom at the same time. That's not a good situation and semaphores are used to prevent this. Unfortunately, the semaphore is a voluntary mechanism and processes (our bathroom goers) can ignore it (i.e. even if there are keys, someone can still just kick the door open).
There are also differences between binary/mutex & counting semaphores.
Check out the lecture notes at http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html.
labelName.font = labelName.font.withSize(15)
If you are using reactive forms in Angular 2+, you can remove leading and trailing spaces with the help of (blur)
app.html
<input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />
app.ts
public trimLeadingAndTrailingSpaces(formControl: AbstractControl) {
if (formControl && formControl.value && typeof formControl.value === 'string') {
formControl.setValue(formControl.value.trim());
}
}
Check Below Codes :
1. SynchronousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err: NSError
println(response)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
println("Synchronous\(jsonResult)")
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
do{
let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)
print(response)
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
print("Synchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}catch let error as NSError
{
print(error.localizedDescription)
}
2. AsynchonousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("Asynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
3. As usual URL connection
Swift 1.2
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.dataVal?.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
var error: NSErrorPointer=nil
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
println(jsonResult)
}
Swift 2.0 +
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
dataVal.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
4. Asynchronous POST Request
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
var stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
let stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
5. Asynchronous GET Request
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
request1.timeoutInterval = 60
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous\(jsonResult)")
})
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
6. Image(File) Upload
Swift 2.0 +
let mainURL = "YOUR_URL_HERE"
let url = NSURL(string: mainURL)
let request = NSMutableURLRequest(URL: url!)
let boundary = "78876565564454554547676"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST" // POST OR PUT What you want
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)
var body = NSMutableData()
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your parameters
body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your Image/File Data
var imageNameval = "HELLO.jpg"
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
//handle error
}
else {
let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
print("Response:\(outputString)")
}
}
dataTask.resume()
7. GET,POST,Etc Swift 3.0 +
let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:60)
request.httpMethod = "POST" // POST ,GET, PUT What you want
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("ASynchronous\(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
dataTask.resume()
One important thing to note about ng-if and ng-show is that when using form controls it is better to use ng-if
because it completely removes the element from the dom.
This difference is important because if you create an input field with required="true"
and then set ng-show="false"
to hide it, Chrome will throw the following error when the user tries to submit the form:
An invalid form control with name='' is not focusable.
The reason being the input field is present and it is required
but since it is hidden Chrome cannot focus on it. This can literally break your code as this error halts script execution. So be careful!
I had the exact same symptom, and this was my problem, very tricky to track down, so I hope it helps someone.
I was using JQuery parseJSON()
and the content I was attempting to parse was actually not JSON, but an error page that was being returned.
To be perfectly precise, Darwin is enough. No need to import the whole Cocoa framework.
import Darwin
Of course, if you need elements from Cocoa or Foundation or other higher level frameworks, you can import them instead
Tested as working:
#Must be the first statement in your script (not coutning comments)
param([Int32]$step=30)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}
Call it with
powershell.exe -file itunesForward.ps1 -step 15
Multiple parameters syntax (comments are optional, but allowed):
<#
Script description.
Some notes.
#>
param (
# height of largest column without top bar
[int]$h = 4000,
# name of the output image
[string]$image = 'out.png'
)
You can also use jq to track down the array within the returned json and then pipe that in to a second jq
call to get its length. Suppose it was in a property called records
, like {"records":[...]}
.
$ curl https://my-source-of-json.com/list | jq -r '.records' | jq length
2
$
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
Show All Markers with Google map
In these Methods store all Markers and automatically zoom to show all markers in google map.
// Declare the Markers List.
List<MarkerOptions> markerList;
private BitmapDescriptor vnrPoint,banPoint;
public void storeAllMarkers()
{
markerList=new ArrayList<>();
markerList.removeAll(markerList);
// latitude and longitude of Virudhunagar
double latitude1=9.587209;
double longitude1=77.951431;
vnrPoint=BitmapDescriptorFactory.fromResource(R.drawable.location_icon_1);
LatLng vnr = new LatLng(latitude1, longitude1);
MarkerOptions vnrMarker = new MarkerOptions();
vnrMarker.position(vnr);
vnrMarker.icon(vnrPoint);
markerList.add(vnrMarker);
// latitude and longitude of Bengaluru
double latitude2=12.972442;
double longitude2=77.580643;
banPoint=BitmapDescriptorFactory.fromResource(R.drawable.location_icon_2);
LatLng ban = new LatLng(latitude2, longitude2);
MarkerOptions bengalureMarker = new MarkerOptions();
bengalureMarker.position(ban);
bengalureMarker.icon(banPoint);
markerList.add(bengalureMarker);
// You can add any numbers of MarkerOptions like this.
showAllMarkers();
}
public void showAllMarkers()
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions m : markerList) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.30);
// Zoom and animate the google map to show all markers
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
googleMap.animateCamera(cu);
}
Give unique class and different id for file input
$("#tab-content").on('change',class,function()
{
var id=$(this).attr('id');
$("#"+id).trigger(your function);
//for name of file input $("#"+id).attr("name");
});
It's just what it says:
inputFile = open((x), encoding = "utf8", "r")
You have specified encoding
as a keyword argument, but "r"
as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:
inputFile = open((x), "r", encoding = "utf8")
In Ubuntu 14.04.2 LTS:
Go to Software Center and remove "IDLE(using Python-2.7)".
Install "IDLE(using Python-3.4)".
Try again. This step worked for me.
You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.
Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.
EDIT:
alias myapp c:\myapp\
I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.
A simple way is to write it:
Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
msgbox "There is no records"
End if
For me, my issue was that I was
android:background="?attr/selectableItemBackground"
To a LinearLayout background, once I removed it the test passed.
In MySQL Workbench 6.1
.
I had to click on the Apply changes
button in the insertion panel (only once, because twice and MWB crashes...).
You have to do it for each of your table.
Generate INSERT statements for table
Try adding JRE System Library in the build path of your project.
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
Here is an example for MySQL for looping through a comma delimited string.
DECLARE v_delimited_string_access_index INT;
DECLARE v_delimited_string_access_value VARCHAR(255);
DECLARE v_can_still_find_values_in_delimited_string BOOLEAN;
SET v_can_still_find_values_in_delimited_string = true;
SET v_delimited_string_access_index = 0;
WHILE (v_can_still_find_values_in_delimited_string) DO
SET v_delimited_string_access_value = get_from_delimiter_split_string(in_array, ',', v_delimited_string_access_index); -- get value from string
SET v_delimited_string_access_index = v_delimited_string_access_index + 1;
IF (v_delimited_string_access_value = '') THEN
SET v_can_still_find_values_in_delimited_string = false; -- no value at this index, stop looping
ELSE
-- DO WHAT YOU WANT WITH v_delimited_string_access_value HERE
END IF;
END WHILE;
this uses the get_from_delimiter_split_string
function defined here: https://stackoverflow.com/a/59666211/3068233
There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
Algorithm starts with 1 as first approximation for square root value.
Then, on each step, it improves next approximation by taking average between current value y
and x/y
. If y
= sqrt(x)
, it will be the same. If y
> sqrt(x)
, then x/y
< sqrt(x)
by about the same amount. In other words, it will converge very fast.
UPDATE: To speed up convergence on very large or very small numbers, changed sqrt()
function to extract binary exponent and compute square root from number in [1, 4)
range. It now needs frexp()
from <math.h>
to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp()
.
To do this using Python code:
importlib.metadata.version
import importlib.metadata
importlib.metadata.version('beautifulsoup4')
'4.9.1'
(using importlib_metadata.version
)
!pip install importlib-metadata
import importlib_metadata
importlib_metadata.version('beautifulsoup4')
'4.9.1'
pkg_resources.Distribution
import pkg_resources
pkg_resources.get_distribution('beautifulsoup4').version
'4.9.1'
pkg_resources.get_distribution('beautifulsoup4').parsed_version
<Version('4.9.1')>
Credited to comments by sinoroc and mirekphd.
One solution is to make another process to perform your read of the process, or make a thread of the process with a timeout.
Here's the threaded version of a timeout function:
http://code.activestate.com/recipes/473878/
However, do you need to read the stdout as it's coming in? Another solution may be to dump the output to a file and wait for the process to finish using p.wait().
f = open('myprogram_output.txt','w')
p = subprocess.Popen('myprogram.exe', stdout=f)
p.wait()
f.close()
str = open('myprogram_output.txt','r').read()
The difference between npm install and npm update handling of package versions specified in package.json:
{
"name": "my-project",
"version": "1.0", // install update
"dependencies": { // ------------------
"already-installed-versionless-module": "*", // ignores "1.0" -> "1.1"
"already-installed-semver-module": "^1.4.3" // ignores "1.4.3" -> "1.5.2"
"already-installed-versioned-module": "3.4.1" // ignores ignores
"not-yet-installed-versionless-module": "*", // installs installs
"not-yet-installed-semver-module": "^4.2.1" // installs installs
"not-yet-installed-versioned-module": "2.7.8" // installs installs
}
}
Summary: The only big difference is that an already installed module with fuzzy versioning ...
npm install
npm update
Additionally: install
and update
by default handle devDependencies differently
npm install
will install/update devDependencies unless --production
flag is addednpm update
will ignore devDependencies unless --dev
flag is addedWhy use npm install
at all?
Because npm install
does more when you look besides handling your dependencies in package.json
.
As you can see in npm install you can ...
PATH
) using npm install -g <name>
--force
A handle is like a primary key value of a record in a database.
edit 1: well, why the downvote, a primary key uniquely identifies a database record, and a handle in the Windows system uniquely identifies a window, an opened file, etc, That's what I'm saying.
The best way to do this is here i found after searching for one issue after other in the LogCat
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
Not releasing the Media player gives you this error in LogCat:
Android: MediaPlayer finalized without being released
Not resetting the Media player gives you this error in LogCat:
Android: mediaplayer went away with unhandled events
So play safe and simple code to use media player.
To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like
mp = MediaPlayer.create(context, R.raw.sound_two);
and play it !
Have fun!
HTML Code
<html>
<body>
<head>
<title></title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
//============================= DATABASE CONNECTIVITY d ====================
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
//============================= DATABASE CONNECTIVITY u ====================
//============================= Retrieve data from DB d ====================
$sql = "SELECT name, size, type FROM videos";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
$path = "uploaded/" . $row["name"];
echo $path . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
//============================= Retrieve data from DB d ====================
?>
</body>
</html>
You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest
.
package hello.easymock.constructor;
import java.io.File;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
@Test
public void testMockFile() throws Exception {
// first, create a mock for File
final File fileMock = EasyMock.createMock(File.class);
EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
EasyMock.replay(fileMock);
// then return the mocked object if the constructor is invoked
Class<?>[] parameterTypes = new Class[] { String.class };
PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
PowerMock.replay(File.class);
// try constructing a real File and check if the mock kicked in
final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
Assert.assertEquals("/my/fake/file/path", mockedFilePath);
}
}
Update of @param's answer.
ICS emulator supports camera.
I found Simple Android Photo Capture, which supports webcam in android emulator.
The simple answer to your question is that there is no Annotation-Inheritance in Java. However, there is a way to use the Spring annotations in a way that I think will help solve your problem.
@RequestMapping is supported at both the type level and at the method level.
When you put @RequestMapping
at the type level, most of the attributes are 'inherited' for each method in that class. This is mentioned in the Spring reference documentation. Look at the api docs for details on how each attribute is handled when adding @RequestMapping
to a type. I've summarized this for each attribute below:
name
: Value at Type level is concatenated with value at method level using '#' as a separator.value
: Value at Type level is inherited by method.path
: Value at Type level is inherited by method.method
: Value at Type level is inherited by method.params
: Value at Type level is inherited by method.headers
: Value at Type level is inherited by method.consumes
: Value at Type level is overridden by method.produces
: Value at Type level is overridden by method.Here is a brief example Controller that showcases how you could use this:
package com.example;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "/",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE,
method = {RequestMethod.GET, RequestMethod.POST})
public class JsonProducingEndpoint {
private FooService fooService;
@RequestMapping(path = "/foo", method = RequestMethod.POST)
public String postAFoo(@RequestBody ThisIsAFoo theFoo) {
fooService.saveTheFoo(theFoo);
return "http://myservice.com/foo/1";
}
@RequestMapping(path = "/foo/{id}", method = RequestMethod.GET)
public ThisIsAFoo getAFoo(@PathVariable String id) {
ThisIsAFoo foo = fooService.getAFoo(id);
return foo;
}
@RequestMapping(path = "/foo/{id}", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public ThisIsAFooXML getAFooXml(@PathVariable String id) {
ThisIsAFooXML foo = fooService.getAFoo(id);
return foo;
}
}
Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat]
attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407
Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.
Model:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Birth)
@Html.EditorFor(x => x.Birth)
@Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
Registration of the custom model binder in Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
And the custom model binder itself:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Now, no matter what culture you have setup in your web.config (<globalization>
element) or the current thread culture, the custom model binder will use the DisplayFormat
attribute's date format when parsing nullable dates.
Solution for Java 8. A bit longer than the Guava one, but at least you don't have to install a library.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
//...
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<String> strings = integers.stream().map(Object::toString)
.collect(Collectors.toList());
HTML5 does not directly support requiring only one/at least one checkbox be checked in a checkbox group. Here is my solution using Javascript:
HTML
<input class='acb' type='checkbox' name='acheckbox[]' value='1' onclick='deRequire("acb")' required> One
<input class='acb' type='checkbox' name='acheckbox[]' value='2' onclick='deRequire("acb")' required> Two
JAVASCRIPT
function deRequireCb(elClass) {
el=document.getElementsByClassName(elClass);
var atLeastOneChecked=false;//at least one cb is checked
for (i=0; i<el.length; i++) {
if (el[i].checked === true) {
atLeastOneChecked=true;
}
}
if (atLeastOneChecked === true) {
for (i=0; i<el.length; i++) {
el[i].required = false;
}
} else {
for (i=0; i<el.length; i++) {
el[i].required = true;
}
}
}
The javascript will ensure at least one checkbox is checked, then de-require the entire checkbox group. If the one checkbox that is checked becomes un-checked, then it will require all checkboxes, again!
Just use ||
if (A || B) { your action here }
Note: with string and number. It's more complicated.
Check this for deep understading:
This is how you can do it from DB2 client.
Open the Command Editor and Run the select Query in the Commands Tab.
Open the corresponding Query Results Tab
Then from Menu --> Selected --> Export
The solution was to use getChildFragmentManager()
instead of getFragmentManager()
when calling from a fragment. If you are calling the method from an activity, then use getFragmentManager()
.
That will solve the problem.
You can force it to push, but please do this ONLY when you're quite sure what you are doing.
The command is:
git push -f
your markup was a bit messed up. Here's the styles you need and proper html
CSS:
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
HTML:
<nav class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</nav>
Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/
Try saving your .c file before building. I believe your computer is referencing a path to a file with no information inside of it.
--Had similar issue when building C projects
In my case, I had to add using System.Data.Entity;
I think this can also works for you select count(*) as anc,(select count(*) from Patient where sex='F')as patientF,(select count(*) from Patient where sex='M') as patientM from anc
and also you can select and count related tables like this select count(*) as anc,(select count(*) from Patient where Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where sex='M') as patientM from anc
Check whether you server is running or not.
Just FYI, you could use the VB.NET Like-Operator:
string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);
Use CompareMethod.Text
if you want to ignore the case.
You need to add using Microsoft.VisualBasic.CompilerServices;
.
I spent a few hours on this too ... and agree that FLAG_ACTIVITY_CLEAR_TOP sounds like what you'd want: clear the entire stack, except for the activity being launched, so the Back button exits the application. Yet as Mike Repass mentioned, FLAG_ACTIVITY_CLEAR_TOP only works when the activity you're launching is already in the stack; when the activity's not there, the flag doesn't do anything.
What to do? Put the activity being launching in the stack with FLAG_ACTIVITY_NEW_TASK, which makes that activity the start of a new task on the history stack. Then add the FLAG_ACTIVITY_CLEAR_TOP flag.
Now, when FLAG_ACTIVITY_CLEAR_TOP goes to find the new activity in the stack, it'll be there and be pulled up before everything else is cleared.
Here's my logout function; the View parameter is the button to which the function's attached.
public void onLogoutClick(final View view) {
Intent i = new Intent(this, Splash.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
One-liner that downloads and automatically installs when the download is finished.
curl --http1.1 https://bootstrap.pypa.io/get-pip.py --output get-pip.py && python get-pip.py
Check this out.
var timeout_;
function mouseDown_i() {
value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
document.getElementById('xxxx').value = value + 1;
timeout_ = setTimeout(function() { mouseDown_i(); }, 150);
}
function mouseDown_d() {
value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
value - 1 <= 0 ? document.getElementById('xxxx').value = '' : document.getElementById('xxxx').value = value - 1;
timeout_ = setTimeout(function() { mouseDown_d(); }, 150);
}
function mouseUp() { clearTimeout(timeout_); }
function mouseLeave() { clearTimeout(timeout_); }
_x000D_
<p onmousedown="mouseDown_i()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to INCREMENT!</p>
<p onmousedown="mouseDown_d()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to DECREMENT!</p>
<input id="xxxx" type="text" value="0">
_x000D_
public class StringToLong {
public static void main (String[] args) {
// String s = "fred"; // do this if you want an exception
String s = "100";
try {
long l = Long.parseLong(s);
System.out.println("long l = " + l);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
You could use the built-in module pprint (https://docs.python.org/3.9/library/pprint.html).
How you can read the file with json data and print it out.
import json
import pprint
json_data = None
with open('file_name.txt', 'r') as f:
data = f.read()
json_data = json.loads(data)
pprint.pprint(json_data)
Use "\n":
file.write("My String\n")
See the Python manual for reference.
SELECT *
FROM customer
WHERE joiningdate >= NOW();
Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx
int atoi(
const char *str
);
int _wtoi(
const wchar_t *str
);
int _atoi_l(
const char *str,
_locale_t locale
);
int _wtoi_l(
const wchar_t *str,
_locale_t locale
);
CString is wchar_t string. So, if you want convert Cstring to int, you can use:
CString s;
int test = _wtoi(s)
I've written a plugin that does this called alterClass – Remove element classes with wildcard matching. Optionally add classes: https://gist.github.com/1517285
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
Try using below Query:
SELECT
GROUP,
COUNT(*) AS Total_Count
FROM
TABLE
GROUP BY
GROUP
ORDER BY
Total_Count DESC
public static void main(String[] args) {
try {
String ss = null;
Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
BufferedWriter writeer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writeer.write("dir");
writeer.flush();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
while ((ss = stdInput.readLine()) != null) {
System.out.println(ss);
}
System.out.println("Here is the standard error of the command (if any):\n");
while ((ss = stdError.readLine()) != null) {
System.out.println(ss);
}
} catch (IOException e) {
System.out.println("FROM CATCH" + e.toString());
}
}
Your problem has nothing to do with encodings, it's a simple matter of understanding basic C++. You are returning a pointer to a local variable from your function, which will have gone out of scope by the time anyone can use it, thus creating undefined behaviour (i.e. a programming error).
Follow this Golden Rule: "If you are using naked char pointers, you're Doing It Wrong. (Except for when you aren't.)"
I've previously posted some code to do the conversion and communicating the input and output in C++ std::string
and std::wstring
objects.
Using a HTTP debugging proxy can cause this - such as Fiddler.
I was loading a PFX certificate from a local file (authentication to Apple.com) and it failed because Fiddler wasn't able to pass this certificate on.
Try disabling Fiddler to check and if that is the solution then you need to probably install the certificate on your machine or in some way that Fiddler can use it.
You can also simply use the HtmlString
class
@(new HtmlString(Model.Content))
My function checks if number is +ve and could be have decimal value as well.
function validateNumeric(numValue){
var value = parseFloat(numValue);
if (!numValue.toString().match(/^[-]?\d*\.?\d*$/))
return false;
else if (numValue < 0) {
return false;
}
return true;
}
I suggest Pdfkit. (installation guide)
It creates pdf from html files. I chose it to create pdf in 2 steps from my Python Pyramid stack:
pdfkit.from_string(...)
method by passing the rendered html as parameterThis way you get a pdf document with styling and images supported.
You can install it as follows :
using pip
pip install pdfkit
If you wanted a framework-esq syntax (Note: IE 8+ support only), you could extend the Element
prototype and add your own setAttributes
function:
Element.prototype.setAttributes = function (attrs) {
for (var idx in attrs) {
if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
} else if (idx === 'html') {
this.innerHTML = attrs[idx];
} else {
this.setAttribute(idx, attrs[idx]);
}
}
};
This lets you use syntax like this:
var d = document.createElement('div');
d.setAttributes({
'id':'my_div',
'class':'my_class',
'styles':{
'backgroundColor':'blue',
'color':'red'
},
'html':'lol'
});
Try it: http://jsfiddle.net/ywrXX/1/
If you don't like extending a host object (some are opposed) or need to support IE7-, just use it as a function
Note that setAttribute
will not work for style
in IE, or event handlers (you shouldn't anyway). The code above handles style
, but not events.
Documentation
setAttribute
on MDN - https://developer.mozilla.org/en-US/docs/DOM/element.setAttributePlain Javascript Solution (DEMO) :
<br/><br/><br/><br/><br/><br/><br/>
<div>
<div id="myyy_bar" style="background:red;"> Here is window </div>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar");
var EnableConsoleLOGS = true; //to check the results in Browser's Inspector(Console), whenever you are scrolling
// ==============================================
window.addEventListener('scroll', function (evt) {
var Positionsss = GetTopLeft ();
if (EnableConsoleLOGS) { console.log(Positionsss); }
if (Positionsss.toppp > 70) { myyElement.style.position="relative"; myyElement.style.top = "0px"; myyElement.style.right = "auto"; }
else { myyElement.style.position="fixed"; myyElement.style.top = "100px"; myyElement.style.right = "0px"; }
});
function GetOffset (object, offset) {
if (!object) return;
offset.x += object.offsetLeft; offset.y += object.offsetTop;
GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
if (!object) return;
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html") { GetScrolled (object.parentNode, scrolled); }
}
function GetTopLeft () {
var offset = {x : 0, y : 0}; GetOffset (myyElement.parentNode, offset);
var scrolled = {x : 0, y : 0}; GetScrolled (myyElement.parentNode.parentNode, scrolled);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>
The problem is you are not linking to the jQuery UI library (which is where datepicker resides):
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<div class="demo">
<p>Date: <input type="text" id="datepicker"></p>
</div><!-- End demo -->
</body>
</HTML>
it's very simple how to replace with Fragment.
DataFromDb changeActivity = new DataFromDb();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.changeFrg, changeActivity);
transaction.commit();
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
How I do it with openpyxl lib:
import csv
from openpyxl import Workbook
def convert_csv_to_xlsx(self):
wb = Workbook()
sheet = wb.active
CSV_SEPARATOR = "#"
with open("my_file.csv") as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
for idx, val in enumerate(col.split(CSV_SEPARATOR)):
cell = sheet.cell(row=r+1, column=idx+1)
cell.value = val
wb.save("my_file.xlsx")
Here is the link for installation details: http://php.net/manual/en/mysqli.installation.php
If you are using Windows or Linux:
- The MySQLi extension is automatically installed in most cases, when PHP & MySQL package is installed.
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
Yes! you can do so without writing any Java/Kotlin code, only XML by using this small library I created, which does so at buildtime, so your app won't be affected by it: https://github.com/LikeTheSalad/android-string-reference
Usage
Your strings:
<resources>
<string name="app_name">My App Name</string>
<string name="template_welcome_message">Welcome to ${app_name}</string>
</resources>
The generated string after building:
<!--resolved.xml-->
<resources>
<string name="welcome_message">Welcome to My App Name</string>
</resources>
HTML CODE
<div id="borderLoader" data-height="230px" data-color="lightgrey" data-
width="230px" data-image="https://fiverr- res.cloudinary.com/t_profile_thumb,q_auto,f_auto/attachments/profile/photo/a54f24b2ab6f377ea269863cbf556c12-619447411516923848661/913d6cc9-3d3c-4884-ac6e-4c2d58ee4d6a.jpg">
</div>
JS CODE
var dataValue, dataSet,key;
dataValue = document.getElementById('borderLoader');
//data set contains all the dataset that you are to style the shape;
dataSet ={
"height":dataValue.dataset.height,
"width":dataValue.dataset.width,
"color":dataValue.dataset.color,
"imageBg":dataValue.dataset.image
};
dataValue.style.height = dataSet.height;
dataValue.style.width = dataSet.width;
dataValue.style.background = "#f3f3f3 url("+dataSet.imageBg+") no-repeat
center";
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
I've tried to activate env from Jenkins job (in bash) with
conda activate base
and it failed, so after many tries, this one worked for me (CentOS 7) :
source /opt/anaconda2/bin/activate base
Firstly, there could be two values that you're referring to:
Underlying Value
If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong
Then you can simply cast it to it's underlying type. Assuming it's an int
, you can do it like this:
int eValue = (int)enumValue;
However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to @JohnStock for the poke to clarify).
This example assigns each a new value, and show the value returned:
public enum MyEnum
{
MyValue1 = 34,
MyValue2 = 27
}
(int)MyEnum.MyValue2 == 27; // True
Index Value
The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.
If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.
Command for this is,
ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest
PRIMARY KEY (wardNo, BHTNo, TestID)
You can use Math.Ceiling
http://msdn.microsoft.com/en-us/library/system.math.ceiling%28v=VS.100%29.aspx
To define intersection that correctly takes into account the cardinality of the elements use Counter
:
from collections import Counter
>>> c1 = [1, 2, 2, 3, 4, 4, 4]
>>> c2 = [1, 2, 4, 4, 4, 4, 5]
>>> list((Counter(c1) & Counter(c2)).elements())
[1, 2, 4, 4, 4]
To remove the flutter debug banner, there are several possibilities :
1- The first one is to use the debugShowCheckModeBanner property in your MaterialApp widget .
Code :
MaterialApp(
debugShowCheckedModeBanner: false,
)
And then do a hot reload.
2-The second possibility is to hide debug mode banner in Flutter Inspector if you use Android Studio or IntelliJ IDEA .
3- The third possibility is to use Dart DevTools .
Grant permissions for that user is needed
Please don't use any library for this effect instead use the recommended way of doing it according to Google I/O. In your recyclerView's onBindViewHolder method do this:
final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
TransitionManager.beginDelayedTransition(recyclerView);
notifyDataSetChanged();
}
});
And for the cool effects that you wanted, use these as your list_item attributes:
android:background="@drawable/comment_background"
android:stateListAnimator="@animator/comment_selection"
where comment_background is:
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true"
android:enterFadeDuration="@android:integer/config_shortAnimTime"
android:exitFadeDuration="@android:integer/config_shortAnimTime">
<item android:state_activated="true" android:drawable="@color/selected_comment_background" />
<item android:drawable="@color/comment_background" />
</selector>
and comment_selection is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<objectAnimator
android:propertyName="translationZ"
android:valueTo="@dimen/z_card"
android:duration="2000"
android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
<item>
<objectAnimator
android:propertyName="translationZ"
android:valueTo="0dp"
android:duration="2000"
android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
</selector>
All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:
<html>
<head>
<script>
function myFunction(){
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>
Better you can use the Webclient class to simplify your task:
using System.Net;
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString("http://somesite.com/default.html");
}
Those files are created and used by Android Studio editor.
You don't need to check in those files to version control.
Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.
Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.
Both are used to send some data and receive some response using that data.
GET: Get information stored in the server. (i.e. search, tweet, person information). If you want to send information then get request send request using process.php?name=subroto
So it basically sends information through url. Url cannot handle more than 2036 char. So for blog post can you remember it is not possible?
POST: Post do same thing as GET. User registration, User login, Big data send, Blog Post. If you need to send secure information then use post or for big data as it not go through url.
AJAX: $.get()
and $.post()
contain features that are subsets of $.ajax()
. It has more configuration.
$.get ()
method, which is a kind of shorthand for $.ajax()
. When using $.get ()
, instead of passing in an object, you pass in arguments. At minimum, you’ll need the first two arguments, which are the URL of the file you want to retrieve (eg. test.txt) and a success callback.
I think Peter has the right idea. I would use a regular expression for this along with the -notmatch operator.
Get-EventLog Security | ?{$_.Username -notmatch '^user1$|^.*user$'}