The first case is telling the web server that you are posting JSON data as in:
{ Name : 'John Smith', Age: 23}
The second option is telling the web server that you will be encoding the parameters in the URL as in:
Name=John+Smith&Age=23
Help -> About Eclipse Platform
For Eclipse Mars - you can check Eclipse -> About Eclipse
or Help -> Installation Details
, then you should see the version:
According to the standard (§6.4.4.4/10)
The value of an integer character constant containing more than one character (e.g., 'ab'), [...] is implementation-defined.
long x = '\xde\xad\xbe\xef'; // yes, single quotes
This is valid ISO 9899:2011 C. It compiles without warning under gcc
with -Wall
, and a “multi-character character constant” warning with -pedantic
.
From Wikipedia:
Multi-character constants (e.g. 'xy') are valid, although rarely useful — they let one store several characters in an integer (e.g. 4 ASCII characters can fit in a 32-bit integer, 8 in a 64-bit one). Since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult.
For portability sake, don't use multi-character constants with integral types.
Easy:
print my_queryset.query
For example:
from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query
It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:
from django.db import connections
connections['default'].queries
The django debug toolbar project uses this to present the queries on a page in a neat manner.
One way could be to have an array of allowed character codes and then use the Array.includes
function to see if entered character is allowed.
Example:
<input type="text" onkeypress="return [45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57].includes(event.charCode);"/>
You can't assign a List<Number>
to a reference of type List<Integer>
because List<Number>
allows types of numbers other than Integer
. If you were allowed to do that, the following would be allowed:
List<Number> numbers = new ArrayList<Number>();
numbers.add(1.1); // add a double
List<Integer> ints = numbers;
Integer fail = ints.get(0); // ClassCastException!
The type List<Integer>
is making a guarantee that anything it contains will be an Integer
. That's why you're allowed to get an Integer
out of it without casting. As you can see, if the compiler allowed a List
of another type such as Number
to be assigned to a List<Integer>
that guarantee would be broken.
Assigning a List<Integer>
to a reference of a type such as List<?>
or List<? extends Number>
is legal because the ?
means "some unknown subtype of the given type" (where the type is Object
in the case of just ?
and Number
in the case of ? extends Number
).
Since ?
indicates that you do not know what specific type of object the List
will accept, it isn't legal to add anything but null
to it. You are, however, allowed to retrieve any object from it, which is the purpose of using a ? extends X
bounded wildcard type. Note that the opposite is true for a ? super X
bounded wildcard type... a List<? super Integer>
is "a list of some unknown type that is at least a supertype of Integer
". While you don't know exactly what type of List
it is (could be List<Integer>
, List<Number>
, List<Object>
) you do know for sure that whatever it is, an Integer
can be added to it.
Finally, new ArrayList<?>()
isn't legal because when you're creating an instance of a paramterized class like ArrayList
, you have to give a specific type parameter. You could really use whatever in your example (Object
, Foo
, it doesn't matter) since you'll never be able to add anything but null
to it since you're assigning it directly to an ArrayList<?>
reference.
If IncomingHandler
class is not static, it will have a reference to your Service
object.
Handler
objects for the same thread all share a common Looper object, which they post messages to and read from.
As messages contain target Handler
, as long as there are messages with target handler in the message queue, the handler cannot be garbage collected. If handler is not static, your Service
or Activity
cannot be garbage collected, even after being destroyed.
This may lead to memory leaks, for some time at least - as long as the messages stay int the queue. This is not much of an issue unless you post long delayed messages.
You can make IncomingHandler
static and have a WeakReference
to your service:
static class IncomingHandler extends Handler {
private final WeakReference<UDPListenerService> mService;
IncomingHandler(UDPListenerService service) {
mService = new WeakReference<UDPListenerService>(service);
}
@Override
public void handleMessage(Message msg)
{
UDPListenerService service = mService.get();
if (service != null) {
service.handleMessage(msg);
}
}
}
See this post by Romain Guy for further reference
In the first case you are creating the object on the heap
using new
.
In the second case you are creating the object on the stack
, so it will be disposed of when going out of scope.
In C++
you'll need to delete objects on the heap
explicitly using delete
when you don't Need them anymore.
To call a static method from a class, do
Singleton* singleton = Singleton::get_sample();
in your main-function or wherever.
Standard class java.util.ArrayList is resizable array, growing when new elements added.
In my case, the crash happened when I calleddeselectRowAtIndexPath:
The line was [tableView deselectRowAtIndexPath:indexPath animated:YES];
Changing it to [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
FIXED MY PROBLEM!
Hope this helps anyone
Apache commons FileUtils will be handy, if you want only to move files from the source to target directory rather than copy the whole directory, you can do:
for (File srcFile: srcDir.listFiles()) {
if (srcFile.isDirectory()) {
FileUtils.copyDirectoryToDirectory(srcFile, dstDir);
} else {
FileUtils.copyFileToDirectory(srcFile, dstDir);
}
}
If you want to skip directories, you can do:
for (File srcFile: srcDir.listFiles()) {
if (!srcFile.isDirectory()) {
FileUtils.copyFileToDirectory(srcFile, dstDir);
}
}
I would do it in the Initialize event of the controller like this...
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
const string culture = "en-US";
CultureInfo ci = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx
When you are in the Command, click Create to create a new parameter; call it project_name
. Once you've created it, double click its name to add it to the command's text. You query should resemble:
SELECT Projecttname, ReleaseDate, TaskName
FROM DB_Table
WHERE Project_Name LIKE {?project_name} + '*'
AND ReleaseDate >= getdate() --assumes sql server
If desired, link the main report to the subreport on this ({?project_name}
) field. If you don't establish a link between the main and subreport, CR will prompt you for the subreport's parameter.
In versions prior to 2008, a command's parameter was only allowed to be a scalar value.
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
From what you've told us it does appear to be a false positive in valgrind. The new
syntax with ()
should value-initialize the object, assuming it is POD.
Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?
Alternately perhaps your compiler doesn't actually value-initialize POD structures.
In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0
in the beginning of your script. This will help you to catch misspelled variable names. Like so,
# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"
PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
+ CategoryInfo : InvalidOperation: (fo:Token) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,
$file = "\\server\share\file.txt"
cat $file
main_recyclerview.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e)
{
int position=rv.getChildAdapterPosition(rv.findChildViewUnder(e.getX(),e.getY()));
switch (position)
{
case 0:
{
wifi(position);
adapter2.notifyDataSetChanged();
}
break;
case 1:
{
sound(position);
adapter2.notifyDataSetChanged();
}
break;
case 2:
{
bluetooth(position);
adapter2.notifyDataSetChanged();
}
break;
}
return true;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e)
{
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
In the ViewDidLoad Method, you have to write this line.
tableViews.separatorStyle = UITableViewCellSeparatorStyleNone;
This is working Code.
This worked for me.
.alert:not(:first-child){
margin: 30px;
}
You can add a callback function to your DatePicker to tell it to blur the input field before showing the DatePicker.
$('.selector').datepicker({
beforeShow: function(){$('input').blur();}
});
Note: The iOS keyboard will appear for a fraction of a second and then hide.
You will need to use semicolon as delimiter while specifying the jar and class file path in windows. This solved the issue.
Assuming the class file is under C:.
java -cp ".;C:\testng.jar" org.testng.TestNG testing.xml
Adding my own experience for those who are experiencing this in the future. My specific error was
Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'
It turns out that this was actually because I had reach the maximum number of open files on my system. It had nothing to do with failed connections, or even a DNS error as indicated.
If you have multiple databases for testing and development this might help
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
test:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
The border is been set on the generated tr
and td
elements, not on the table
. So, this should do:
.companyHeaderGrid.ui-panelgrid>*>tr,
.companyHeaderGrid.ui-panelgrid .ui-panelgrid-cell {
border: none;
}
How I found it? Just check the generated HTML output and all CSS style rules in the webdeveloper toolset of Chrome (rightclick, Inspect Element or press F12). Firebug and IE9 have a similar toolset. As to the confusion, just keep in mind that JSF/Facelets ultimately generates HTML and that CSS only applies on the HTML markup, not on the JSF source code. So to apply/finetune CSS you need to look in the client (webbrowser) side instead.
If you're still on PrimeFaces 4 or older, use below instead:
.companyHeaderGrid.ui-panelgrid>*>tr,
.companyHeaderGrid.ui-panelgrid>*>tr>td {
border: none;
}
This has been discussed in many posts but still I could not figure out a solution with:
android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"
Below solution will work with any of the ui components : Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout clicks inside a listview cell and also will respond to onItemClick:
Adapter class - getview():
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.my_ref_row, parent, false);
}
final Organization currentOrg = organizationlist.get(position).getOrganization();
TextView name = (TextView) view.findViewById(R.id.name);
Button btn = (Button) view.findViewById(R.id.btn_check);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
context.doSelection(currentOrg);
}
});
if(currentOrg.isSelected()){
btn.setBackgroundResource(R.drawable.sub_search_tick);
}else{
btn.setBackgroundResource(R.drawable.sub_search_tick_box);
}
}
In this was you can get the button clicked object to the activity. (Specially when you want the button to act as a check box with selected and non-selected states):
public void doSelection(Organization currentOrg) {
Log.e("Btn clicked ", currentOrg.getOrgName());
if (currentOrg.isSelected() == false) {
currentOrg.setSelected(true);
} else {
currentOrg.setSelected(false);
}
adapter.notifyDataSetChanged();
}
Here is a shorter version that takes care of
Code:
var setQueryParameter = function(uri, key, value) {
var re = new RegExp("([?&])("+ key + "=)[^&#]*", "g");
if (uri.match(re))
return uri.replace(re, '$1$2' + value);
// need to add parameter to URI
var paramString = (uri.indexOf('?') < 0 ? "?" : "&") + key + "=" + value;
var hashIndex = uri.indexOf('#');
if (hashIndex < 0)
return uri + paramString;
else
return uri.substring(0, hashIndex) + paramString + uri.substring(hashIndex);
}
The regex description can be found here.
NOTE: This solution is based on @amateur answer, but with many improvements.
Using python, here are few methods:
import statistics as st
n = int(input())
data = list(map(int, input().split()))
stdev = st.pstdev(data)
variance = st.pvariance(data)
devia = math.sqrt(variance)
mean = sum(data)/n
variance = sum([((x - mean) ** 2) for x in X]) / n
stddev = variance ** 0.5
print("{0:0.1f}".format(stddev))
variance
calculates variance of sample population pvariance
calculates variance of entire population stdev
and pstdev
Step 1: Define attributes in $appends
Step 2: Define accessor for that attributes.
Example:
<?php
...
class Movie extends Model{
protected $appends = ['cover'];
//define accessor
public function getCoverAttribute()
{
return json_decode($this->InJson)->cover;
}
Yes, you can modify state of objects inside your stream, but most often you should avoid modifying state of source of stream. From non-interference section of stream package documentation we can read that:
For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose
Spliterator
reports theCONCURRENT
characteristic.
So this is OK
List<User> users = getUsers();
users.stream().forEach(u -> u.setProperty(value));
// ^ ^^^^^^^^^^^^^
but this in most cases is not
users.stream().forEach(u -> users.remove(u));
//^^^^^ ^^^^^^^^^^^^
and may throw ConcurrentModificationException
or even other unexpected exceptions like NPE:
List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
list.stream()
.filter(i -> i > 5)
.forEach(i -> list.remove(i)); //throws NullPointerException
your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.
var $previous = $('.navlink').filter(function() {
return $(this).data("selected") == true
});
After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.
The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.
So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:
default.aspx
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
default.aspx.cs code:
public partial class _Default : System.Web.UI.Page
{
protected string GetDateInHomepageFormat(DateTime d)
{
string retValue = "";
// Do all processing required and return value
return retValue;
}
}
Hope this helps others as well.
i like to use gawk for running multiple commands on a list, for instance
ls -l | gawk '{system("/path/to/cmd.sh "$1)}'
however the escaping of the escapable characters can get a little hairy.
You have to right idea generating the url based off of the input value. The only issue is you are using window.location.href. Setting window.location.href changes the url of the current window. What you probably want to do is change the src attribute of an image.
<html>
<body>
<form>
<input type="text" value="" id="imagename">
<input type="button" onclick="var image = document.getElementById('the-image'); image.src='http://webpage.com/images/'+document.getElementById('imagename').value +'.png'" value="GO">
</form>
<img id="the-image">
</body>
</html>
Just need to change one letter:), rename 640x360.ogv to 640x360.ogg, it will work for all the 3 browers.
I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar
I put together a little test here:
\documentclass[10pt,twocolumn]{article}
\title{Article Title}
\author{
First Author\\
Department\\
school\\
email@edu
\and
Second Author\\
Department\\
school\\
email@edu
\and
Third Author\\
Department\\
school\\
email@edu
\and
Fourth Author\\
Department\\
school\\
email@edu
}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\ldots
\end{abstract}
\section{Introduction}
\ldots
\end{document}
Things to note, the title, author and date fields are declared before \begin{document}
. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn
in the document class.
This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}
. Here's a more detailed article on \LaTeX
font sizes:
https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont
To italicize you can use {\it First Name}
or \textit{First Name}
.
Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.
I tried the below code,
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously.
Its better to call setTimeout(executeQuery, 5000);
outside executeQuery()
in a separate function as below,
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
updateCall();
}
function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}
$(document).ready(function() {
executeQuery();
});
This worked exactly as intended.
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
I think the answer you are after is implied (if not stated) by Vinko's answer, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
You probably can combine the two tests on the second line into one with:
if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '-a
' and do recommend using separate simple tests combined with &&
. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).
You can find the details of these, and other related shell parameter expansions, the test
or [
command and conditional expressions in the Bash manual.
I was recently asked by email about this answer with the question:
You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
Wouldn't this accomplish the same?
if [ -z "${VAR}" ]; then echo VAR is not set at all; fi
Fair question - the answer is 'No, your simpler alternative does not do the same thing'.
Suppose I write this before your test:
VAR=
Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:
(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo JL:1 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:1 VAR is not set at all; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo JL:2 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:2 VAR is not set at all; fi
)
The output is:
JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all
In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the ${VAR=value}
and ${VAR:=value}
notations make. Ditto for ${VAR-value}
and ${VAR:-value}
, and ${VAR+value}
and ${VAR:+value}
, and so on.
As Gili points out in his answer, if you run bash
with the set -o nounset
option, then the basic answer above fails with unbound variable
. It is easily remedied:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
Or you could cancel the set -o nounset
option with set +u
(set -u
being equivalent to set -o nounset
).
changing:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: 100%;
}
to:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: auto;
float:left;
}
should start you off.
See Bavarious's answer.
Use xattr
with the -c
flag to "clear" the attributes:
xattr -c yourfile.txt
To recursively remove extended attributes on all files in a directory, combine the -c
"clear" flag with the -r
recursive flag:
xattr -rc /path/to/directory
Have a long path with spaces or special characters?
Open Terminal.app
and start typing xattr -rc
, include a trailing space, and then then drag the file or folder to the Terminal.app
window and it will automatically add the full path with proper escaping.
For me it was simply a matter of restarting the docker daemon..
Try gcc -c -I/home/me/development/skia sample.c
.
Assuming, that you have root access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists this block.
sudo -u postgres psql template1
Then sudo nano /etc/postgresql/11/main/pg_hba.conf file
local all postgres ident
For newer versions of PostgreSQL ident actually might be peer.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';
Use compareTo()
function that's built into the class.
read
reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.
Consequently, the following code is not safe if the input might not be terminated by a newline:
while read LINE; do
# do something with LINE
done
because the body of the while
won't be executed on the last line.
Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.
One way to solve the problem is to test if what was read is non-empty (-n
):
while read -r LINE || [[ -n $LINE ]]; do
# do something with LINE
done
Other solutions include using mapfile
to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep .
, for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk
(which is usually my preference).
Note that -r
is almost certainly needed in the read
builtin; it causes read
to not reinterpret \
-sequences in the input.
I hide the warnings in the pink boxes by running the following code in a cell:
from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
if (code_show_err){
$('div.output_stderr').hide();
} else {
$('div.output_stderr').show();
}
code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')
Here is a way to get the header titles from the column names dynamically.
/* Change table_name and database_name */
SET @table_name = 'table_name';
SET @table_schema = 'database_name';
SET @default_group_concat_max_len = (SELECT @@group_concat_max_len);
/* Sets Group Concat Max Limit larger for tables with a lot of columns */
SET SESSION group_concat_max_len = 1000000;
SET @col_names = (
SELECT GROUP_CONCAT(QUOTE(`column_name`)) AS columns
FROM information_schema.columns
WHERE table_schema = @table_schema
AND table_name = @table_name);
SET @cols = CONCAT('(SELECT ', @col_names, ')');
SET @query = CONCAT('(SELECT * FROM ', @table_schema, '.', @table_name,
' INTO OUTFILE \'/tmp/your_csv_file.csv\'
FIELDS ENCLOSED BY \'\\\'\' TERMINATED BY \'\t\' ESCAPED BY \'\'
LINES TERMINATED BY \'\n\')');
/* Concatenates column names to query */
SET @sql = CONCAT(@cols, ' UNION ALL ', @query);
/* Resets Group Contact Max Limit back to original value */
SET SESSION group_concat_max_len = @default_group_concat_max_len;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I have found the only reliable, portable method to be
bytes(bytearray([n]))
Just bytes([n]) does not work in python 2. Taking the scenic route through bytearray seems like the only reasonable solution.
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
In MVC4 & MVC5 It is little bit different, use following
/App_Start/RouteConfig.cs
namespace MyNamespace
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] {"MyNamespace.Controllers"}
);
}
}
}
and in Areas
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "MyNamespace.Areas.Admin.Controllers" }
);
Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.
def get_domain_suffixes():
import requests
res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
lst=set()
for line in res.text.split('\n'):
if not line.startswith('//'):
domains=line.split('.')
cand=domains[-1]
if cand:
lst.add('.'+cand)
return tuple(sorted(lst))
domain_suffixes=get_domain_suffixes()
def reminds_url(txt:str):
"""
>>> reminds_url('yandex.ru.com/somepath')
True
"""
ltext=txt.lower().split('/')[0]
return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)
Just set the className
attribute of the real DOM element to ''
(nothing).
$('#item')[0].className = ''; // the real DOM element is at [0]
Edit: Other people have said that just calling removeClass
works - I tested this with the Google JQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:
$("#item").removeClass();
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
Depending on the schema/account you are using to connect to the database, I would suspect you are missing a grant to the account you are using to connect to the database.
Connect as PCT account in the database, then grant the account you are using select access for the table.
grant select on pi_int to Account_used_to_connect
Try this code. it worked for me.
function getInvoiceID(url, invoiceId) {
return $.ajax({
type: 'POST',
url: url,
data: { invoiceId: invoiceId },
async: false,
});
}
function isInvoiceIdExists(url, invoiceId) {
$.when(getInvoiceID(url, invoiceId)).done(function (data) {
if (!data) {
}
});
}
It looks as if you could use the API functions to
UPDATE
I guess you're using the DOM Data Source (for server-side processing) to generate your table. I didn't really get that at first, so my previous answer won't work for that.
To get it to work without rewriting your server side code:
What you'll need to do is totally remove the old table (in the dom) and replace it with the ajax result content, then reinitialize the datatable:
// in your $.post callback:
function (data) {
// remove the old table
$("#ajaxresponse").children().remove();
// replace with the new table
$("#ajaxresponse").html(data);
// reinitialize the datatable
$('#rankings').dataTable( {
"sDom":'t<"bottom"filp><"clear">',
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bSortable": false, "sWidth": "10px" },
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
}
);
}
This one should work
^([A-Z]{1}+[a-z\-\.\']*+[\s]?)*
Add some special characters if you need them.
Pfft! Microseconds! Never solve a problem in microseconds that can be solved in nanoseconds.
Note that the accepted answer:
A better solution is to return True immediately when NAN is found:
import numba
import numpy as np
NAN = float("nan")
@numba.njit(nogil=True)
def _any_nans(a):
for x in a:
if np.isnan(x): return True
return False
@numba.jit
def any_nans(a):
if not a.dtype.kind=='f': return False
return _any_nans(a.flat)
array1M = np.random.rand(1000000)
assert any_nans(array1M)==False
%timeit any_nans(array1M) # 573us
array1M[0] = NAN
assert any_nans(array1M)==True
%timeit any_nans(array1M) # 774ns (!nanoseconds)
and works for n-dimensions:
array1M_nd = array1M.reshape((len(array1M)/2, 2))
assert any_nans(array1M_nd)==True
%timeit any_nans(array1M_nd) # 774ns
Compare this to the numpy native solution:
def any_nans(a):
if not a.dtype.kind=='f': return False
return np.isnan(a).any()
array1M = np.random.rand(1000000)
assert any_nans(array1M)==False
%timeit any_nans(array1M) # 456us
array1M[0] = NAN
assert any_nans(array1M)==True
%timeit any_nans(array1M) # 470us
%timeit np.isnan(array1M).any() # 532us
The early-exit method is 3 orders or magnitude speedup (in some cases). Not too shabby for a simple annotation.
Why it is hard
Popular font formats like TrueType and OpenType are vector outline formats: they use Bezier curves to define the boundary of the letter.
Transforming those formats into arrays of pixels (rasterization) is too specific and out of OpenGL's scope, specially because OpenGl does not have non-straight primitives (e.g. see Why is there no circle or ellipse primitive in OpenGL?)
The easiest approach is to first raster fonts ourselves on the CPU, and then give the array of pixels to OpenGL as a texture.
OpenGL then knows how to deal with arrays of pixels through textures very well.
Texture atlas
We could raster characters for every frame and re-create the textures, but that is not very efficient, specially if characters have a fixed size.
The more efficient approach is to raster all characters you plan on using and cram them on a single texture.
And then transfer that to the GPU once, and use it texture with custom uv coordinates to choose the right character.
This approach is called a texture atlas and it can be used not only for textures but also other repeatedly used textures, like tiles in a 2D game or web UI icons.
The Wikipedia picture of the full texture, which is itself taken from freetype-gl, illustrates this well:
I suspect that optimizing character placement to the smallest texture problem is an NP-hard problem, see: What algorithm can be used for packing rectangles of different sizes into the smallest rectangle possible in a fairly optimal way?
The same technique is used in web development to transmit several small images (like icons) at once, but there it is called "CSS Sprites": https://css-tricks.com/css-sprites/ and are used to hide the latency of the network instead of that of the CPU / GPU communication.
Non-CPU raster methods
There also exist methods which don't use the CPU raster to textures.
CPU rastering is simple because it uses the GPU as little as possible, but we also start thinking if it would be possible to use the GPU efficiency further.
This FOSDEM 2014 video explains other existing techniques:
Fonts inside of the 3D geometry with perspective
Rendering fonts inside of the 3D geometry with perspective (compared to an orthogonal HUD) is much more complicated, because perspective could make one part of the character much closer to the screen and larger than the other, making an uniform CPU discretization (e.g. raster, tesselation) look bad on the close part. This is actually an active research topic:
Distance fields are one of the popular techniques now.
The examples that follow were all tested on Ubuntu 15.10.
Because this is a complex problem as discussed previously, most examples are large, and would blow up the 30k char limit of this answer, so just clone the respective Git repositories to compile.
They are all fully open source however, so you can just RTFS.
FreeType solutions
FreeType looks like the dominant open source font rasterization library, so it would allow us to use TrueType and OpenType fonts, making it the most elegant solution.
https://github.com/rougier/freetype-gl
Was a set of examples OpenGL and freetype, but is more or less evolving into a library that does it and exposes a decent API.
In any case, it should already be possible to integrate it on your project by copy pasting some source code.
It provides both texture atlas and distance field techniques out of the box.
Demos under: https://github.com/rougier/freetype-gl/tree/master/demos
Does not have a Debian package, and it a pain to compile on Ubuntu 15.10: https://github.com/rougier/freetype-gl/issues/82#issuecomment-216025527 (packaging issues, some upstream), but it got better as of 16.10.
Does not have a nice installation method: https://github.com/rougier/freetype-gl/issues/115
Generates beautiful outputs like this demo:
libdgx https://github.com/libgdx/libgdx/tree/1.9.2/extensions/gdx-freetype
Examples / tutorials:
Other font rasterizers
Those seem less good than FreeType, but may be more lightweight:
Anton's OpenGL 4 Tutorials example 26 "Bitmap fonts"
The font was created by the author manually and stored in a single .png
file. Letters are stored in an array form inside the image.
This method is of course not very general, and you would have difficulties with internationalization.
Build with:
make -f Makefile.linux64
Output preview:
opengl-tutorial chapter 11 "2D fonts"
Textures are generated from DDS files.
The tutorial explains how the DDS files were created, using CBFG and Paint.Net.
Output preview:
For some reason Suzanne is missing for me, but the time counter works fine: https://github.com/opengl-tutorials/ogl/issues/15
FreeGLUT
GLUT has glutStrokeCharacter
and FreeGLUT is open source...
https://github.com/dcnieho/FreeGLUT/blob/FG_3_0_0/src/fg_font.c#L255
OpenGLText
https://github.com/tlorach/OpenGLText
TrueType raster. By NVIDIA employee. Aims for reusability. Haven't tried it yet.
ARM Mali GLES SDK Sample
http://malideveloper.arm.com/resources/sample-code/simple-text-rendering/ seems to encode all characters on a PNG, and cut them from there.
SDL_ttf
Source: https://github.com/cirosantilli/cpp-cheat/blob/d36527fe4977bb9ef4b885b1ec92bd0cd3444a98/sdl/ttf.c
Lives in a separate tree to SDL, and integrates easily.
Does not provide a texture atlas implementation however, so performance will be limited: How to render fonts and text with SDL2 efficiently?
Related threads
Clear file input with jQuery
$("#fileInputId").val(null);
Clear file input with JavaScript
document.getElementById("fileInputId").value = null;
Just put the following code on the top of the page
@{
Layout = "";
}
Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:
>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'
This will almost certainly be faster than the conversion to and from a date.
var __startTime = moment("2016-06-06T09:00").format();
var __endTime = moment("2016-06-06T21:00").format();
var __duration = moment.duration(moment(__endTime).diff(__startTime));
var __hours = __duration.asHours();
console.log(__hours);
SELECT @@IDENTITY AS 'Identity';
or
SELECT last_insert_id();
They are the same thing. If you use the set transaction isolation level
statement, it will apply to all the tables in the connection, so if you only want a nolock
on one or two tables use that; otherwise use the other.
Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider snapshot
or serializable
hints instead.
Swift 4.0 implementation :
use import in top of page by import EventKit
then
@IBAction func addtoCalendarClicked(sender: AnyObject) {
let eventStore = EKEventStore()
eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
if (granted) && (error == nil) {
print("granted \(granted)")
print("error \(error)")
let event = EKEvent(eventStore: eventStore)
event.title = "Event Title"
event.startDate = Date()
event.endDate = Date()
event.notes = "Event Details Here"
event.calendar = eventStore.defaultCalendarForNewEvents
var event_id = ""
do {
try eventStore.save(event, span: .thisEvent)
event_id = event.eventIdentifier
}
catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
if(event_id != ""){
print("event added !")
}
}
})
}
Question was more about XML but as annotation are more popular nowadays and it works similarly I'll show by example.
Let's create class Foo
:
public class Foo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and two Configuration files (you can't create one):
@Configuration
public class Configuration1 {
@Bean
public Foo foo() {
Foo foo = new Foo();
foo.setName("configuration1");
return foo;
}
}
and
@Configuration
public class Configuration2 {
@Bean
public Foo foo() {
Foo foo = new Foo();
foo.setName("configuration2");
return foo;
}
}
and let's see what happens when calling foo.getName()
:
@SpringBootApplication
public class OverridingBeanDefinitionsApplication {
public static void main(String[] args) {
SpringApplication.run(OverridingBeanDefinitionsApplication.class, args);
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(
Configuration1.class, Configuration2.class);
Foo foo = applicationContext.getBean(Foo.class);
System.out.println(foo.getName());
}
}
in this example result is: configuration2
.
The Spring Container gets all configuration metadata sources and merges bean definitions in those sources. In this example there are two @Bean
s. Order in which they are fed into ApplicationContext
decide. You can flip new AnnotationConfigApplicationContext(Configuration2.class, Configuration1.class);
and result will be configuration1
.
There is a simple function subtract
which moment library gives us to subtract time from some time.
Using it is also very simple.
moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time
//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously
//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time
//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time
Hope this helps!
If anyone is still having this issue, simply close the solution and then reopen it.
You can use inbuilt library pickle
This library allows you to save any object in python to a file
This library will maintain the format as well
import pickle
with open('/content/list_1.txt', 'wb') as fp:
pickle.dump(list_1, fp)
you can also read the list back as an object using same library
with open ('/content/list_1.txt', 'rb') as fp:
list_1 = pickle.load(fp)
reference : Writing a list to a file with Python
Most likely;
However, lets assume you do need to handle an exception from a child thread another. I would use an ExecutorService like this:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
System.out.println("** Started");
Thread.sleep(2000);
throw new IllegalStateException("exception from thread");
}
});
try {
future.get(); // raises ExecutionException for any uncaught exception in child
} catch (ExecutionException e) {
System.out.println("** RuntimeException from thread ");
e.getCause().printStackTrace(System.out);
}
executor.shutdown();
System.out.println("** Main stopped");
prints
** Started
** RuntimeException from thread
java.lang.IllegalStateException: exception from thread
at Main$1.call(Main.java:11)
at Main$1.call(Main.java:6)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
** Main stopped
Ted Hopp answered this quite nicely. I have been using res/raw for my opengl texture and shader files. I was thinking about moving them to an assets directory to provide a hierarchical organization.
This thread convinced me not to. First, because I like the use of a unique resource id. Second because it's very simple to use InputStream/openRawResource or BitmapFactory to read in the file. Third because it's very useful to be able to use in a portable library.
Use Array list http://developer.android.com/reference/java/util/ArrayList.html
That line of code can actually appear in several different contexts and alghough it behaves approximately the same, there are small differences.
// foo.h
static const int i = 0;
'i
' will be visible in every translation unit that includes the header. However, unless you actually use the address of the object (for example. '&i
'), I'm pretty sure that the compiler will treat 'i
' simply as a type safe 0
. Where two more more translation units take the '&i
' then the address will be different for each translation unit.
// foo.cc
static const int i = 0;
'i
' has internal linkage, and so cannot be referred to from outside of this translation unit. However, again unless you use its address it will most likely be treated as a type-safe 0
.
One thing worth pointing out, is that the following declaration:
const int i1 = 0;
is exactly the same as static const int i = 0
. A variable in a namespace declared with const
and not explicitly declared with extern
is implicitly static. If you think about this, it was the intention of the C++ committee to allow const
variables to be declared in header files without always needing the static
keyword to avoid breaking the ODR.
class A {
public:
static const int i = 0;
};
In the above example, the standard explicitly specifies that 'i
' does not need to be defined if its address is not required. In other words if you only use 'i
' as a type-safe 0 then the compiler will not define it. One difference between the class and namespace versions is that the address of 'i
' (if used in two ore more translation units) will be the same for the class member. Where the address is used, you must have a definition for it:
// a.h
class A {
public:
static const int i = 0;
};
// a.cc
#include "a.h"
const int A::i; // Definition so that we can take the address
This error happened to me because I had @@model instead of @model... copy & paste error in my case. Changing to @model fixed it for me.
Instead of adding a toolbar in the layout, you can set your custom view as shown below.
Toolbar parent = (Toolbar) customView.getParent();
parent.setContentInsetsAbsolute(0,0);
Yes, there is one here: http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding.
class KeyStatisticCollection(DataDownloadUtilities.DataDownloadCollection):
def GenerateAddressStrings(self):
pass
def worker(self):
pass
def DownloadProc(self):
pass
As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:
var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');
for(var i = spans.length; i--;) {
var span = spans[i];
if(span.className.match(/\btheclass\b/)) {
span.parentNode.removeChild(span);
}
}
getElementsByTagName
is the most cross-browser-compatible method that can be used here. getElementsByClassName
would be much better, but is not supported by Internet Explorer <= IE 8.
I picked node-sass implementer for libsass because it is based on node.js.
$ npm install -g node-sass
installs node-sass globally -g
.This will hopefully install all you need, if not read libsass at the bottom.
General format:
$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css
Examples:
$ node-sass my-styles.scss my-styles.css
compiles a single file manually.$ node-sass my-sass-folder/ -o my-css-folder/
compiles all the files in a folder manually.$ node-sass -w sass/ -o css/
compiles all the files in a folder automatically whenever the source file(s) are modified. -w
adds a watch for changes to the file(s).More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.
You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.
package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions. "sass": "node-sass -w sass/ -o css/"
to scripts
in package.json
file. It should look something like this:"scripts": {
"test" : "bla bla bla",
"sass": "node-sass -w sass/ -o css/"
}
$ npm run sass
will compile your files.$ npm install -g gulp
installs Gulp globally.package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions.$ npm install --save-dev gulp
installs Gulp locally. --save-dev
adds gulp
to devDependencies
in package.json
.$ npm install gulp-sass --save-dev
installs gulp-sass locally.gulpfile.js
file in your project root folder with this content:'use strict';
var gulp = require('gulp');
A basic example to transpile
Add this code to your gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
$ gulp sass
runs the above task which compiles .scss file(s) in the sass
folder and generates .css file(s) in the css
folder.
To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js
:
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
All is set now! Just run the watch task:
$ gulp sass:watch
As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.
Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:
LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
Use Nesting column
To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).
<div class="row">_x000D_
<div class="col-sm-9">_x000D_
Level 1: .col-sm-9_x000D_
<div class="row">_x000D_
<div class="col-xs-8 col-sm-6">_x000D_
Level 2: .col-xs-8 .col-sm-6_x000D_
</div>_x000D_
<div class="col-xs-4 col-sm-6">_x000D_
Level 2: .col-xs-4 .col-sm-6_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
There are many answers available telling the approach. I took the same approach but the implementation isn't good.
Here is the base Idea . I made modifications to keyboardWasShown method.
{
// Obtain keyboard Info
NSDictionary* info = [notification userInfo];
CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
// Obtain ScrollView Info w.r.t. top View
CGRect scrollViewRect = [self.view convertRect:self.scrollView.frame fromView:nil];
// Depending upon your screen Ui, Scroll View's bottom edge might be at some offset from screen's bottom
// Calculate the exact offset
int scrollViewBottomOffset = self.view.frame.size.height - (scrollViewRect.origin.y + scrollViewRect.size.height);
int heightToBeAdjusted = keyboardRect.size.height - scrollViewBottomOffset;
// We may also need to consider the Insets if already present with ScrollView. Let's keep it simple for now
// But we should store these, so that we can restore the Insets when Keyboard is gone
// origInsets = self.scrollView.contentInset;
// Set the new Insets for ScrollView
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, heightToBeAdjusted, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// Visible frame (not overlapped by Keyboard)
CGRect visibleFrame = self.view.frame;
visibleFrame.size.height -= keyboardRect.size.height;
// Get the Rect for Textfield w.r.t self.view
CGRect activeFieldFrame = self.activeField.frame;
activeFieldFrame = [self.view convertRect:activeFieldFrame fromView:self.scrollView];
// Check if the TextField is Visible or not
if (!CGRectContainsRect(visibleFrame, activeFieldFrame) ) {
// Scroll to make it visible but for scrolling use the activeField frame w.r.t. to scroll View
[self.scrollView scrollRectToVisible:self.activeField.frame animated:YES];
}
}
And add this method to initialize the activeField
- (IBAction)textFieldDidBeginEditing:(UITextField *)sender
{
self.activeField = sender;
}
I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"
in my .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
then in my component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
ASCII has 128 code positions, allocated to graphic characters and control characters (control codes).
Unicode has 1,114,112 code positions. About 100,000 of them have currently been allocated to characters, and many code points have been made permanently noncharacters (i.e. not used to encode any character ever), and most code points are not yet assigned.
The only things that ASCII and Unicode have in common are: 1) They are character codes. 2) The 128 first code positions of Unicode have been defined to have the same meanings as in ASCII, except that the code positions of ASCII control characters are just defined as denoting control characters, with names corresponding to their ASCII names, but their meanings are not defined in Unicode.
Sometimes, however, Unicode is characterized (even in the Unicode standard!) as “wide ASCII”. This is a slogan that mainly tries to convey the idea that Unicode is meant to be a universal character code the same way as ASCII once was (though the character repertoire of ASCII was hopelessly insufficient for universal use), as opposite to using different codes in different systems and applications and for different languages.
Unicode as such defines only the “logical size” of characters: Each character has a code number in a specific range. These code numbers can be presented using different transfer encodings, and internally, in memory, Unicode characters are usually represented using one or two 16-bit quantities per character, depending on character range, sometimes using one 32-bit quantity per character.
for item in do_not_use_list_as_a_name[1:-1]:
#...do whatever
I used this:
myElement = document.getElemenById("xyz");
Get_Offset_From_Start ( myElement ); // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement ); // returns positions from current scrolled view's TOP and LEFT
code:
function Get_Offset_From_Start (object, offset) {
offset = offset || {x : 0, y : 0};
offset.x += object.offsetLeft; offset.y += object.offsetTop;
if(object.offsetParent) {
offset = Get_Offset_From_Start (object.offsetParent, offset);
}
return offset;
}
function Get_Offset_From_CurrentView (myElement) {
if (!myElement) return;
var offset = Get_Offset_From_Start (myElement);
var scrolled = GetScrolled (myElement.parentNode);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
scrolled = scrolled || {x : 0, y : 0};
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
return scrolled;
}
/*
// live monitoring
window.addEventListener('scroll', function (evt) {
var Positionsss = Get_Offset_From_CurrentView(myElement);
console.log(Positionsss);
});
*/
You could use this code:
if (!Object.keys) {
Object.keys = function (obj) {
var keys = [],
k;
for (k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
}
return keys;
};
}
Then you can use this in older browsers as well:
var len = Object.keys(obj).length;
I have created this function for iOS following the answer given by chmike
+ (NSArray *)intersectionPointsOfCircleWithCenter:(CGPoint)center withRadius:(float)radius toLinePoint1:(CGPoint)p1 andLinePoint2:(CGPoint)p2
{
NSMutableArray *intersectionPoints = [NSMutableArray array];
float Ax = p1.x;
float Ay = p1.y;
float Bx = p2.x;
float By = p2.y;
float Cx = center.x;
float Cy = center.y;
float R = radius;
// compute the euclidean distance between A and B
float LAB = sqrt( pow(Bx-Ax, 2)+pow(By-Ay, 2) );
// compute the direction vector D from A to B
float Dx = (Bx-Ax)/LAB;
float Dy = (By-Ay)/LAB;
// Now the line equation is x = Dx*t + Ax, y = Dy*t + Ay with 0 <= t <= 1.
// compute the value t of the closest point to the circle center (Cx, Cy)
float t = Dx*(Cx-Ax) + Dy*(Cy-Ay);
// This is the projection of C on the line from A to B.
// compute the coordinates of the point E on line and closest to C
float Ex = t*Dx+Ax;
float Ey = t*Dy+Ay;
// compute the euclidean distance from E to C
float LEC = sqrt( pow(Ex-Cx, 2)+ pow(Ey-Cy, 2) );
// test if the line intersects the circle
if( LEC < R )
{
// compute distance from t to circle intersection point
float dt = sqrt( pow(R, 2) - pow(LEC,2) );
// compute first intersection point
float Fx = (t-dt)*Dx + Ax;
float Fy = (t-dt)*Dy + Ay;
// compute second intersection point
float Gx = (t+dt)*Dx + Ax;
float Gy = (t+dt)*Dy + Ay;
[intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Fx, Fy)]];
[intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Gx, Gy)]];
}
// else test if the line is tangent to circle
else if( LEC == R ) {
// tangent point to circle is E
[intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Ex, Ey)]];
}
else {
// line doesn't touch circle
}
return intersectionPoints;
}
On:
Do:
$ sudo nano /etc/mysql/conf.d/mysql.cnf
Copy and paste:
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
To the bottom of the file
$ sudo service mysql restart
You declare
int countlines(char *filename)
to take a char *
argument.
You call it like this
countlines(fp)
passing in a FILE *.
That is why you get that compile error.
You probably should change that second line to
countlines("Test.txt")
since you open the file in countlines
Your current code is attempting to open the file in two different places.
Just use the Class method using this foobar->foobarfunc();
C-style solution could be to use itoa
, but better way is to print this number into string by using sprintf
/ snprintf
. Check this question: How to convert an integer to a string portably?
Note that itoa
function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. It's a non-standard function, thus you should avoid using it. Check this question too: Alternative to itoa() for converting integer to string C++?
Also note that writing C-style code while programming in C++ is considered bad practice and sometimes referred as "ghastly style". Do you really want to convert it into C-style char*
string? :)
XmlTextWriter.WriteString()
does the escaping.
You can need to pass in the string 'int64'
:
>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]}) # some test dataframe
>>> df['a'].astype('int64')
0 1
1 2
Name: a, dtype: int64
There are some alternative ways to specify 64-bit integers:
>>> df['a'].astype('i8') # integer with 8 bytes (64 bit)
0 1
1 2
Name: a, dtype: int64
>>> import numpy as np
>>> df['a'].astype(np.int64) # native numpy 64 bit integer
0 1
1 2
Name: a, dtype: int64
Or use np.int64
directly on your column (but it returns a numpy.array
):
>>> np.int64(df['a'])
array([1, 2], dtype=int64)
Try using MAX
with a GROUP BY
.
SELECT u.userName, MAX(c.carPrice)
FROM users u
LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;
GROUP BY
The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.
For example, if we have a set of records representing temperatures over time and location in a table like this:
Location Time Temperature
-------- ---- -----------
London 12:00 10.0
Bristol 12:00 12.0
Glasgow 12:00 5.0
London 13:00 14.0
Bristol 13:00 13.0
Glasgow 13:00 7.0
...
Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:
SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;
I want columns One and Two to shrink/grow to fit rather than being fixed.
Have you tried: flex-basis: auto
or this:
flex: 1 1 auto
, which is short for:
flex-grow: 1
(grow proportionally)flex-shrink: 1
(shrink proportionally)flex-basis: auto
(initial size based on content size)or this:
main > section:first-child {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:nth-child(2) {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:last-child {
flex: 20 1 auto;
display: flex;
flex-direction: column;
}
Related:
basically if you already specify the year range there is no need to use mindate
and maxdate
if only year is required
so easy, only use margin and left, right properties:
.elements {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
You can see more in this tip => How to set div element to center in html- Obinb blog
In Java, according to the JSSE Reference Guide, there is no default for the keystore
, the default for the truststore
is "jssecacerts, if it exists. Otherwise, cacerts".
A few applications use ~/.keystore
as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).
I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.
The file you give is a shell script, not an awk program. So, try sh my.awk
.
If you want to use awk -f my.awk life.csv > life_out.cs
, then remove awk -F , '
and the last line from the file and add FS=","
in BEGIN
.
I just had the same problem, and I could fix it by just putting a comma and not a period/full stop in the number because of French localization.
So it works with:
2 is OK
2,5 is OK
2.5 is KO (The number is considered "illegal" and you receive empty value).
Google text to speech
<!DOCTYPE html>
<html>
<head>
<script>
function play(id){
var text = document.getElementById(id).value;
var url = 'http://translate.google.com/translate_tts?tl=en&q='+text;
var a = new Audio(url);
a.play();
}
</script>
</head>
<body>
<input type="text" id="text" />
<button onclick="play('text');"> Speak it </button>
</body>
</html>
Use IDA Pro and the Decompiler.
You can use the parseInt() function to convert the string to a number, e.g:
parseInt($('#elem').css('top'));
Update: (as suggested by Ben): You should give the radix too:
parseInt($('#elem').css('top'), 10);
Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).
Other answers added great stuff. I will add just my 2 cents.
According to Wikipedia we know for sure: a file descriptor is a non-negative integer. The most important thing I think is missing, would be to say:
File descriptors are bound to a process ID.
We know most famous file descriptors are 0, 1 and 2.
0 corresponds to STDIN
, 1 to STDOUT
, and 2 to STDERR
.
Say, take shell processes as an example and how does it apply for it?
Check out this code
#>sleep 1000 &
[12] 14726
We created a process with the id 14726 (PID).
Using the lsof -p 14726
we can get the things like this:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sleep 14726 root cwd DIR 8,1 4096 1201140 /home/x
sleep 14726 root rtd DIR 8,1 4096 2 /
sleep 14726 root txt REG 8,1 35000 786587 /bin/sleep
sleep 14726 root mem REG 8,1 11864720 1186503 /usr/lib/locale/locale-archive
sleep 14726 root mem REG 8,1 2030544 137184 /lib/x86_64-linux-gnu/libc-2.27.so
sleep 14726 root mem REG 8,1 170960 137156 /lib/x86_64-linux-gnu/ld-2.27.so
sleep 14726 root 0u CHR 136,6 0t0 9 /dev/pts/6
sleep 14726 root 1u CHR 136,6 0t0 9 /dev/pts/6
sleep 14726 root 2u CHR 136,6 0t0 9 /dev/pts/6
The 4-th column FD and the very next column TYPE correspond to the File Descriptor and the File Descriptor type.
Some of the values for the FD can be:
cwd – Current Working Directory
txt – Text file
mem – Memory mapped file
mmap – Memory mapped device
But the real file descriptor is under:
NUMBER – Represent the actual file descriptor.
The character after the number i.e "1u", represents the mode in which the file is opened. r for read, w for write, u for read and write.
TYPE specifies the type of the file. Some of the values of TYPEs are:
REG – Regular File
DIR – Directory
FIFO – First In First Out
But all file descriptors are CHR – Character special file (or character device file)
Now, we can identify the File Descriptors for STDIN
, STDOUT
and STDERR
easy with lsof -p PID
, or we can see the same if we ls /proc/PID/fd
.
Note also that file descriptor table that kernel keeps track of is not the same as files table or inodes table. These are separate, as some other answers explained.
You may ask yourself where are these file descriptors physically and what is stored in /dev/pts/6
for instance
sleep 14726 root 0u CHR 136,6 0t0 9 /dev/pts/6
sleep 14726 root 1u CHR 136,6 0t0 9 /dev/pts/6
sleep 14726 root 2u CHR 136,6 0t0 9 /dev/pts/6
Well, /dev/pts/6
lives purely in memory. These are not regular files, but so called character device files. You can check this with: ls -l /dev/pts/6
and they will start with c
, in my case crw--w----
.
Just to recall most Linux like OS define seven types of files:
In order to use local gem repository in a Rails project, follow the steps below:
Check if your gem folder is a git repository (the command is executed in the gem folder)
git rev-parse --is-inside-work-tree
Getting repository path (the command is executed in the gem folder)
git rev-parse --show-toplevel
Setting up a local override for the rails application
bundle config local.GEM_NAME /path/to/local/git/repository
where GEM_NAME
is the name of your gem and /path/to/local/git/repository
is the output of the command in point 2
In your application Gemfile
add the following line:
gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
Running bundle install
should give something like this:
Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository)
where GEM_NAME
is the name of your gem and /path/to/local/git/repository
from point 2
Finally, run bundle list
, not gem list
and you should see something like this:
GEM_NAME (0.0.1 5a68b88)
where GEM_NAME
is the name of your gem
A few important cases I am observing using:
Rails 4.0.2
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]
Ubuntu 13.10
RubyMine 6.0.3
RubyMine
is not showing local gems as an external library. More information about the bug can be found here and herestop/start
the rails serverIf I am changing the version
of the gem, stopping/starting
the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile
like this:
gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.
Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).
String result = String.format("%0" + messageDigest.length + "s", hexString.toString())
That's the shortest solution given what you already have. If you could convert the byte array to a numeric value, String.format
can convert it to a hex string at the same time.
This will update your android SDK and accept the license in the same time (ex for Android 25):
android update sdk --no-ui --filter build-tools-25.0.0,android-25,extra-android-m2repository
In my case addInterceptor()
didn't work to add HTTP headers to my request, I had to use addNetworkInterceptor()
. Code is as follows:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addNetworkInterceptor(new AddHeaderInterceptor());
And the interceptor code:
public class AddHeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("Authorization", "MyauthHeaderContent");
return chain.proceed(builder.build());
}
}
This and more examples on this gist
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
try this one
return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");
I was having the same problem. This worked for me:
.center {
margin: 0 auto;
width: 400px;
**display:block**
}
On Ubuntu, you would need to install a package called python-dev
. Since this package doesn't seem to be installed (locate Python.h
didn't find anything) and you can't install it system-wide yourself, we need a different solution.
You can install Python in your home directory -- you don't need any special permissions to do this. If you are allowed to use a web browser and run a gcc, this should work for you. To this end
Download the source tarball.
Unzip with
tar xjf Python-2.7.2.tar.bz2
Build and install with
cd Python-2.7.2
./configure --prefix=/home/username/python --enable-unicode=ucs4
make
make install
Now, you have a complete Python installation in your home directory. Pass -I /home/username/python/include
to gcc when compiling to make it aware of Python.h
. Pass -L /home/username/python/lib
and -lpython2.7
when linking.
This might help someone.
I've created new test project with Core Data called "CoreData". Shortly I've got "Use of undeclared type" for NSManagedObjectContext and other Core Data classes. After several attempts of importing, adding to Build phases, etc. I've deleted project and started new one called "TestingCoreData" and it all worked well.
Don't name (test) Projects like name of the Classes
I did this many years back on 2003 or possibly 97, yikes!
If I recall you need to use one of the subcommands above tied to a timer. You cannot operate on the db with any connections or forms open.
So you do something about closing all forms, and kick off the timer as the last running method. (which will in turn call the compact operation once everything closes)
If you haven't figured this out I could dig through my archives and pull it up.
if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.
Have you installed any product of SQL in your system machine ? You can download and install "ODBC Driver 13(or any version) for SQL Server" and try to run if you havent alerady done.
--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
is now in the neil
group, so webgui
can call set role neil
. However, webgui
did not inherit neil
's permissions.
Later, login as webgui:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
does not need superuser
permission for this.
You want to set role
at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}
It's an issue with popper.js
file. What I found at the official site was that bundle files include popper in itself but not jquery. I managed to fix it by adding link to these files:
bootstrap.bundle.js
bootstrap.bundle.min.js
I removed popper.js
however since it comes within the bundle file.
With the regex filter bellow, we can dismiss cast_sender.js
errors :
^((?!cast_sender).)*$
Do not forget to check Regex box.
Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit()
.
For example:
admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()
user = User.query.get(5)
user.name = 'New Name'
db.session.commit()
Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.
We can achieve this other way despite of directly calling event with <select>
.
JS part:
$("#sort").change(function(){
alert('Selected value: ' + $(this).val());
});
HTML part:
<select id="sort">
<option value="1">View All</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
<option value="4">Last Modified</option>
<option value="5">Ranking</option>
<option value="6">Reviewed</option>
</select>
The filename should be a string. In other names it should be within quotes.
f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
thisline = i.split(" ");
You can also open the file using with
with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
lines = f.readlines()
for i in lines:
thisline = i.split(" ");
There is no need to add the semicolon(;
) in python. It's ugly.
visibility=hidden
is very useful, but it will still take up space on the page. You can also use
display=none
because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.
First of all you do not need a .py
.
If you have a file a.py
and inside you have some functions:
def b():
# Something
return 1
def c():
# Something
return 2
And you want to import them in z.py
you have to write
from a import b, c
The answer will not work when using the overload to indicate the template @Html.DisplayFor(x => x.Foos, "YourTemplateName)
.
Seems to be designed that way, see this case. Also the exception the framework gives (about the type not been as expected) is quite misleading and fooled me on the first try (thanks @CodeCaster)
In this case you have to use @foreach
@foreach (var item in Model.Foos)
{
@Html.DisplayFor(x => item, "FooTemplate")
}
You only need this link jspdf.min.js
It has everything in it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
USE This Assembly Referance in your Project
Add a reference to System.Net.Http.Formatting.dll
To fetch single row
$result = $this->getEntityManager()->getConnection()->fetchAssoc($sql)
To fetch all records
$result = $this->getEntityManager()->getConnection()->fetchAll($sql)
Here you can use sql native query, all will work without any issue.
I have faced the same issue. You need to enable the Mixed Mode Authentication first. For more details How to enable Mixed Mode Authentication
You can make the field nullable, if that suits your specific modeling concerns. A null date won't be coerced to a date that isn't within the range of the SQL DateTime type the way a default value would. Another option is to explicitly map to a different type, perhaps with,
.HasColumnType("datetime2")
To get the user email, you have to log in the user with his Facebook account using the email
permission. Use for that the Facebook PHP SDK (see on github) as following.
First check if the user is already logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he his not, you can display the login link asking for the email
permission :
if (!$user) {
$args = array('scope' => 'email');
echo '<a href="' . $facebook->getLoginUrl() . '">Login with Facebook</a>';
} else {
echo '<a href="' . $facebook->getLogoutUrl() . '">Logout</a>';
}
When he is logged in the email can be found in the $user_profile
array.
Hope that helps !
SQLyog is GUI based solution to the problem of data search across all columns, tables and databases. One can customize search restricting it to field, table and databases.
In its Data Search
feature one can search for strings just like one uses Google.
I have completely replaced all uses of instance variables in my rspec tests to use let(). I've written a quickie example for a friend who used it to teach a small Rspec class: http://ruby-lambda.blogspot.com/2011/02/agile-rspec-with-let.html
As some of the other answers here says, let() is lazy evaluated so it will only load the ones that require loading. It DRYs up the spec and make it more readable. I've in fact ported the Rspec let() code to use in my controllers, in the style of inherited_resource gem. http://ruby-lambda.blogspot.com/2010/06/stealing-let-from-rspec.html
Along with lazy evaluation, the other advantage is that, combined with ActiveSupport::Concern, and the load-everything-in spec/support/ behavior, you can create your very own spec mini-DSL specific to your application. I've written ones for testing against Rack and RESTful resources.
The strategy I use is Factory-everything (via Machinist+Forgery/Faker). However, it is possible to use it in combination with before(:each) blocks to preload factories for an entire set of example groups, allowing the specs to run faster: http://makandra.com/notes/770-taking-advantage-of-rspec-s-let-in-before-blocks
You can use this to check the exception and the inner exception for a Win32Exception derived exception.
catch (Exception e) {
var w32ex = e as Win32Exception;
if(w32ex == null) {
w32ex = e.InnerException as Win32Exception;
}
if(w32ex != null) {
int code = w32ex.ErrorCode;
// do stuff
}
// do other stuff
}
Starting with C# 6, when can be used in a catch statement to specify a condition that must be true for the handler for a specific exception to execute.
catch (Win32Exception ex) when (ex.InnerException is Win32Exception) {
var w32ex = (Win32Exception)ex.InnerException;
var code = w32ex.ErrorCode;
}
As in the comments, you really need to see what exception is actually being thrown to understand what you can do, and in which case a specific catch is preferred over just catching Exception. Something like:
catch (BlahBlahException ex) {
// do stuff
}
Also System.Exception has a HRESULT
catch (Exception ex) {
var code = ex.HResult;
}
However, it's only available from .NET 4.5 upwards.
PIE
makes Internet Explorer 6-9
capable of rendering several of the most useful CSS3
decoration features
................................................................................
Check the unsaved values for your primary key/Object ID in your hbm files. If you have automated ID creation by hibernate framework and you are setting the ID somewhere it will throw this error.By default the unsaved value is 0, so if you set the ID to 0 you will see this error.
The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.
As a footnote, passing in null to most TryParse methods will throw an exception.
First of all, write the following code:
#include <Mmsystem.h>
#include <mciapi.h>
//these two headers are already included in the <Windows.h> header
#pragma comment(lib, "Winmm.lib")
To open *.mp3:
mciSendString("open \"*.mp3\" type mpegvideo alias mp3", NULL, 0, NULL);
To play *.mp3:
mciSendString("play mp3", NULL, 0, NULL);
To play and wait until the *.mp3 has finished playing:
mciSendString("play mp3 wait", NULL, 0, NULL);
To replay (play again from start) the *.mp3:
mciSendString("play mp3 from 0", NULL, 0, NULL);
To replay and wait until the *.mp3 has finished playing:
mciSendString("play mp3 from 0 wait", NULL, 0, NULL);
To play the *.mp3 and replay it every time it ends like a loop:
mciSendString("play mp3 repeat", NULL, 0, NULL);
If you want to do something when the *.mp3 has finished playing, then you need to RegisterClassEx
by the WNDCLASSEX
structure, CreateWindowEx
and process it's messages with the GetMessage, TranslateMessage and DispatchMessage functions in a while
loop and call:
mciSendString("play mp3 notify", NULL, 0, hwnd); //hwnd is an handle to the window returned from CreateWindowEx. If this doesn't work, then replace the hwnd with MAKELONG(hwnd, 0).
In the window procedure, add the case MM_MCINOTIFY:
The code in there will be executed when the mp3 has finished playing.
But if you program a Console Application and you don't deal with windows, then you can CreateThread
in suspend state by specifying the CREATE_SUSPENDED
flag in the dwCreationFlags
parameter and keep the return value in a static
variable and call it whatever you want. For instance, I call it mp3. The type of this static
variable is HANDLE
of course.
Here is the ThreadProc
for the lpStartAddress
of this thread:
DWORD WINAPI MP3Proc(_In_ LPVOID lpParameter) //lpParameter can be a pointer to a structure that store data that you cannot access outside of this function. You can prepare this structure before `CreateThread` and give it's address in the `lpParameter`
{
Data *data = (Data*)lpParameter; //If you call this structure Data, but you can call it whatever you want.
while (true)
{
mciSendString("play mp3 from 0 wait", NULL, 0, NULL);
//Do here what you want to do when the mp3 playback is over
SuspendThread(GetCurrentThread()); //or the handle of this thread that you keep in a static variable instead
}
}
All what you have to do now is to ResumeThread(mp3);
every time you want to replay your mp3 and something will happen every time it finishes.
You can #define play_my_mp3 ResumeThread(mp3);
to make your code more readable.
Of course you can remove the while (true)
, SuspendThread
and the from 0 codes, if you want to play your mp3 file only once and do whatever you want when it is over.
If you only remove the SuspendThread
call, then the sound will play over and over again and do something whenever it is over. This is equivalent to:
mciSendString("play mp3 repeat notify", NULL, 0, hwnd); //or MAKELONG(hwnd, 0) instead
in windows.
To pause the *.mp3 in middle:
mciSendString("pause mp3", NULL, 0, NULL);
and to resume it:
mciSendString("resume mp3", NULL, 0, NULL);
To stop it in middle:
mciSendString("stop mp3", NULL, 0, NULL);
Note that you cannot resume a sound that has been stopped, but only paused, but you can replay it by carrying out the play command. When you're done playing this *.mp3, don't forget to:
mciSendString("close mp3", NULL, 0, NULL);
All these actions also apply to (work with) wave files too, but with wave files, you can use "waveaudio" instead of "mpegvideo". Also you can just play them directly without opening them:
PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME);
If you don't want to specify an handle to a module:
sndPlaySound("*.wav", SND_FILENAME);
If you don't want to wait until the playback is over:
PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC);
To play the wave file over and over again:
PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC | SND_LOOP);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC | SND_LOOP);
Note that you must specify both the SND_ASYNC
and SND_LOOP
flags, because you never going to wait until a sound, that repeats itself countless times, is over!
Also you can fopen
the wave file and copy all it's bytes to a buffer (an enormous/huge (very big) array of bytes) with the fread
function and then:
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC | SND_LOOP);
//or
sndPlaySound(buffer, SND_MEMORY);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC | SND_LOOP);
Either OpenFile
or CreateFile
or CreateFile2
and either ReadFile
or ReadFileEx
functions can be used instead of fopen
and fread
functions.
Hope this fully answers perfectly your question.
Adding to Jim's elaborate answer:
Check the typing
module -- this module supports type hints as specified by PEP 484.
For example, the function below takes and returns values of type str
and is annotated as follows:
def greeting(name: str) -> str:
return 'Hello ' + name
The typing
module also supports:
Make sure JAVA_HOME is set and the path in environment variables reflects the bin directory of JAVA_HOME. Basically, the PATH should be able to find the keytools.exe file in your jdk location.
Try below code:
@Html.DropDownList("ProductTypeID",null,"",new { @class = "form-control"})
a quick way to see your errors whilst testing:
$error= $st->errorInfo();
echo $error[2];
1) Install 'body-parser'
from npm.
2) Then in your app.ts
var bodyParser = require('body-parser');
3) then you need to write
app.use(bodyParser.json())
in app.ts module
4) keep in mind that you include
app.use(bodyParser.json())
in the top or before any module declaration.
Ex:
app.use(bodyParser.json())
app.use('/user',user);
5) Then use
var postdata = req.body;
I know basic use of abstract classes is to create templates for future classes. But are there any more uses of them?
Not only can you define a template for children, but Abstract Classes offer the added benefit of letting you define functionality that your child classes can utilize later.
You could not provide a default method implementation in an Interface prior to Java 8.
When should you prefer them over interfaces and when not?
Abstract Classes are a good fit if you want to provide implementation details to your children but don't want to allow an instance of your class to be directly instantiated (which allows you to partially define a class).
If you want to simply define a contract for Objects to follow, then use an Interface.
Also when are abstract methods useful?
Abstract methods are useful in the same way that defining methods in an Interface is useful. It's a way for the designer of the Abstract class to say "any child of mine MUST implement this method".
After an activity started, restarted (onRestart() happens before onStart()), or paused (onPause()), onResume() called. When the activity is in the state of onResume(), the activity is ready to be used by the app user.
I have studied the activity lifecycle a little bit, and here's my understanding of this topic: If you want to restart the activity (A) at the end of the execution of another, there could be a few different cases.
The other activity (B) has been paused and/or stopped or destroyed, and the activity A possibly had been paused (onPause()), in this case, activity A will call onResume()
The activity B has been paused and/or stopped or destroyed, the activity A possibly had been stopped (onStop()) due to memory thing, in this case, activity A will call onRestart() first, onStart() second, then onResume()
The activity B has been paused and/or stopped or destroyed, the activity A has been destroyed, the programmer can call onStart() manually to start the activity first, then onResume() because when an activity is in the destroyed status the activity has not started, and this happens before the activity being completely removed. If the activity is removed, the activity needs to be created again. Manually calling onStart() I think it's because if the activity not started and it is created, onStart() will be called after onCreate().
If you want to update data, make a data update function and put the function inside the onResume(). Or put a loadData function inside onResume()
It's better to understand the lifecycle with the help of the Activity lifecycle diagram.
Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block. A very basic Example:
try {
// some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}
But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.
try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
throw e;
}
So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code. I found this article which explains this feature very well along with its implementation. Improved and Better Exception Handling from Java 7 This may help you too.
Here I am posting you the some code example which record good quality of sound using AudioRecord API.
Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.
public class Audio_Record extends Activity {
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord recorder = null;
private Thread recordingThread = null;
private boolean isRecording = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonHandlers();
enableButtons(false);
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
}
private void setButtonHandlers() {
((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
}
private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnStop, isRecording);
}
int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
int BytesPerElement = 2; // 2 bytes in 16bit format
private void startRecording() {
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
//convert short to byte
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void writeAudioDataToFile() {
// Write the output audio in byte
String filePath = "/sdcard/voice8K16bitmono.pcm";
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short writing to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
// stops the recording activity
if (null != recorder) {
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart: {
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop: {
enableButtons(false);
stopRecording();
break;
}
}
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.onKeyDown(keyCode, event);
}
}
For more detail try this AUDIORECORD BLOG.
Happy Coding !!
Its a bit late but if you don't want to use a div specifically, I usually do it like this...
var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);
ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.
cmd
as administratorC:\xampp\apache\bin
httpd.exe -k install
more informationcmd
as administratorC:\xampp\mysql\bin
mysqld.exe --install
more informationPure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B
as a word character but #
as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a #
almost immediately and happily breaks there; whereas with the B
, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).
But that's pure speculation.
Use this:
$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
I increased the virtual device SD card size from 500MB to 2GiB, the problem solved.
Bitmap d = new Bitmap(c.Width, c.Height);
for (int i = 0; i < c.Width; i++)
{
for (int x = 0; x < c.Height; x++)
{
Color oc = c.GetPixel(i, x);
int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
d.SetPixel(i, x, nc);
}
}
This way it also keeps the alpha channel.
Enjoy.
Update: check for existence using TryGetValue
to do only one lookup in the case where you have the list:
List<int> list;
if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}
list.Add(2);
var dictionary = new Dictionary<string, List<int>>();
if (!dictionary.ContainsKey("foo"))
dictionary.Add("foo", new List<int>());
dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);
Or List<string>
as in your case.
As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>
, favour the constructor that takes the initial list capacity: new List<int>(100);
.
This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.
Sometimes the provided solution by @palotasb is not sufficient. There are use cases where for example a "Filter" submits button is placed above buttons like "Next and Previous". I found a workaround for this: copy the submit button which needs to act as the default submit button in a hidden div and place it inside the form above any other submit button. Technically it will be submitted by a different button when pressing Enter than when clicking on the visible Next button. But since the name and value are the same, there's no difference in the result.
<html>
<head>
<style>
div.defaultsubmitbutton {
display: none;
}
</style>
</head>
<body>
<form action="action" method="get">
<div class="defaultsubmitbutton">
<input type="submit" name="next" value="Next">
</div>
<p><input type="text" name="filter"><input type="submit" value="Filter"></p>
<p>Filtered results</p>
<input type="radio" name="choice" value="1">Filtered result 1
<input type="radio" name="choice" value="2">Filtered result 2
<input type="radio" name="choice" value="3">Filtered result 3
<div>
<input type="submit" name="prev" value="Prev">
<input type="submit" name="next" value="Next">
</div>
</form>
</body>
</html>
While for most cases replacing ojdbc driver jar will be the solution, my case was different.
If you are certain you are using correct ojdbc driver. Double check if you are actually connecting to the database you are thinking you are. In my case jdbc configuration (in Tomcat/conf) was pointing to different database that had different Oracle version.
If you're leveraging React Hooks, you can take advantage of the useHistory
API that comes from React Router v5.
import React, {useCallback} from 'react';
import {useHistory} from 'react-router-dom';
export default function StackOverflowExample() {
const history = useHistory();
const handleOnClick = useCallback(() => history.push('/sample'), [history]);
return (
<button type="button" onClick={handleOnClick}>
Go home
</button>
);
}
Another way to write the click handler if you don't want to use useCallback
const handleOnClick = () => history.push('/sample');
The v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown (which then trigger's a redirect).
import { Redirect } from 'react-router';
// ... your class implementation
handleOnClick = () => {
// some action...
// then redirect
this.setState({redirect: true});
}
render() {
if (this.state.redirect) {
return <Redirect push to="/sample" />;
}
return <button onClick={this.handleOnClick} type="button">Button</button>;
}
Reference: https://reacttraining.com/react-router/web/api/Redirect
You can also take advantage of Router
's context that's exposed to the React component.
static contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired
}).isRequired,
staticContext: PropTypes.object
}).isRequired
};
handleOnClick = () => {
this.context.router.push('/sample');
}
This is how <Redirect />
works under the hood.
If you still need to do something similar to v2's implementation, you can create a copy of BrowserRouter
then expose the history
as an exportable constant. Below is a basic example but you can compose it to inject it with customizable props if needed. There are noted caveats with lifecycles, but it should always rerender the Router, just like in v2. This can be useful for redirects after an API request from an action function.
// browser router file...
import createHistory from 'history/createBrowserHistory';
import { Router } from 'react-router';
export const history = createHistory();
export default class BrowserRouter extends Component {
render() {
return <Router history={history} children={this.props.children} />
}
}
// your main file...
import BrowserRouter from './relative/path/to/BrowserRouter';
import { render } from 'react-dom';
render(
<BrowserRouter>
<App/>
</BrowserRouter>
);
// some file... where you don't have React instance references
import { history } from './relative/path/to/BrowserRouter';
history.push('/sample');
Latest BrowserRouter
to extend: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js
Push a new state to the browserHistory
instance:
import {browserHistory} from 'react-router';
// ...
browserHistory.push('/sample');
Reference: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md
If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.
For example, if using SSMS as GUI:
When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.
For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php
$datetime = "20130409163705";
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want
Result:
09/04/2013 16:37:05
In Java 8 for an Obj
entity with field
and getField() method you can use:
List<Obj> objs ...
Stream<Obj> notNullObjs =
objs.stream().filter(obj -> obj.getValue() != null);
Double sum = notNullObjs.mapToDouble(Obj::getField).sum();
If you want the accepted answer to work in JQuery 3 change the code like this:
var scrollItems = menuItems.map(function () {
var id = $(this).attr("href");
try {
var item = $(id);
if (item.length) {
return item;
}
} catch {}
});
I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)
After trying out everything else in this thread, I found out my own problem was because the path to the .apk file was too long. So I cd'ed to the directory where the .apk was in and did:
cd /Very/Long/Path/To/Package/
adb install mypackage.apk
instead of
adb install /Very/Long/Path/To/Package/mypackage.apk
And it worked...installed just fine.
Just thought this might help someone else.
I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
switch ((Int32)_respContent.Code)
{
case 1:
case 6:
case 7:
response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
break;
case 2:
case 3:
case 4:
response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
break;
}
return Task.FromResult(response);
}
, where _request is the HttpRequest and _respContent is the payload.
NO. It's not possible to change height of a select dropdown because that property is browser specific.
However if you want that functionality, then there are many options. You can use bootstrap dropdown-menu
and define it's max-height
property. Something like this.
$('.dropdown-menu').on( 'click', 'a', function() {_x000D_
var text = $(this).html();_x000D_
var htmlText = text + ' <span class="caret"></span>';_x000D_
$(this).closest('.dropdown').find('.dropdown-toggle').html(htmlText);_x000D_
});
_x000D_
.dropdown-menu {_x000D_
max-height: 146px;_x000D_
overflow: scroll;_x000D_
overflow-x: hidden;_x000D_
margin-top: 0px;_x000D_
}_x000D_
_x000D_
.caret {_x000D_
float: right;_x000D_
margin-top: 5%;_x000D_
}_x000D_
_x000D_
#menu1 {_x000D_
width: 160px; _x000D_
text-align: left;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container" style="margin:10px">_x000D_
<div class="dropdown">_x000D_
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials_x000D_
<span class="caret"></span></button>_x000D_
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1">_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>
_x000D_
Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn't understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.
The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.
Remove specific index(i removed 16 and 21 from matrix)
import numpy as np
mat = np.arange(12,26)
a = [4,9]
del_map = np.delete(mat, a)
del_map.reshape(3,4)
Output:
array([[12, 13, 14, 15],
[17, 18, 19, 20],
[22, 23, 24, 25]])
Use this command in cmd:
adb shell pm uninstall -k com.packagename
For example:
adb shell pm uninstall -k com.fedmich.pagexray
The -k
flag tells the package manager to keep the cache and data directories around, even though the app is removed. If you want a clean uninstall, don't specify -k
.
All the major color codes are given at https://www.siafoo.net/snippet/88
The general Angular way to get access to an element that triggered an event is to write a directive and bind() to the desired event:
app.directive('myChange', function() {
return function(scope, element) {
element.bind('change', function() {
alert('change on ' + element);
});
};
});
or with DDO (as per @tpartee's comment below):
app.directive('myChange', function() {
return {
link: function link(scope, element) {
element.bind('change', function() {
alert('change on ' + element);
});
}
}
});
The above directive can be used as follows:
<input id="searchText" ng-model="searchText" type="text" my-change>
Type into the text field, then leave/blur. The change callback function will fire. Inside that callback function, you have access to element
.
Some built-in directives support passing an $event object. E.g., ng-*click, ng-Mouse*. Note that ng-change does not support this event.
Although you can get the element via the $event object:
<button ng-click="clickit($event)">Hello</button>
$scope.clickit = function(e) {
var elem = angular.element(e.srcElement);
...
this goes "deep against the Angular way" -- Misko.
Add: now you can use lambda to simplify your syntax. Requirement: Java 8+
public class A {
public static void main(String[] arg)
{
Thread th = new Thread(() -> {System.out.println("blah");});
th.start();
}
}
Check the HTTP headers that chrome is sending with the request (Using browser extension or proxy) then try sending the same headers with CURL - Possibly one at a time till you figure out which header(s) makes the request work.
curl -A [user-agent] -H [headers] "http://something.com/api"
Another way to write if and else in Laravel using path
<p class="@if(Request::is('path/anotherPath/*')) className @else anotherClassName @endif" >
</p>
Hope it helps
If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../
apiVersion: skaffold/v2beta4
kind: Config
metadata:
name: frontend
build:
artifacts:
- image: nginx-angular-ui
context: ../../../
sync:
# A local build will update dist and sync it to the container
manual:
- src: './dist/apps'
dest: '/usr/share/nginx/html'
docker:
dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
- image: webapi/image
context: ../../../../api/
docker:
dockerfile: ./dockerfile
deploy:
kubectl:
manifests:
- ./.k8s/*.yml
skaffold run -f ./skaffold.yaml
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
It should be
r.append("\n");
But I recommend you to do as below,
r.append(System.getProperty("line.separator"));
System.getProperty("line.separator")
gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()
Faced a similar challenge adding files with .ini extensions to the classpath. Found this answer, which is to add it to Preferences -> Compiler -> Resource Patterns -> [...] ;*.ini
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
Use like this
<div ng-if="data.IsActive === 1">InActive</div>
<div ng-if="data.IsActive === 0">Active</div>
In my case it meant, there is some kind of mistake in my implementation, and it says that it cannot find the resource for the error message to be properly shown in LogCat. When I fixed that mistake in my implementation the problem from LogCat was gone as well. So actually unless you are missing some really neccessary resource you should not concentrate to fix the missing resources, but rather fix your implementation.
The mistake, BTW, was that I was running ads in debug mode without going to ads test mode.
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
When I want the UI to be able to update its display while waiting for a task to complete, I use a while-loop that tests IsAlive on the thread:
Thread t = new Thread(() => someMethod(parameters));
t.Start();
while (t.IsAlive)
{
Thread.Sleep(500);
Application.DoEvents();
}
You actually compile the source code of test.c
twice:
test.c
itself,main.c
which includes all the test.c
source.What you need in your main.c
in order to use the test()
function is a simple declaration, not its definition. This is achieved by including a test.h
header file which contains something like:
void test(void);
This informs the compiler that such a function with input parameters and return type exists. What this function does ( everything inside {
and }
) is left in your test.c
file.
In main.c, replace #include "test.c"
by #include "test.h"
.
A last point: with your programs being more complex, you will be faced to situations when header files may be included several times. To prevent this, header sources are sometimes enclosed by specific macro definitions, like:
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
void test(void);
#endif
I can think of a cheeky way to do it, I don't think this will be the best option but it will work.
Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow
.
table {_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
max-height: 60px;_x000D_
overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<th>head1</th>_x000D_
<th>head2</th>_x000D_
<th>head3</th>_x000D_
<th>head4</th>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
<table>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
INSERT INTO `dbMyDataBase`.`tblMyTable` ( `IdAutoincrement`, `Column2`, `Column3`, `Column4` ) SELECT NULL, `Column2`, `Column3`, 'CustomValue' AS Column4 FROM `dbMyDataBase`.`tblMyTable` WHERE `tblMyTable`.`Column2` = 'UniqueValueOfTheKey' ; /* mySQL 5.6 */
When using Node.js, you can retrieve environment variables by key from the process.env
object:
for example
var mode = process.env.NODE_ENV;
var apiKey = process.env.apiKey; // '42348901293989849243'
Here is the answer that will explain setting environment variables in node.js
There is no show
event in js - you need to bind your button either to the click
event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form
, you may prefer to bind the whole form to the submit
event.
With very few exceptions (I can only think of one), C++ determines the
entire meaning of an expression (or sub-expression) from the expression
itself. What you do with the results of the expression doesn't matter.
In your case, in the expression a / b
, there's not a double
in
sight; everything is int
. So the compiler uses integer division.
Only once it has the result does it consider what to do with it, and
convert it to double
.
It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.
You are able to checkout the following resources:
Try this:
List list = new ArrayList();
list.add("Apple");
list.add("Banana");
Object[] ol = list.toArray();