This is an old question, but its one I found while searching as well.
If you installed with brew
then the solution would actually be the this:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
First set Storage Engine as InnoDB
then the relation view option enable in structure menu
This method will return the selected value for the drop down,
public static String getSelected_visibleText(WebDriver driver, String elementType, String value)
{
WebElement element = Webelement_Finder.webElement_Finder(driver, elementType, value);
Select Selector = new Select(element);
Selector.getFirstSelectedOption();
String textval=Selector.getFirstSelectedOption().getText();
return textval;
}
Meanwhile
String textval=Selector.getFirstSelectedOption();
element.getText();
Will return all the elements in the drop down.
For a public action on an OSM map (position a marker on click) the question was: 1) how to determine the duration of mouse down->up (you can't imagine creating a new marker for each click) and 2) did the mouse move during down->up (i.e user is dragging the map).
const map = document.getElementById('map');
map.addEventListener("mousedown", position);
map.addEventListener("mouseup", calculate);
let posX, posY, endX, endY, t1, t2, action;
function position(e) {
posX = e.clientX;
posY = e.clientY;
t1 = Date.now();
}
function calculate(e) {
endX = e.clientX;
endY = e.clientY;
t2 = (Date.now()-t1)/1000;
action = 'inactive';
if( t2 > 0.5 && t2 < 1.5) { // Fixing duration of mouse down->up
if( Math.abs( posX-endX ) < 5 && Math.abs( posY-endY ) < 5 ) { // 5px error on mouse pos while clicking
action = 'active';
// --------> Do something
}
}
console.log('Down = '+posX + ', ' + posY+'\nUp = '+endX + ', ' + endY+ '\nAction = '+ action);
}
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
Just use target
on your tag <a>
<a href="newsletter_01.pdf" target="_blank">Read more</a>
The target attribute specifies where to open the link. Using "_blank" will make your browser to open a new window/tab.
You could also use target in many ways. See http://www.w3schools.com/tags/att_a_target.asp
The following POSIX program will print the names of the files in the current directory:
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html
Tested in Ubuntu 16.04.
Alternatively, you can use npx
which comes along with the npm > 5.6.
npx bower install
height:59.55%;//First specify your height then make overflow auto overflow:auto;
queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value
I had got the same error. Because of security reasons, I could not see option for allowing Apps downloaded from Anywhere in System preference-> Security Tab.
I removed the extended attribute from Zip file by below command.
xattr -d com.apple.quarantine [Zip file path]
And then got below error:- org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: javax/annotation/PostConstruct
Resolved it by uninstalling all different versions of java and installed just 1.8.0_231.
Worked finally.
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
In the position where you want to add text, do:
Shift
+ Alt
+ down arrow
and select the lines you want. Then type. The text you type is inserted on all of the lines you selected.
Quoting the Pandas docs
pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.
So, the Series is the data structure for a single column of a DataFrame
, not only conceptually, but literally, i.e. the data in a DataFrame
is actually stored in memory as a collection of Series
.
Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.
They both have extremely similar APIs, but you'll find that DataFrame
methods always cater to the possibility that you have more than one column. And, of course, you can always add another Series
(or equivalent object) to a DataFrame
, while adding a Series
to another Series
involves creating a DataFrame
.
8388608 bytes is 8M, the default limit in PHP. Update your post_max_size
in php.ini to a larger value.
upload_max_filesize
sets the max file size that a user can upload while
post_max_size
sets the maximum amount of data that can be sent via a POST in a form.
So you can set upload_max_filesize
to 1 meg, which will mean that the biggest single file a user can upload is 1 megabyte, but they could upload 5 of them at once if the post_max_size
was set to 5.
The block approach avoids running the lookup algorithm for every key:
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
NSLog(@"%@ => %@", key, value);
}];
Even though NSDictionary
is implemented as a hashtable (which means that the cost of looking up an element is O(1)
), lookups still slow down your iteration by a constant factor.
My measurements show that for a dictionary d
of numbers ...
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
NSNumber* value = @(i);
dict[value.stringValue] = value;
}
... summing up the numbers with the block approach ...
__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
sum += value.intValue;
}];
... rather than the loop approach ...
int sum = 0;
for (NSString* key in dict)
sum += [dict[key] intValue];
... is about 40% faster.
EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.
This works in Firefox 3.0, but not in MSIE 8, nor in Opera 9.62:
jQuery('#destinations').children('option[value="1"]').hide();
jQuery('#destinations').children('option[value="1"]').css('display','none');
But rather hiding an option, one can simply disable it:
jQuery('#destinations').val('2');
jQuery('#destinations').children('option[value="1"]').attr('disabled','disabled');
The first of the the two lines above is for Firefox and pass focus to the 2nd option (assuming it has value="2"). If we omit it, the option is disabled, but the still displays the "enabled" option before we drop it down. Hence, we pass focus to another option to avoid this.
Here's an example that reads a list of CSV strings into a list of lists and then loops through that list of lists and prints the CSV strings back out to the console.
import java.util.ArrayList;
import java.util.List;
public class ListExample
{
public static void main(final String[] args)
{
//sample CSV strings...pretend they came from a file
String[] csvStrings = new String[] {
"abc,def,ghi,jkl,mno",
"pqr,stu,vwx,yz",
"123,345,678,90"
};
List<List<String>> csvList = new ArrayList<List<String>>();
//pretend you're looping through lines in a file here
for(String line : csvStrings)
{
String[] linePieces = line.split(",");
List<String> csvPieces = new ArrayList<String>(linePieces.length);
for(String piece : linePieces)
{
csvPieces.add(piece);
}
csvList.add(csvPieces);
}
//write the CSV back out to the console
for(List<String> csv : csvList)
{
//dumb logic to place the commas correctly
if(!csv.isEmpty())
{
System.out.print(csv.get(0));
for(int i=1; i < csv.size(); i++)
{
System.out.print("," + csv.get(i));
}
}
System.out.print("\n");
}
}
}
Pretty straightforward I think. Just a couple points to notice:
I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List<String>
.
In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:
List<List<String>> csvList = new ArrayList<List<String>>(500);
That way you would never waste processing time waiting for your list to grow dynamically grow. This is why I pass "linePieces.length" to the constructor. Not usually a big deal, but helpful sometimes.
Hope that helps!
Converting a byte[]
to a string
seems simple but any kind of encoding is likely to mess up the output string. This little function just works without any unexpected results:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
You can zip
the list with itself sans the first element:
a = [5, 7, 11, 4, 5]
for previous, current in zip(a, a[1:]):
print(previous, current)
This works even if your list has no elements or only 1 element (in which case zip
returns an empty iterable and the code in the for
loop never executes). It doesn't work on generators, only sequences (tuple
, list
, str
, etc).
I think this article explains well:
Running Commands on a Remote Linux / UNIX Host
Google is your best friend ;-)
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable.
I've been through basically all of stackoverflow for this error and nothing resolved my issue. I was able to log into mysql directly from the linux command line fine, but with the same user and password couldn't log into phpmyadmin.
So I beat my head against the wall for half the day until I realized it wasn't even reading the config.inc.php under /etc/phpmyadmin (the only place it was located btw based on "find / -iname config.inc.php". So I changed the host in /usr/share/phpMyAdmin/libraries/config.default.php and it finally worked.
I know there's probably another issue with why it isn't reading the config from the /etc/phpmyadmin folder but I can't be bothered with that for now :P
tldr; if your settings don't seem to be applying at all try making the changes within /usr/share/phpMyAdmin/libraries/config.default.php
why has no answer I've seen mentioned anything about the unwrap
method? Or, even easier, the get_text
method
http://www.crummy.com/software/BeautifulSoup/bs4/doc/#unwrap http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text
To revert modified files:
sudo svn revert
svn status|grep "^ *M" | sed -e 's/^ *M *//'
For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)
Here is the solution I used for me Is works for fetching JSON from string
protected String getJSONFromString(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("cartype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("model"))
.toString();
}
In general you just have to define a slightly transparent color when creating the shape.
You can achieve that by setting the colors alpha channel.
#FF000000
will get you a solid black whereas #00000000
will get you a 100% transparent black (well it isn't black anymore obviously).
The color scheme is like this #AARRGGBB
there A stands for alpha channel, R stands for red, G for green and B for blue.
The same thing applies if you set the color in Java. There it will only look like 0xFF000000
.
UPDATE
In your case you'd have to add a solid
node. Like below.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape_my">
<stroke android:width="4dp" android:color="#636161" />
<padding android:left="20dp"
android:top="20dp"
android:right="20dp"
android:bottom="20dp" />
<corners android:radius="24dp" />
<solid android:color="#88000000" />
</shape>
The color here is a half transparent black.
I tested each of the above methods for finding if any alphabets are contained in a given string and found out average processing time per string on a standard computer.
~250 ns for
import re
~3 µs for
re.search('[a-zA-Z]', string)
~6 µs for
any(c.isalpha() for c in string)
~850 ns for
string.upper().isupper()
Opposite to as alleged, importing re takes negligible time, and searching with re takes just about half time as compared to iterating isalpha() even for a relatively small string.
Hence for larger strings and greater counts, re would be significantly more efficient.
But converting string to a case and checking case (i.e. any of upper().isupper() or lower().islower() ) wins here. In every loop it is significantly faster than re.search() and it doesn't even require any additional imports.
Although git pull origin yourbranch
works, it's not really a good idea
You can alternatively do the following:
git fetch origin
git merge origin/yourbranch
The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.
The second line merges your current branch with that of yourbranch
that you fetched from origin
(which is one of your remotes
).
This is assuming origin
points to the repository at address ssh://11.21.3.12:23211/dir1/dir2
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
On Xamarin.Android, It works for me and need change layout
var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
layout.SpanCount = GetItemPerRow(Context);
recyclerView.SetAdapter(null);
recyclerView.SetAdapter(adapter); //reset
switch() is a powerful and standard way of implementing state machines in C, but it can decrease maintainability down if you have a large number of states. Another common method is to use function pointers to store the next state. This simple example implements a set/reset flip-flop:
/* Implement each state as a function with the same prototype */
void state_one(int set, int reset);
void state_two(int set, int reset);
/* Store a pointer to the next state */
void (*next_state)(int set, int reset) = state_one;
/* Users should call next_state(set, reset). This could
also be wrapped by a real function that validated input
and dealt with output rather than calling the function
pointer directly. */
/* State one transitions to state one if set is true */
void state_one(int set, int reset) {
if(set)
next_state = state_two;
}
/* State two transitions to state one if reset is true */
void state_two(int set, int reset) {
if(reset)
next_state = state_one;
}
The percent sign is escaped using a percent sign:
System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);
The complete syntax can be accessed in java docs. This particular information is in the section Conversions
of the first link.
The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. %
is not a valid character.
<body onload="window.print()">
or
window.onload = function() { window.print(); }
list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();
Which works for me to show the time sorted in descending order.
You can use
Source.fromFile(fileName).getLines().mkString
however it should be noticed that getLines() removes all new line characters. If you want save formatting you should use
Source.fromFile(fileName).iter.mkString
=CONCATENATE(LEFT(A1,1), B1)
Assuming A1 holds 1st names; B1 Last names
(a)Simply click on your database, select your table. Click on 'Operations'. Under the 'table options' section change the AUTO_INCREMENT value to your desired value, in this case: 10000 the click 'Go'. (See the image attached)
(b)Alternatively, you can run a SQL command under the SQL tab after selecting your table. Simply type 'ALTER TABLE table_name AUTO_INCREMENT = 10000;' then click 'Go'. That's it!! SETTING AUTO INCREMENT VALUE image(a)
Count distinct values, use nunique
:
df['hID'].nunique()
5
Count only non-null values, use count
:
df['hID'].count()
8
Count total values including null values, use the size
attribute:
df['hID'].size
8
Use boolean indexing:
df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])
OR using query
:
df.query('mID == "A"')['hID'].agg(['nunique','count','size'])
Output:
nunique 5
count 5
size 5
Name: hID, dtype: int64
To achieve what you want without removing any styles you have to make the z-index of the '.parent' class bigger then the '.wholePage' class.
.parent {
position: relative;
z-index: 4; /*matters since it's sibling to wholePage*/
}
.child {
position: relative;
z-index:1; /*doesn't matter */
background-color: white;
padding: 5px;
}
jsFiddle: http://jsfiddle.net/ZjXMR/2/
(But use this in rare occasions, because HTML method is PREFERRED WAY).
.container{_x000D_
position:relative;_x000D_
}_x000D_
.container::before{ _x000D_
content:"";_x000D_
width: 100%; height: 100%; position: absolute; background: black; opacity: 0.3; z-index: 1; top: 0; left: 0;_x000D_
background: black;_x000D_
}_x000D_
.container::after{ _x000D_
content: "Your Text"; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 3; overflow: hidden; font-size: 2em; color: red; text-align: center; text-shadow: 0px 0px 5px black; background: #0a0a0a8c; padding: 5px;_x000D_
animation-name: blinking;_x000D_
animation-duration: 1s;_x000D_
animation-iteration-count: infinite;_x000D_
animation-direction: alternate;_x000D_
}_x000D_
@keyframes blinking {_x000D_
0% {opacity: 0;}_x000D_
100% {opacity: 1;}_x000D_
}
_x000D_
<div class="container">here is main content, text , <br/> images and other page details</div>
_x000D_
Use re.search(r'\((.*?)\)',s).group(1)
:
>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"
Simply alter your table, no need to any thing. just run this query on database.
ALTER TABLE table_name
CONVERT TO CHARACTER SET utf8
it will definately work.
Hi I'm late to the party.. just wanted to point out that the instructions from http://davidtsadler.com/archives/2012/06/03/how-to-install-magento-on-ubuntu/ were really useful.
I had Ubuntu server installed with Apache, MySql and Php so I thought I could jump to the heading Creating the directory from which Magento will be served from and I reached the same problem as the OP, i.e. I had 'index.php' needed in all the URLs (or I would get 404 not found). I then went back to Installing and configuring the Apache HTTP server and after restarting apache it works perfectly.
For reference, I was missing:
sudo bash -c "cat >> /etc/apache2/conf.d/servername.conf <<EOF
ServerName localhost
EOF"
... and
sudo a2enmod rewrite
sudo service apache2 restart
Hope this helps
sometimes you don't want to compare all public properties and want to compare only the subset of them, so in this case you can just move logic to compare the desired list of properties to abstract class
public abstract class ValueObject<T> where T : ValueObject<T>
{
protected abstract IEnumerable<object> GetAttributesToIncludeInEqualityCheck();
public override bool Equals(object other)
{
return Equals(other as T);
}
public bool Equals(T other)
{
if (other == null)
{
return false;
}
return GetAttributesToIncludeInEqualityCheck()
.SequenceEqual(other.GetAttributesToIncludeInEqualityCheck());
}
public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
{
return Equals(left, right);
}
public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
{
return !(left == right);
}
public override int GetHashCode()
{
int hash = 17;
foreach (var obj in this.GetAttributesToIncludeInEqualityCheck())
hash = hash * 31 + (obj == null ? 0 : obj.GetHashCode());
return hash;
}
}
and use this abstract class later to compare the objects
public class Meters : ValueObject<Meters>
{
...
protected decimal DistanceInMeters { get; private set; }
...
protected override IEnumerable<object> GetAttributesToIncludeInEqualityCheck()
{
return new List<Object> { DistanceInMeters };
}
}
I just came across a similar problem. Try
require './st.rb'
This should do the trick.
For namespace and Library
@using NameSpace_Name
For Model
@model Application_Name.Models.Model_Name
For Iterate the list on Razor Page (You Have to use foreach loop for access the list items)
@model List<Application_Name.Models.Model_Name>
@foreach (var item in Model)
{
<tr>
<td>@item.srno</td>
<td>@item.name</td>
</tr>
}
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
If you have access to SRV Records, you can use them to get what you want :)
E.G
A Records
Name: mc1.domain.com
Value: <yourIP>
Name: mc2.domain.com
Value: <yourIP>
SRV Records
Name: _minecraft._tcp.mc1.domain.com
Priority: 5
Weight: 5
Port: 25565
Value: mc1.domain.com
Name: _minecraft._tcp.mc2.domain.com
Priority: 5
Weight: 5
Port: 25566
Value: mc2.domain.com
then in minecraft you can use
mc1.domain.com which will sign you into server 1 using port 25565
and
mc2.domain.com which will sign you into server 2 using port 25566
then on your router you can have it point 25565 and 25566 to the machine with both servers on and Voilà!
Source: This works for me running 2 minecraft servers on the same machine with ports 50500 and 50501
You can eventually extend the EL language by using the EL Functor, which will allow you to call any Java beans methods, even with parameters...
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.
If you allocate the array on the heap you should be fine, assuming your machine has enough memory.
int* array = new int[1000000];
But remember that this will require you to delete[]
the array. A better solution would be to use std::vector<int>
and resize it to 1000000 elements.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
In general, an "object" is an instance of a class, which is an "image"/"fingerprint" of a class created in memory (via New keyword).
The variable of object type refers to this memory location, that is, it essentially contains the address in memory.
So a parameter of object type passes a reference/"link" to an object, not a copy of the whole object.
http://www.mail-archive.com/[email protected]/msg03998.html says:
...and .removeClass() would remove all classes...
It works for me ;)
cheers
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.
There has been a discussion here which might help: Is there a simple way to convert C++ enum to string?
UPDATE: Here#s a script for Lua which creates an operator<< for each named enum it encounters. This might need some work to make it work for the less simple cases [1]:
function make_enum_printers(s)
for n,body in string.gmatch(s,'enum%s+([%w_]+)%s*(%b{})') do
print('ostream& operator<<(ostream &o,'..n..' n) { switch(n){')
for k in string.gmatch(body,"([%w_]+)[^,]*") do
print(' case '..k..': return o<<"'..k..'";')
end
print(' default: return o<<"(invalid value)"; }}')
end
end
local f=io.open(arg[1],"r")
local s=f:read('*a')
make_enum_printers(s)
Given this input:
enum Errors
{ErrorA=0, ErrorB, ErrorC};
enum Sec {
X=1,Y=X,foo_bar=X+1,Z
};
It produces:
ostream& operator<<(ostream &o,Errors n) { switch(n){
case ErrorA: return o<<"ErrorA";
case ErrorB: return o<<"ErrorB";
case ErrorC: return o<<"ErrorC";
default: return o<<"(invalid value)"; }}
ostream& operator<<(ostream &o,Sec n) { switch(n){
case X: return o<<"X";
case Y: return o<<"Y";
case foo_bar: return o<<"foo_bar";
case Z: return o<<"Z";
default: return o<<"(invalid value)"; }}
So that's probably a start for you.
[1] enums in different or non-namespace scopes, enums with initializer expressions which contain a komma, etc.
A parent ViewGroup into which the fragment's View is to be inserted,
A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.
In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
So, You need to call rootView
in here
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
If you already know the process then this will be useful:
PID=`ps -eaf | grep <process> | grep -v grep | awk '{print $2}'`
if [[ "" != "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
fi
You can see formControlName in label , removing this solved my problem
I was trying to follow the flow described here - but haven't luck to completely kill the session.. Then I fond additional step here:
http://wyding.blogspot.com/2013/08/solution-for-ora-01940-cannot-drop-user.html
What I did:
1. select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>';
- as described below.
Out put will be something like this:alter system kill session '22,15' immediate;
2. alter system disconnect session '22,15' IMMEDIATE ;
- 22-sid, 15-serial - repeat the command for each returned session from previous command
3. Repeat steps 1-2 while select...
not return an empty table
4. Call
drop user...
What was missed - call alter system disconnect session '22,15' IMMEDIATE ;
for each of session returned by select 'alter system kill session '..
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
Difference between Proxy server (also called forward proxy) and Reverse Proxy Server depends on the point of reference.
Technically, both are exactly the same. Both serve the same purpose of transmitting data to a destination on behalf of a source.
The difference lies in 'on whose behalf is the proxy server acting / who is the proxy server representing?'
If the proxy server is forwarding requests to internet server on behalf of the end users (Example: students in a college accessing internet through college proxy server.), then the proxy is called 'Forward proxy' or simply 'Proxy'.
If the proxy server is responding to incoming requests, on behalf of a server, then the proxy is called 'Reverse Proxy', as it is working in the reverse direction, from the point of view of the end user.
Some Examples of Reverse proxies:
Use of forward proxy:
Use of Reverse proxy:
Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...
create or replace procedure temp_proc is
begin
DBMS_OUTPUT.ENABLE(1000000);
DBMS_OUTPUT.PUT_LINE('Test');
end;
...and call it in a PLSQL block...
begin
temp_proc;
end;
...as SQL is non-procedural.
In the top answer, I think the if (timer)
statement has been mistakenly placed within the stop()
function call. It should instead be placed within the run()
function call like if (timer) timer = setTimeout(run, 200)
. This prevents future setTimeout
statements from being run right after stop()
is called.
EDIT 2: The top answer is CORRECT for synchronous function calls. If you want to make async function calls, then use mine instead.
Given below is an example with what I think is the correct way (feel to correct me if I am wrong since I haven't yet tested this):
const runSetTimeoutsAtIntervals = () => {
const timeout = 1000 // setTimeout interval
let runFutureSetTimeouts // Flag that is set based on which cycle continues or ends
const runTimeout = async() => {
await asyncCall() // Now even if stopRunSetTimeoutsAtIntervals() is called while this is running, the cycle will stop
if (runFutureSetTimeouts) runFutureSetTimeouts = setTimeout(runTimeout, timeout)
}
const stopRunSetTimeoutsAtIntervals = () => {
clearTimeout(runFutureSetTimeouts)
runFutureSetTimeouts = false
}
runFutureSetTimeouts = setTimeout(runTimeout, timeout) // Set flag to true and start the cycle
return stopRunSetTimeoutsAtIntervals
}
// You would use the above function like follows.
const stopRunSetTimeoutsAtIntervals = runSetTimeoutsAtIntervals() // Start cycle
stopRunSetTimeoutsAtIntervals() // Stop cycle
EDIT 1: This has been tested and works as expected.
function
getValue(input){
var value = input.value ? parseInt(input.value) : 0;
let min = input.min;
let max = input.max;
if(value < min)
return parseInt(min);
else if(value > max)
return parseInt(max);
else return value;
}
Usages
changeDotColor = (event) => {
let value = this.getValue(event.target) //value will be always number
console.log(value)
console.log(typeof value)
}
It should be,
*/15 * * * * your_command_or_whatever
From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):
The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.
In C, the name s appearing in
struct s { ... };
is a tag. A tag name is not a type name. Given the definition above, declarations such as
s x; /* error in C */ s *p; /* error in C */
are errors in C. You must write them as
struct s x; /* OK */ struct s *p; /* OK */
The names of unions and enumerations are also tags rather than types.
In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,
struct s s;
is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.
Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining
struct s { ... }; typedef struct s S;
lets you use S in place of struct s, as in
S x; S *p;
A program cannot use S as the name of both a type and a variable (or function or enumeration constant):
S S; // error
This is good.
The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:
typedef struct { ... } S;
The linked article also has a discussion about how the C++ behavior of not requireing a typedef
can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef
your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef
the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.
Since ES6, you can use template literals:
const age = 3_x000D_
console.log(`I'm ${age} years old!`)
_x000D_
P.S. Note the use of backticks: ``
.
// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})
// 2. Get first item
var item = items[0]
Shorter:
var item = items.sort(function() {return 0.5 - Math.random()})[0];
class
is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class
itself.
e.g.
class ANewType
{
// ... details
};
This defines a new type called ANewType
which is a class type.
You can then use this in function declarations:
void function(ANewType object);
You can then pass objects of type ANewType
into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.
If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.
void function(ANewType& object); // object passed by reference
This syntax means that any use of object
in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.
[* The class
keyword is also used in template definitions, but that's a different subject.]
I solved my problem simply using ng-init
for default selection instead of ng-checked
<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />
This code allows you to autoplay iframe video
<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
It is common to get this issue. I cannot set any specific Java home in my system as I have 2 different version of Java (Java 6 and Java 7) for different environment. To resolve the issue, I included the JDK path in the run configuration when opening the build.xml file. This way, 2 different build files use 2 different Java version for build. I think there might be a better solution to this problem but at least the above approach avoid setting the JAVA_HOME variable.
Thanks nikie for that great Laplace suggestion. OpenCV docs pointed me in the same direction: using python, cv2 (opencv 2.4.10), and numpy...
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
numpy.max(cv2.convertScaleAbs(cv2.Laplacian(gray_image,3)))
result is between 0-255. I found anything over 200ish is very in focus, and by 100, it's noticeably blurry. the max never really gets much under 20 even if it's completely blurred.
You can just tell Finder to open the .sh
file in Terminal:
This will have the exact same effect as renaming it to .command
except… you don't have to rename it :)
If you have to get an attribute that is not the ID. I would use CollectionUtils.
Dog someDog = new Dog();
Dog dog = CollectionUtils(dogList, new Predicate() {
@Override
public boolean evaluate(Object o)
{
Dog d = (Dog)o;
return someDog.getName().equals(d.getName());
}
});
Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>
This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
It has nothing to do with your form or the values in it. It gets fired by the browser to prevent the user from repeating the same request with the cached data. If you really need to enable the refreshing of the result page, you should redirect the user, either via PHP (header('Location:result.php');
) or other server-side language you're using. Meta tag solution should work also to disable the resending on refresh.
On new El Capitan installation where SIP(rootless prevents access to usr/lib/) is on by default and you cannot create the symlink unless you are in recovery mode. As @yannisxu said you can disable SIP and do your symlink to /usr/lib/local and this will work.
you can use the following command on MAC OSX El Capitan instead of turning off SIP:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
There used to be an option where you can login as root and this can disable SIP but in the final release that is now obsolete, you can read more about it here: https://forums.developer.apple.com/thread/4686
Question:
There is a nvram boot-args command available in Developer Beta 1 which can disable SIP when run with root privileges:
nvram boot-args="rootless=0"
Will this option of disabling SIP also be available in the El Capitan release version? Or is this strictly for the Developer Builds?
Answer:
This nvram boot-args command will be going away. It will not be available in the El Capitan release version and may disappear before the end of the Developer Betas. Keep an eye on the release notes for future Developer Betas.
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
>>> xs = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> xs.sort(key=lambda x: x[1])
>>> reduce(lambda l, x: (l.append([x]) if l[-1][0][1] != x[1] else l[-1].append(x)) or l, xs[1:], [[xs[0]]]) if xs else []
[[['A', 0], ['C', 0]], [['B', 1]], [['D', 2], ['E', 2]]]
Basically, if the list is sorted, it is possible to reduce
by looking at the last group constructed by the previous steps - you can tell if you need to start a new group, or modify an existing group. The ... or l
bit is a trick that enables us to use lambda
in Python. (append
returns None
. It is always better to return something more useful than None
, but, alas, such is Python.)
In my case, the problem was that I was building on a, older virtual machine which was based on Win7.
I found this fix from https://github.com/NuGet/NuGetGallery/issues/8176#issuecomment-683923724 :
nuget.org started enforcing the use of TLS 1.2 (and dropped support for TLS 1.1 and 1.0) earlier this year. Windows 7 has TLS 1.2 disabled by default (check the
DisabledByDefault
value underHKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client
in your registry). To enable the support, please make sure you have an update (*) installed and switch the support on:reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v DisabledByDefault /t REG_DWORD /d 0 /f /reg:32 reg add "HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v DisabledByDefault /t REG_DWORD /d 0 /f /reg:64 reg add "HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v Enabled /t REG_DWORD /d 1 /f /reg:32 reg add "HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v Enabled /t REG_DWORD /d 1 /f /reg:64
The (*) update referred to was Microsoft kb3140245: Update for Windows 7 (KB3140245)
I installed the update, rebooted (as requested by the update), added those registry keys, and then Nuget worked fine.
I had this same problem, my solution:
In the web.config file :
<compilation debug="true>
had to be changed to
<compilation debug="true" targetFramework="4.0">
try this query
SELECT ID, FirstName, LastName FROM table GROUP BY(FirstName)
Try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
...and you might also want to do this too:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline 1 */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000, _x000D_
/* Outline 2 */_x000D_
-2px -2px 0 #ff0000,_x000D_
2px -2px 0 #ff0000,_x000D_
-2px 2px 0 #ff0000,_x000D_
2px 2px 0 #ff0000, _x000D_
-3px 0 0 #ff0000,_x000D_
3px 0 0 #ff0000,_x000D_
0 3px 0 #ff0000,_x000D_
0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.
Have fun!
Update: Before continuing everyone should read and understand the html5rocks tutorial on CORS. It is easy to understand and very clear.
If you control the server being POSTed, simply leverage the "Cross-Origin Resource Sharing standard" by setting response headers on the server. This answer is discussed in other answers in this thread, but not very clearly in my opinion.
In short here is how you accomplish the cross domain POST from from.com/1.html to to.com/postHere.php (using PHP as an example). Note: you only need to set Access-Control-Allow-Origin
for NON OPTIONS
requests - this example always sets all headers for a smaller code snippet.
In postHere.php setup the following:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://from.com': case 'https://from.com':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
This allows your script to make cross domain POST, GET and OPTIONS. This will become clear as you continue to read...
Setup your cross domain POST from JS (jQuery example):
$.ajax({
type: 'POST',
url: 'https://to.com/postHere.php',
crossDomain: true,
data: '{"some":"json"}',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
When you do the POST in step 2, your browser will send a "OPTIONS" method to the server. This is a "sniff" by the browser to see if the server is cool with you POSTing to it. The server responds with an "Access-Control-Allow-Origin" telling the browser its OK to POST|GET|ORIGIN if request originated from "http://from.com" or "https://from.com". Since the server is OK with it, the browser will make a 2nd request (this time a POST). It is good practice to have your client set the content type it is sending - so you'll need to allow that as well.
MDN has a great write-up about HTTP access control, that goes into detail of how the entire flow works. According to their docs, it should "work in browsers that support cross-site XMLHttpRequest". This is a bit misleading however, as I THINK only modern browsers allow cross domain POST. I have only verified this works with safari,chrome,FF 3.6.
Keep in mind the following if you do this:
This depends very much on the specific case. Preferably, I think one should use the switch
over the if-else
if there are many nested if-elses
.
The question is how much is many?
Yesterday I was asking myself the same question:
public enum ProgramType {
NEW, OLD
}
if (progType == OLD) {
// ...
} else if (progType == NEW) {
// ...
}
if (progType == OLD) {
// ...
} else {
// ...
}
switch (progType) {
case OLD:
// ...
break;
case NEW:
// ...
break;
default:
break;
}
In this case, the 1st if
has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.
I ended up choosing the switch
because it just reads better.
From JQuery Documentation
The jqXHR objects returned by $.ajax()
as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax()
request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done()
for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail()
method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
(added in jQuery 1.6)
An alternative construct to the complete callback option, the .always()
method replaces the deprecated .complete()
method.
In response to a successful request, the function's arguments are the same as those of .done()
: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail()
: the jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done()
and .fail()
methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then()
for implementation details.
Deprecation Notice: The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callbacks are removed as of jQuery 3.0. You can usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
The below code will help you to merge two JSON object which has nested objects.
function mergeJSON(source1,source2){
/*
* Properties from the Souce1 object will be copied to Source2 Object.
* Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
* */
var mergedJSON = Object.create(source2);// Copying Source2 to a new Object
for (var attrname in source1) {
if(mergedJSON.hasOwnProperty(attrname)) {
if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
/*
* Recursive call if the property is an object,
* Iterate the object and set all properties of the inner object.
*/
mergedJSON[attrname] = zrd3.utils.mergeJSON(source1[attrname], mergedJSON[attrname]);
}
} else {//else copy the property from source1
mergedJSON[attrname] = source1[attrname];
}
}
return mergedJSON;
}
I prefer following economic solution
BEGIN
FOR i IN (SELECT NULL FROM USER_OBJECTS WHERE OBJECT_TYPE = 'TABLE' AND OBJECT_NAME = 'TABLE_NAME') LOOP
EXECUTE IMMEDIATE 'DROP TABLE TABLE_NAME';
END LOOP;
END;
Alternate for Page Refresh (F5)
driver.navigate().refresh();
(or)
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
With Dedexer, you can disassemble the .dex
file into dalvik bytecode (.ddx
).
Decompiling towards Java isn't possible as far as I know.
You can read about dalvik bytecode here.
The first variant is indeed more efficient than the second when the function is called either zero or one times. With the second and subsequent invocations, however, the "import every call" approach is actually less efficient. See this link for a lazy-loading technique that combines the best of both approaches by doing a "lazy import".
But there are reasons other than efficiency why you might prefer one over the other. One approach is makes it much more clear to someone reading the code as to the dependencies that this module has. They also have very different failure characteristics -- the first will fail at load time if there's no "datetime" module while the second won't fail until the method is called.
Added Note: In IronPython, imports can be quite a bit more expensive than in CPython because the code is basically being compiled as it's being imported.
http://docs.python.org/library/configparser.html
Python's standard library might be helpful in this case.
For those who are still stumped with this problem (I tried all the above suggestions) --
If you're on a 64-bit version of Windows and you've installed the 32-bit JDK, besides adjusting PATH
variables, you may need to adjust registry variables, too.
I was pulling my hair out, having correctly set my PATH
variables -- still to no avail -- and then only finding "vacated" Java entries in my registry, seemingly a deadend of fixing the "misfiring" Java Runtime Environment.
By using Process Monitor
to watch the program I was trying to get started, in order to sniff out where it was looking in the registry for Java (Runtime Environment), I triumphantly discovered that it's looking in the 32-bit version of registry entries, found in HKEY_LOCAL_MACHINE\SOFTWARE\**Wow6432Node**\JavaSoft\Java Runtime Environment
.
Within that key, you should find subkeys of different Java versions installed (past and/or present). Click on the subkey of the latest version (my subkey is currently 1.7.0_25, for example). After clicking on that subkey, you'll see registry string values listed on the right, and particularly, JavaHome
and RuntimeLib
. You need to modify the values of those two values to reflect the both the current folder and jvm.dll file, respectively.
For example, in my case, the values were (previously) respectively set at C:\Program Files (x86)\Java\jre7
and C:\Program Files (x86)\Java\jre7\bin\client\jvm.dll
which are nonexistent on my machine. I had to update these to the current folder and file of C:\Program Files (x86)\Java\jdk1.7.0_25\jre
and C:\Program Files (x86)\Java\jdk1.7.0_25\jre\bin\client\jvm.dll
.
Again, this will depend entirely on both what version of Java (JDK and/or JRE) you have installed -- 32 or 64-bit -- and what type of operating system you're on -- 32 or 64-bit. Just know that they're reflected in different locations within the registry (like the Wow6432Node
for 32 bit applications, in my case with the 32-bit JDK installed on a 64-bit machine).
Now that I've updated those two registry values, my program runs flawlessly, with no more hiccups or complaints about a missing Java Runtime Environment (stemming from the registry).
I know this an old question but I just wanted to add if you would like to easily change the height of a UITextField from inside IB then simply change that UITextfield's border type to anything other than the default rounded corner type. Then you can stretch or change height attributes easily from inside the editor.
I'm answering on specific to this error code(08s01).
usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".
1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.
2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days
3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.
if the array looks like:
the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)
Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed.
ps -o nlwp <pid>
Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).
Without using a visual selection, gU<motion>
will make the characters in motion
uppercase, or use gu<motion>
for lowercase.
For more of these, see Section 3 in Vim's change.txt help file.
HERE ARE SIMPLE STEPS TO REMOVE PUBLIC IN URL (Laravel 5)
1: Copy all files form public folder and past them in laravel root folder
2: Open index.php and change
From
require __DIR__.'/../bootstrap/autoload.php';
To
require __DIR__.'/bootstrap/autoload.php';
And
$app = require_once __DIR__.'/../bootstrap/app.php';
To
$app = require_once __DIR__.'/bootstrap/app.php';
In laravel 4 path 2 is $app = require_once __DIR__.'/bootstrap/start.php';
instead of $app = require_once __DIR__.'/bootstrap/app.php';/app.php
That is it.
var defaultSettings = {
ajaxsettings: {},
uisettings: {}
};
Take a look at this site: http://www.json.org/
Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.
Simply restart the Android Studio. In my case, I was offline before starting the Android Studio, but online when I did restart.
If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.
If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.
My suggestions :
For setting the values in the number, use constructors. Do not use like the methods you have used above like :
public void setNumber(double fnum, double snum){ this.fn = fnum; this.sn = snum; }
Constructors exists to initialize the objects.This is their job and they are pretty good at it.
Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well
In the main class, create a Calculate object using the new operator and the constructor in place.
Call the getAnswer() method with the created Calculate object.
Rest of the code looks fine to me. Be modular. You could read your program in a much better way.
Here is my modular piece of code. Two files : Main.java & Calculate.java
public class Calculate {
private double fn;
private double sn;
private char op;
public double getFn() {
return fn;
}
public void setFn(double fn) {
this.fn = fn;
}
public double getSn() {
return sn;
}
public void setSn(double sn) {
this.sn = sn;
}
public char getOp() {
return op;
}
public void setOp(char op) {
this.op = op;
}
public Calculate(double fn, double sn, char op) {
this.fn = fn;
this.sn = sn;
this.op = op;
}
public void getAnswer(){
double ans;
switch (getOp()){
case '+':
ans = add(getFn(), getSn());
ansOutput(ans);
break;
case '-':
ans = sub (getFn(), getSn());
ansOutput(ans);
break;
case '*':
ans = mul (getFn(), getSn());
ansOutput(ans);
break;
case '/':
ans = div (getFn(), getSn());
ansOutput(ans);
break;
default:
System.out.println("--------------------------");
System.out.println("Invalid choice of operator");
System.out.println("--------------------------");
}
}
public static double add(double x,double y){
return x + y;
}
public static double sub(double x, double y){
return x - y;
}
public static double mul(double x, double y){
return x * y;
}
public static double div(double x, double y){
return x / y;
}
public static void ansOutput(double x){
System.out.println("----------- -------");
System.out.printf("the answer is %.2f\n", x);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Let me solve this question with a practical example in the form of a simple dice rolling app that calls 1 of 6 dice face images randomly to the screen when tapped.
first declare a variable that generates random numbers (don't forget to import dart.math). Then declare a variable that parses the initial random number within constraints between 1 and 6 as an Integer.
Both variables are static private in order to be initialized once.This is is not a huge deal but would be good practice if you had to initialize a whole bunch of random numbers.
static var _random = new Random();
static var _diceface = _random.nextInt(6) +1 ;
Now create a Gesture detection widget with a ClipRRect as a child to return one of the six dice face images to the screen when tapped.
GestureDetector(
onTap: () {
setState(() {
_diceface = _rnd.nextInt(6) +1 ;
});
},
child: ClipRRect(
clipBehavior: Clip.hardEdge,
borderRadius: BorderRadius.circular(100.8),
child: Image(
image: AssetImage('images/diceface$_diceface.png'),
fit: BoxFit.cover,
),
)
),
A new random number is generated each time you tap the screen and that number is referenced to select which dice face image is chosen.
I hoped this example helped :)
1) Check if you are using OnItemClickListener or OnClickListener (which is not supported for ListView)
Documentation Android Developers ListView
2) Check if you added Listener to your ListView properly. It's hooked on ListView not on ListAdapter!
ListView.setOnItemClickListener(listener);
3) If you need to use OnClickListener, check if you do use DialogInterface.OnClickListener
or View.OnClickListener
(they can be easily exchanged if not validated or if using both of them)
implementation Without a Controller.
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
<body>_x000D_
_x000D_
<script>_x000D_
var app = angular.module("myShoppingList", []); _x000D_
</script>_x000D_
_x000D_
<div ng-app="myShoppingList" ng-init="products = ['Milk','Bread','Cheese']">_x000D_
<ul>_x000D_
<li ng-repeat="x in products track by $index">{{x}}_x000D_
<span ng-click="products.splice($index,1)">×</span>_x000D_
</li>_x000D_
</ul>_x000D_
<input ng-model="addItem">_x000D_
<button ng-click="products.push(addItem)">Add</button>_x000D_
</div>_x000D_
_x000D_
<p>Click the little x to remove an item from the shopping list.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The splice() method adds/removes items to/from an array.
array.splice(index, howmanyitem(s), item_1, ....., item_n)
index: Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.
howmanyitem(s): Optional. The number of items to be removed. If set to 0, no items will be removed.
item_1, ..., item_n: Optional. The new item(s) to be added to the array
It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute
. If so, you should make sure that you inherit that, and not ActionFilterAttribute
, in order to let ASP.NET MVC do more of the work for you.
Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Do whatever checking you need here
// If you want the base check as well (against users/roles) call
base.OnAuthorization(filterContext);
}
}
There is a good question with an answer with more details here on SO.
I had an error with an array getting the max and the min so my solution was:
int max = Arrays.stream(arrayWithInts).max().getAsInt();
int min = Arrays.stream(arrayWithInts).min().getAsInt();
Use the function Contains
from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
You already implicitly have multiple implicit return statements, caused by error handling, so deal with it.
As is typical with programming, though, there are examples both for and against the multiple return practice. If it makes the code clearer, do it one way or the other. Use of many control structures can help (the case statement, for example).
Have you tried changing the specific levels of your Hospital
vector?
levels(survey$hospital)[levels(survey$hospital) == "Hospital #1"] <- "Hosp 1"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #2"] <- "Hosp 2"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #3"] <- "Hosp 3"
Just use a subquery with INNER JOIN, LEFT JOIN or smth else:
DELETE FROM m_productprice
WHERE m_product_id IN
(
SELECT B.m_product_id
FROM m_productprice B
INNER JOIN m_product C
ON B.m_product_id = C.m_product_id
WHERE C.upc = '7094'
AND B.m_pricelist_version_id = '1000020'
)
to optimize the query,
IN
PHP can be easily utilized for reading bar codes printed on paper documents. Connecting manual barcode reader to the computer via USB significantly extends usability of PHP (or any other web programming language) into tasks involving document and product management, like finding a book records in the database or listing all bills for a particular customer.
Following sections briefly describe process of connecting and using manual bar code reader with PHP.
The usage of bar code scanners described in this article are in the same way applicable to any web programming language, such as ASP, Python or Perl. This article uses only PHP since all tests have been done with PHP applications.
What is a bar code reader (scanner)
Bar code reader is a hardware pluggable into computer that sends decoded bar code strings into computer. The trick is to know how to catch that received string. With PHP (and any other web programming language) the string will be placed into focused input HTML element in browser. Thus to catch received bar code string, following must be done:
just before reading the bar code, proper input element, such as INPUT TEXT FIELD must be focused (mouse cursor is inside of the input field). once focused, start reading the code when the code is recognized (bar code reader usually shortly beeps), it is send to the focused input field. By default, most of bar code readers will append extra special character to decoded bar code string called CRLF (ENTER). For example, if decoded bar code is "12345AB", then computer will receive "12345ABENTER". Appended character ENTER (or CRLF) emulates pressing the key ENTER causing instant submission of the HTML form:
<form action="search.php" method="post">
<input name="documentID" onmouseover="this.focus();" type="text">
</form>
Choosing the right bar code scanner
When choosing bar code reader, one should consider what types of bar codes will be read with it. Some bar codes allow only numbers, others will not have checksum, some bar codes are difficult to print with inkjet printers, some barcode readers have narrow reading pane and cannot read for example barcodes with length over 10 cm. Most of barcode readers support common barcodes, such as EAN8, EAN13, CODE 39, Interleaved 2/5, Code 128 etc.
For office purposes, the most suitable barcodes seem to be those supporting full range of alphanumeric characters, which might be:
Other important things to note:
Installing scanner drivers
Installing manual bar code reader requires installing drivers for your particular operating system and should be normally supplied with purchased bar code reader.
Once installed and ready, bar code reader turns on signal LED light. Reading the barcode starts with pressing button for reading.
Scanning the barcode - how does it work?
STEP 1 - Focused input field ready for receiving character stream from bar code scanner:
STEP 2 - Received barcode string from bar code scanner is immediatelly submitted for search into database, which creates nice "automated" effect:
STEP 3 - Results returned after searching the database with submitted bar code:
Conclusion
It seems, that utilization of PHP (and actually any web programming language) for scanning the bar codes has been quite overlooked so far. However, with natural support of emulated keypress (ENTER/CRLF) it is very easy to automate collecting & processing recognized bar code strings via simple HTML (GUI) fomular.
The key is to understand, that recognized bar code string is instantly sent to the focused HTML element, such as INPUT text field with appended trailing character ASCII 13 (=ENTER/CRLF, configurable option), which instantly sends input text field with populated received barcode as a HTML formular to any other script for further processing.
Reference: http://www.synet.sk/php/en/280-barcode-reader-scanner-in-php
Hope this helps you :)
I am not sure I fully understand the problem, but pulling an existing branch is done like this (at least it works for me :)
git pull origin BRANCH
This is assuming that your local branch is created off of the origin/BRANCH.
MY UPDATE TO TONY L'S ANSWER
This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position
or only wanting horizontal/vertical centering rather than both.
center.js:
// We add a pos parameter so we can specify which position type we want
// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
this.css("position", pos);
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it vertically only
jQuery.fn.centerVer = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
return this;
}
In my <head>
:
<script src="scripts/center.js"></script>
Examples of usage:
$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")
$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")
$("#example5").center("absolute")
$("#example6").center("fixed")
It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.
Hope this is useful for someone out there! Enjoy.
In my opinion a very easy and clean way could be:
git checkout -f A
git symbolic-ref HEAD refs/heads/master
git commit
Make use of jquery toggle function which do the task for you
.toggle() - Display or hide the matched elements.
$('#myelement').click(function(){
$('#another-element').toggle('slow');
});
for simple comments:
set serveroutput on format wrapped;
begin
DBMS_OUTPUT.put_line('simple comment');
end;
/
-- do something
begin
DBMS_OUTPUT.put_line('second simple comment');
end;
/
you should get:
anonymous block completed
simple comment
anonymous block completed
second simple comment
if you want to print out the results of variables, here's another example:
set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
DBMS_OUTPUT.put_line(a_comment);
end;
/
-- do something
declare
a_comment VARCHAR2(200) :='comment';
begin
DBMS_OUTPUT.put_line(a_comment || 2);
end;
your output should be:
anonymous block completed
first comment
anonymous block completed
comment2
This depends on what function1 is doing.
If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.
If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:
function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}
function MyCallback(result)
{
function2(result);
}
Had forgotten this issue... I was actually asking with Eclipse, sorry for not stating that originally. And the answer seems to be too simple (at least with 3.5; probably with older versions also):
Java run configuration's Arguments : VM arguments:
-Djava.library.path="${workspace_loc:project}\lib;${env_var:PATH}"
Must not forget the quotation marks, otherwise there are problems with spaces in PATH.
I am running Ubuntu 16.04 (Xenial Xerus). This is what worked for me:
/etc/apache2/sites-available
. There
you will find a file called 000-default.conf
.cp 000-default.conf example.local.conf
<VirtualHost *:80>
to <VirtualHost example.local:80>
ServerName example.local
And if you need to, add this line: ServerAlias www.example.local
service Apache2 restart
Open a browser and navigate to example.local
. You should see your website.
You were almost there. Here is what you can try though.
$(function(){
$("#txtSearchProdAssign").keyup(function (e) {
if (e.which == 13) {
$('input[name="butAssignProd"]').trigger('click');
}
});
});
I have used trigger()
to execute click and bind it on the keyup
event insted of keydown
because click
event comprises of two events actually i.e. mousedown
then mouseup
. So to resemble things same as possible with keydown
and keyup
.
Here is a Demo
I had a similar issue and ended up with this:
For me this has the advantage that data and annotation are not overlapping.
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
x = A[ind]
y = B[ind]
xPos = x1 + .02 * (x1 - x0)
yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
ax.annotate('',#label,
xy=(x, y), xycoords='data',
xytext=(xPos, yPos), textcoords='data',
arrowprops=dict(
connectionstyle="arc3,rad=0.",
shrinkA=0, shrinkB=10,
arrowstyle= '-|>', ls= '-', linewidth=2
),
va='bottom', ha='left', zorder=19
)
ax.text(xPos + .01 * (x1 - x0), yPos,
'({:.2f}, {:.2f})'.format(x,y),
transform=ax.transData, va='center')
plt.grid()
plt.show()
Using the text argument in .annotate
ended up with unfavorable text positions.
Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.
You can just use:
> names(LIST)
[1] "A" "B"
Obviously the names of the first element is just
> names(LIST)[1]
[1] "A"
Well I did a bit of searching around the internet for you and I found this handy link.
Easiest way to find duplicate values in a JavaScript array
You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.
I believe the reason why the first set of properties will not work is because there is no auto
value for display
, so that property should be ignored. In that case, inline-table
will still take effect, and as width
do not apply to inline
elements, that set of properties will not do anything.
The second set of properties will simply hide the table, as that's what display: none
is for.
Try resetting it to table
instead:
table.other {
width: auto;
min-width: 0;
display: table;
}
Edit: min-width
defaults to 0
, not auto
I discovered that I had to include
body { width:100%; }
for "margin: 0 auto" to work for tables.
See the Range.SpecialCells method. For example, to get cells with constant values or formulas use:
_xlWorksheet.UsedRange.SpecialCells(
Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants |
Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeFormulas)
So why is td default set to vertical-align: top;? I really don't know that yet. I would not dare to touch it. Instead add this to your stylesheet. It alters the buttons in the tables.
table .btn{
vertical-align: top;
}
You need to create a popover instance that has the html option enabled (place this in your javascript file after the popover JS code):
$('.popover-with-html').popover({ html : true });
I was getting a same error. I found out the solution that I had created the primary key in the main table as BIGINT UNSIGNED and was declaring it as a foreign key in the second table as only BIGINT.
When I declared my foreign key as BIGINT UNSIGED in second table, everything worked fine, even didn't need any indexes to be created.
So it was a datatype mismatch between the primary key and the foreign key :)
Try hitting the URL with "https://" instead of "http://"
The jquery BalusC's solution improved by me. Used also: Brad Robertson's comment here.
Just put this in a .js, use the wide class for your desired combos and don't forge to give it an Id. Call the function in the onload (or documentReady or whatever).
As simple ass that :)
It will use the width that you defined for the combo as minimun length.
function fixIeCombos() {
if ($.browser.msie && $.browser.version < 9) {
var style = $('<style>select.expand { width: auto; }</style>');
$('html > head').append(style);
var defaultWidth = "200";
// get predefined combo's widths.
var widths = new Array();
$('select.wide').each(function() {
var width = $(this).width();
if (!width) {
width = defaultWidth;
}
widths[$(this).attr('id')] = width;
});
$('select.wide')
.bind('focus mouseover', function() {
// We're going to do the expansion only if the resultant size is bigger
// than the original size of the combo.
// In order to find out the resultant size, we first clon the combo as
// a hidden element, add to the dom, and then test the width.
var originalWidth = widths[$(this).attr('id')];
var $selectClone = $(this).clone();
$selectClone.addClass('expand').hide();
$(this).after( $selectClone );
var expandedWidth = $selectClone.width()
$selectClone.remove();
if (expandedWidth > originalWidth) {
$(this).addClass('expand').removeClass('clicked');
}
})
.bind('click', function() {
$(this).toggleClass('clicked');
})
.bind('mouseout', function() {
if (!$(this).hasClass('clicked')) {
$(this).removeClass('expand');
}
})
.bind('blur', function() {
$(this).removeClass('expand clicked');
})
}
}
Here is another alternative solution. You can use ClientScriptManager Page.ClientScript.RegisterArrayDeclaration. Here is an example for chart data.
var page = HttpContext.Current.CurrentHandler as Page;
_data = "[Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]";
page.ClientScript.RegisterArrayDeclaration("chartdata0", _data);
This code creates an array on the client side
var chartdata0 = new Array([Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]);
See the following article
This solution has an issue with bigger arrays on chrome 64 browser including "Version 78.0.3904.70 (Official Build) (64-bit)". You may get "Uncaught RangeError: Maximum call stack size exceeded". However it is working with IE11, Microsoft Edge, and FireFox.
If you want to configure for the standalone log4j applications, you can use the BasicConfigurator. This solution won't be good for the web applications like Spring environment.
You need to write-
BasicConfigurator.configure();
or
ServletContext sc = config.getServletContext();
String log4jLocation = config.getInitParameter("log4j-properties-location");
String webAppPath = sc.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
PropertyConfigurator.configure(log4jProp);
Slightly shorter version using methods chain:
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
.Select(g => new {Value = g.Key, Count = g.Count()})
.OrderByDescending(x=>x.Count);
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
You don't need to explicitly use qualifiers like item.photo == ''
or item.photo != ''
. Like in JavaScript, an empty string will be evaluated as false.
Your views will be much cleaner and readable as well.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>_x000D_
<div ng-app init="item = {photo: ''}">_x000D_
<div ng-if="item.photo"> show if photo is not empty</div>_x000D_
<div ng-if="!item.photo"> show if photo is empty</div>_x000D_
_x000D_
<input type=text ng-model="item.photo" placeholder="photo" />_x000D_
</div
_x000D_
Updated to remove bug in Angular
Not really and I am talking about SQL Server. The temp table (with single #) exists and is visible within the scope it is created (scope-bound). Each time you call your stored procedure it creates a new scope and therefore that temp table exists only in that scope. I believe the temp tables are also visible to stored procedures and udfs that're called within that scope as well. If you however use double pound (##) then they become global within your session and therefore visible to other executing processes as part of the session that the temp table is created in and you will have to think if the possibility of temp table being accessed concurrently is desirable or not.
Try this library, its lightweight and easy to implement
https://github.com/sunnag7/FontStyler
<com.sunnag.fontstyler.FontStylerView
android:textStyle="bold"
android:text="@string/about_us"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp"
app:fontName="Lato-Bold"
android:textSize="18sp"
android:id="@+id/textView64" />
Use actionListener
if you want have a hook before the real business action get executed, e.g. to log it, and/or to set an additional property (by <f:setPropertyActionListener>
), and/or to have access to the component which invoked the action (which is available by ActionEvent
argument). So, purely for preparing purposes before the real business action gets invoked.
The actionListener
method has by default the following signature:
import javax.faces.event.ActionEvent;
// ...
public void actionListener(ActionEvent event) {
// ...
}
And it's supposed to be declared as follows, without any method parentheses:
<h:commandXxx ... actionListener="#{bean.actionListener}" />
Note that you can't pass additional arguments by EL 2.2. You can however override the ActionEvent
argument altogether by passing and specifying custom argument(s). The following examples are valid:
<h:commandXxx ... actionListener="#{bean.methodWithoutArguments()}" />
<h:commandXxx ... actionListener="#{bean.methodWithOneArgument(arg1)}" />
<h:commandXxx ... actionListener="#{bean.methodWithTwoArguments(arg1, arg2)}" />
public void methodWithoutArguments() {}
public void methodWithOneArgument(Object arg1) {}
public void methodWithTwoArguments(Object arg1, Object arg2) {}
Note the importance of the parentheses in the argumentless method expression. If they were absent, JSF would still expect a method with ActionEvent
argument.
If you're on EL 2.2+, then you can declare multiple action listener methods via <f:actionListener binding>
.
<h:commandXxx ... actionListener="#{bean.actionListener1}">
<f:actionListener binding="#{bean.actionListener2()}" />
<f:actionListener binding="#{bean.actionListener3()}" />
</h:commandXxx>
public void actionListener1(ActionEvent event) {}
public void actionListener2() {}
public void actionListener3() {}
Note the importance of the parentheses in the binding
attribute. If they were absent, EL would confusingly throw a javax.el.PropertyNotFoundException: Property 'actionListener1' not found on type com.example.Bean
, because the binding
attribute is by default interpreted as a value expression, not as a method expression. Adding EL 2.2+ style parentheses transparently turns a value expression into a method expression. See also a.o. Why am I able to bind <f:actionListener> to an arbitrary method if it's not supported by JSF?
Use action
if you want to execute a business action and if necessary handle navigation. The action
method can (thus, not must) return a String
which will be used as navigation case outcome (the target view). A return value of null
or void
will let it return to the same page and keep the current view scope alive. A return value of an empty string or the same view ID will also return to the same page, but recreate the view scope and thus destroy any currently active view scoped beans and, if applicable, recreate them.
The action
method can be any valid MethodExpression
, also the ones which uses EL 2.2 arguments such as below:
<h:commandXxx value="submit" action="#{bean.edit(item)}" />
With this method:
public void edit(Item item) {
// ...
}
Note that when your action method solely returns a string, then you can also just specify exactly that string in the action
attribute. Thus, this is totally clumsy:
<h:commandLink value="Go to next page" action="#{bean.goToNextpage}" />
With this senseless method returning a hardcoded string:
public String goToNextpage() {
return "nextpage";
}
Instead, just put that hardcoded string directly in the attribute:
<h:commandLink value="Go to next page" action="nextpage" />
Please note that this in turn indicates a bad design: navigating by POST. This is not user nor SEO friendly. This all is explained in When should I use h:outputLink instead of h:commandLink? and is supposed to be solved as
<h:link value="Go to next page" outcome="nextpage" />
See also How to navigate in JSF? How to make URL reflect current page (and not previous one).
Since JSF 2.x there's a third way, the <f:ajax listener>
.
<h:commandXxx ...>
<f:ajax listener="#{bean.ajaxListener}" />
</h:commandXxx>
The ajaxListener
method has by default the following signature:
import javax.faces.event.AjaxBehaviorEvent;
// ...
public void ajaxListener(AjaxBehaviorEvent event) {
// ...
}
In Mojarra, the AjaxBehaviorEvent
argument is optional, below works as good.
public void ajaxListener() {
// ...
}
But in MyFaces, it would throw a MethodNotFoundException
. Below works in both JSF implementations when you want to omit the argument.
<h:commandXxx ...>
<f:ajax execute="@form" listener="#{bean.ajaxListener()}" render="@form" />
</h:commandXxx>
Ajax listeners are not really useful on command components. They are more useful on input and select components <h:inputXxx>
/<h:selectXxx>
. In command components, just stick to action
and/or actionListener
for clarity and better self-documenting code. Moreover, like actionListener
, the f:ajax listener
does not support returning a navigation outcome.
<h:commandXxx ... action="#{bean.action}">
<f:ajax execute="@form" render="@form" />
</h:commandXxx>
For explanation on execute
and render
attributes, head to Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
The actionListener
s are always invoked before the action
in the same order as they are been declared in the view and attached to the component. The f:ajax listener
is always invoked before any action listener. So, the following example:
<h:commandButton value="submit" actionListener="#{bean.actionListener}" action="#{bean.action}">
<f:actionListener type="com.example.ActionListenerType" />
<f:actionListener binding="#{bean.actionListenerBinding()}" />
<f:setPropertyActionListener target="#{bean.property}" value="some" />
<f:ajax listener="#{bean.ajaxListener}" />
</h:commandButton>
Will invoke the methods in the following order:
Bean#ajaxListener()
Bean#actionListener()
ActionListenerType#processAction()
Bean#actionListenerBinding()
Bean#setProperty()
Bean#action()
The actionListener
supports a special exception: AbortProcessingException
. If this exception is thrown from an actionListener
method, then JSF will skip any remaining action listeners and the action method and proceed to render response directly. You won't see an error/exception page, JSF will however log it. This will also implicitly be done whenever any other exception is being thrown from an actionListener
. So, if you intend to block the page by an error page as result of a business exception, then you should definitely be performing the job in the action
method.
If the sole reason to use an actionListener
is to have a void
method returning to the same page, then that's a bad one. The action
methods can perfectly also return void
, on the contrary to what some IDEs let you believe via EL validation. Note that the PrimeFaces showcase examples are littered with this kind of actionListener
s over all place. This is indeed wrong. Don't use this as an excuse to also do that yourself.
In ajax requests, however, a special exception handler is needed. This is regardless of whether you use listener
attribute of <f:ajax>
or not. For explanation and an example, head to Exception handling in JSF ajax requests.
In bootstrap 4, if you want to over-ride when navbar-expand-*, expands and collapses and shows and hides the hamburger (navbar-toggler) you have to find that style/definition in bootstrap.css, and redefine it in your own customstyle.css (or directly in bootstrap.css if you are so inclined).
Eg. I wanted the navbar-expand-lg to collapses and shows the navbar-toggler at 950px. In bootstrap.css I find:
@media (max-width: 991.98px) {
.navbar-expand-lg > .container,
.navbar-expand-lg > .container-fluid {
padding-right: 0;
padding-left: 0;
}
}
And below that ...
@media (min-width:992px) {
... lots of styling ...
}
I copied both @media queries and stuck them in my style.css, then modified the size to fit my needs. I my case I wanted it to collapse at 950px. The @media queries must need to be different sizes (I'm guessing), so I set container max-width to 949.98px and used the 950px for the other @media query and so the following code was appended to my style.css. This was not easy to detangle from twisted solutions I found on Stackoverflow and elsewhere. Hope this helps.
@media (max-width: 949.98px) {
.navbar-expand-lg > .container,
.navbar-expand-lg > .container-fluid {
padding-right: 0;
padding-left: 0;
}
}
@media (min-width: 950px) {
.navbar-expand-lg {
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
}
.navbar-expand-lg .navbar-nav {
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
}
.navbar-expand-lg .navbar-nav .dropdown-menu {
position: absolute;
}
.navbar-expand-lg .navbar-nav .dropdown-menu-right {
right: 0;
left: auto;
}
.navbar-expand-lg .navbar-nav .nav-link {
padding-right: 0.5rem;
padding-left: 0.5rem;
}
.navbar-expand-lg > .container,
.navbar-expand-lg > .container-fluid {
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
}
.navbar-expand-lg .navbar-collapse {
display: -webkit-box !important;
display: -ms-flexbox !important;
display: flex !important;
-ms-flex-preferred-size: auto;
flex-basis: auto;
}
.navbar-expand-lg .navbar-toggler {
display: none;
}
.navbar-expand-lg .dropup .dropdown-menu {
top: auto;
bottom: 100%;
}
}
I've taken DLog
and ALog
from above, and added ULog
which raises a UIAlertView
message.
To summarize:
DLog
will output like NSLog
only when the DEBUG variable is set ALog
will always output like NSLog
ULog
will show the UIAlertView
only when the DEBUG variable is set
#ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif #define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #ifdef DEBUG # define ULog(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } #else # define ULog(...) #endif
This is what it looks like:
+1 Diederik
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
I think this may help you solve your issue.
Imagine you have a dictionary like this:
dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}
And you want to change values by this one:
dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}
You can use code bellow to change values of dic0
properly respected to dic0t01
without worrying yourself about indexes in dictionary:
for x, y in dic0.items():
dic0[x] = dic0to1[y]
Now you have:
>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}
Right click the shortcut and select properties. Make sure you are on the "Shortcut" Tab. Select the RUN drop down box and change it to Maximized.
This may assist in launching the program in full screen on the primary monitor.
Beside accepted answer, you need to hold a reference of listener and remove when you don't need it. Otherwise you will get a null pointer exception for your ScrollView and memory leak (mentioned in comments of accepted answer).
You can implement OnScrollChangedListener in your activity/fragment.
MyFragment : ViewTreeObserver.OnScrollChangedListener
Add it to scrollView when your view is ready.
scrollView.viewTreeObserver.addOnScrollChangedListener(this)
Remove listener when no longer need (ie. onPause())
scrollView.viewTreeObserver.removeOnScrollChangedListener(this)
Just use PrintJS
let printjs = document.createElement("script");
printjs.src = "https://printjs-4de6.kxcdn.com/print.min.js";
document.body.appendChild(printjs);
printjs.onload = function (){
printJS('id_of_div_you_want_to_print', 'html');
}
Ori Drori's comment is correct, you aren't doing this the "React Way". In React, you should ideally not be changing classes and event handlers using the DOM. Do it in the render() method of your React components; in this case that would be the sideNav and your Header. A rough example of how this would be done in your code is as follows.
HEADER
class Header extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div className="header">
<i className="border hide-on-small-and-down"></i>
<div className="container">
<a ref="btn" href="#" className="btn-menu show-on-small"
onClick=this.showNav><i></i></a>
<Menu className="menu hide-on-small-and-down"/>
<Sidenav ref="sideNav"/>
</div>
</div>
)
}
showNav() {
this.refs.sideNav.show();
}
}
SIDENAV
class SideNav extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
}
}
render() {
if (this.state.open) {
return (
<div className = "sideNav">
This is a sidenav
</div>
)
} else {
return null;
}
}
show() {
this.setState({
open: true
})
}
}
You can see here that we are not toggling classes but using the state of the components to render the SideNav. This way, or similar is the whole premise of using react. If you are using bootstrap, there is a library which integrates bootstrap elements with the react way of doing things, allowing you to use the same elements but set state on them instead of directly manipulating the DOM. It can be found here - https://react-bootstrap.github.io/
Hope this helps, and enjoy using React!
Replace disabled
with readonly="readonly"
. I think it is the same function.
<input type="text" class="details-dialog" readonly="readonly" style="color: ur color;">
or_()
function can be useful in case of unknown number of OR query components.
For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_()
function we must do something like this:
query = Book.query
if filter.title and filter.author:
query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
query = query.filter(Book.author.ilike(filter.author))
With or_()
function it can be rewritten to:
query = Book.query
not_null_filters = []
if filter.title:
not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
not_null_filters.append(Book.author.ilike(filter.author))
if len(not_null_filters) > 0:
query = query.filter(or_(*not_null_filters))
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Try clean project...
If it doesn't work... Then... Goto build.gradle in project section
Try downgrading the gradle version
From...
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
}
To...
dependencies {
classpath 'com.android.tools.build:gradle:1.2.0'
}
Then gradle.properties, add this
org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m
Sync it... Clean/Rebuild... It worked for me... So, I am sharing...
It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe
. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.
I ended up creating the ODBC connection directly under HKLM\Software\ODBC
. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.
After creating the entry (by hand), I fired up my windows service and everything was happy.
Go to Attributes Inspector(right top corner) In the Simulated Metrics, which has Size, Orientation, Status Bar, Top Bar, Bottom Bar properties. For SIZE, change Inferred --> Freeform.
<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>
Or if you have a content coming from the database;
<?php $data = strip_tags($get_row['description']); ?>
<?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}
// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}
scanner.useDelimiter(",");
This should work.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("/Users/pankaj/abc.csv"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
System.out.print(scanner.next()+"|");
}
scanner.close();
}
}
For CSV File:
a,b,c d,e
1,2,3 4,5
X,Y,Z A,B
Output is:
a|b|c d|e
1|2|3 4|5
X|Y|Z A|B|
Using 2.7:
from functools import partial
from random import randint
for roll in iter(partial(randint, 1, 8), 1):
print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'
you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!
Then change the "oops" print to a raise SystemExit
Try removing the text-alignment center and center the <h1>
or <div>
the text resides in.
h1 {
background-color:green;
margin: 0 auto;
width: 200px;
}
One major difference that no one has pointed out so far and that might be important to some people is that (at least on Windows) Atom doesn't fully support other keyboard layouts than US. There is an bug report on that with a few hundred posts that has been open for more than a year now (https://github.com/atom/atom-keymap/issues/35).
Might be relevant when choosing an editor.
Less efficient, but simpler-looking:
m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
print "He loves",m0.group(1)
elif m1:
print "Er liebt",m1.group(1)
elif m2:
print "Il aime",m2.group(1)
The problem with the Perl stuff is the implicit updating of some hidden variable. That's simply hard to achieve in Python because you need to have an assignment statement to actually update any variables.
The version with less repetition (and better efficiency) is this:
pats = [
("I love (\w+)", "He Loves {0}" ),
("Ich liebe (\w+)", "Er Liebe {0}" ),
("Je t'aime (\w+)", "Il aime {0}")
]
for p1, p3 in pats:
m= re.match( p1, statement )
if m:
print p3.format( m.group(1) )
break
A minor variation that some Perl folk prefer:
pats = {
"I love (\w+)" : "He Loves {0}",
"Ich liebe (\w+)" : "Er Liebe {0}",
"Je t'aime (\w+)" : "Il aime {0}",
}
for p1 in pats:
m= re.match( p1, statement )
if m:
print pats[p1].format( m.group(1) )
break
This is hardly worth mentioning except it does come up sometimes from Perl programmers.
I've slightly modified Peter's answer here to create a reusable, non-interactive shell script called git-split.sh
:
#!/bin/sh
if [[ $# -ne 2 ]] ; then
echo "Usage: git-split.sh original copy"
exit 0
fi
git mv "$1" "$2"
git commit -n -m "Split history $1 to $2 - rename file to target-name"
REV=`git rev-parse HEAD`
git reset --hard HEAD^
git mv "$1" temp
git commit -n -m "Split history $1 to $2 - rename source-file to temp"
git merge $REV
git commit -a -n -m "Split history $1 to $2 - resolve conflict and keep both files"
git mv temp "$1"
git commit -n -m "Split history $1 to $2 - restore name of source-file"
The reason you're receiving that error is that you're using the runtime build which doesn't support templates in HTML files as seen here vuejs.org
In essence what happens with vue loaded files is that their templates are compile time converted into render functions where as your base function was trying to compile from your html element.
In addition to @Boaz's and @vegemite4me's answers....
By implementing ImplicitNamingStrategy
you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder
during Hibernate's initialization:
metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());
It works for @UniqueConstraint
, but not for @Column(unique = true)
, which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).
There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586
Thanks.
dougg3 has this pretty much (I can't comment there). The main additional thing you need to know is the headers which don't conflict with each other but do provide the correct prototypes. The answer is
#include <stropts.h>
#include <asm/termios.h>
After that you can use dougg3's code, preferably with error checking round the ioctl() calls. You will probably need to put this in a separate .c file to the rest of your serial port code which uses the normal termios to set other parameters. Doing POSIX manipulations first, then this to set the custom speed, works fine on the built-in UART of the Raspberry Pi to get a 250k baud rate.
This happened to me right after upgrading Firefox to version 51. After clearing the cache
, the problem has gone.
The 'script' command under Unix should do the trick. Just run it at the start of your new console and you should be good.
fwrite()
is a smidgen faster and file_put_contents()
is just a wrapper around those three methods anyway, so you would lose the overhead.
Article
file_put_contents(file,data,mode,context):
The file_put_contents
writes a string to a file.
This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure.
fwrite(file,string,length):
The fwrite
writes to an open file.The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.This function returns the number of bytes written or FALSE on failure.
For anyone who likes Extension methods, this one does the trick for us.
using System.Text;
namespace System
{
public static class StringExtension
{
private static readonly ASCIIEncoding asciiEncoding = new ASCIIEncoding();
public static string ToAscii(this string dirty)
{
byte[] bytes = asciiEncoding.GetBytes(dirty);
string clean = asciiEncoding.GetString(bytes);
return clean;
}
}
}
(System namespace so it's available pretty much automatically for all of our strings.)
I just wanted to add to this discussion that I am just compiling on VS and GCC, and used to use include guards. I have now switched to #pragma once
, and the only reason for me is not performance or portability or standard as I don't really care what is standard as long as VS and GCC support it, and that is that:
#pragma once
reduces possibilities for bugs.
It is all too easy to copy and paste a header file to another header file, modify it to suit ones needs, and forget to change the name of the include guard. Once both are included, it takes you a while to track down the error, as the error messages aren't necessarily clear.
For me, with Homebrew 1.6.7
, the following worked:
brew upgrade git
I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.
See below link for more details.
i always use this cheap word for vertical spaces.
<p>Q1</p>
<br>
<p>Q2</p>
If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.
path = 'C:\\Users\\Username\\Path\\To\\File'
with open(path, 'w') as f:
f.write(data)
Edit:
Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.
import os
cur_path = os.path.dirname(__file__)
new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
f.write(data)
Edit 2: One quick note about __file__
, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.
Using this fiddle, you can play around with the width
of each div. I've tried in both Chrome and IE and I notice a difference in width between 33%
and 33.3%
. I also notice a very small difference between 33.3%
and 33.33%
. I don't notice any difference further than this.
The difference between 33.33%
and the theoretical 33.333...%
is a mere 0.00333...%
.
For arguments sake, say my screen width is 1960px
; a fairly high but common resolution. The difference between these two widths is still only 0.065333...px
.
So, further than two decimal places, the difference in precision is negligible.
One of the important things to take into account is the "zoom" level of your projection (for Google Maps in particular).
As Google explains it:
At zoom level 1, the map consists of 4 256x256 pixels tiles, resulting in a pixel space from 512x512. At zoom level 19, each x and y pixel on the map can be referenced using a value between 0 and 256 * 2^19
( See https://developers.google.com/maps/documentation/javascript/maptypes?hl=en#MapCoordinates)
To factor in the "zoom" value, I recommend the simple and effective deltaLonPerDeltaX and deltaLatPerDeltaY functions below. While x-pixels and longitudes are strictly proportional, this is not the case for y-pixels and latitudes, for which the formula requires the initial latitude.
// Adapted from : http://blog.cppse.nl/x-y-to-lat-lon-for-google-maps
window.geo = {
glOffset: Math.pow(2,28), //268435456,
glRadius: Math.pow(2,28) / Math.PI,
a: Math.pow(2,28),
b: 85445659.4471,
c: 0.017453292519943,
d: 0.0000006705522537,
e: Math.E, //2.7182818284590452353602875,
p: Math.PI / 180,
lonToX: function(lon) {
return Math.round(this.glOffset + this.glRadius * lon * this.p);
},
XtoLon: function(x) {
return -180 + this.d * x;
},
latToY: function(lat) {
return Math.round(this.glOffset - this.glRadius *
Math.log((1 + Math.sin(lat * this.p)) /
(1 - Math.sin(lat * this.p))) / 2);
},
YtoLat: function(y) {
return Math.asin(Math.pow(this.e,(2*this.a/this.b - 2*y/this.b)) /
(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1) -
1/(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1)
) / this.c;
},
deltaLonPerDeltaX: function(deltaX, zoom) {
// 2^(7+zoom) pixels <---> 180 degrees
return deltaX * 180 / Math.pow(2, 7+zoom);
},
deltaLatPerDeltaY: function(deltaY, zoom, startLat) {
// more complex because of the curvature, we calculte it by difference
var startY = this.latToY(startLat),
endY = startY + deltaY * Math.pow(2, 28-7-zoom),
endLat = this.YtoLat(endY);
return ( endLat - startLat ); // = deltaLat
}
}
Given a job (I assume you know its name) you can use:
EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'
as suggested in MSDN Job Help Procedure. It returns a lot of informations about the job (owner, server, status and so on).
As @Alok mentioned in the comments, you can do react-native eject
to generate the ios
and android
folders. But you will need an app.json
in your project first.
{"name": "example", "displayName": "Example"}
I am a synthesizer:). Here I combined the answers into one function:
#' keep rows that have a certain number (range) of NAs anywhere/somewhere and delete others
#' @param df a data frame
#' @param col restrict to the columns where you would like to search for NA; eg, 3, c(3), 2:5, "place", c("place","age")
#' \cr default is NULL, search for all columns
#' @param n integer or vector, 0, c(3,5), number/range of NAs allowed.
#' \cr If a number, the exact number of NAs kept
#' \cr Range includes both ends 3<=n<=5
#' \cr Range could be -Inf, Inf
#' @return returns a new df with rows that have NA(s) removed
#' @export
ez.na.keep = function(df, col=NULL, n=0){
if (!is.null(col)) {
# R converts a single row/col to a vector if the parameter col has only one col
# see https://radfordneal.wordpress.com/2008/08/20/design-flaws-in-r-2-%E2%80%94-dropped-dimensions/#comments
df.temp = df[,col,drop=FALSE]
} else {
df.temp = df
}
if (length(n)==1){
if (n==0) {
# simply call complete.cases which might be faster
result = df[complete.cases(df.temp),]
} else {
# credit: http://stackoverflow.com/a/30461945/2292993
log <- apply(df.temp, 2, is.na)
logindex <- apply(log, 1, function(x) sum(x) == n)
result = df[logindex, ]
}
}
if (length(n)==2){
min = n[1]; max = n[2]
log <- apply(df.temp, 2, is.na)
logindex <- apply(log, 1, function(x) {sum(x) >= min && sum(x) <= max})
result = df[logindex, ]
}
return(result)
}
I use expr. It returns a non-zero if you try to add a zero to a non-numeric value:
if expr -- "$number" + 0 > /dev/null 2>&1
then
echo "$number is a number"
else
echo "$number isn't a number"
fi
It might be possible to use bc if you need non-integers, but I don't believe bc
has quite the same behavior. Adding zero to a non-number gets you zero and it returns a value of zero too. Maybe you can combine bc
and expr
. Use bc
to add zero to $number
. If the answer is 0
, then try expr
to verify that $number
isn't zero.
If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.
In Bundle ID Suffix you should write full name of bundle ID.
Example:
Bundle ID suffix = thebestapp (NOT CORRECT!!!!)
Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)
The reason for this is explained in the Developer Portal:
The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g.
ABCDE12345
), and an App ID Suffix (a Bundle ID search string, e.g.com.mycompany.appname
). [emphasis added]
So in this case the suffix is the full string com.awesomeapps.thebestapp
.
Swift 3 or Swift 4:
UIApplication.shared.statusBarFrame.height
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
obj.__class__.__name__
will get you any objects name, so you can do this:
class Clazz():
def getName(self):
return self.__class__.__name__
Usage:
>>> c = Clazz()
>>> c.getName()
'Clazz'
CREATE OR REPLACE PACKAGE BODY TEST AS
FUNCTION GET_UPS(
TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
STARTING_DATE_IN DATE,
ENDING_DATE_IN DATE
)RETURN MEASURE_TABLE IS
T MEASURE_TABLE;
BEGIN
**SELECT MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
PERIOD,VALUE ) BULK COLLECT INTO T
FROM ...**
;
RETURN T;
END GET_UPS;
END TEST;
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
if you are using .bind(this), try this:
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
$(this.pagination).find("a").on('click', function(evt) {
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
this.goTo(index);
}.bind(this))
you can also mention the path at runtime using -D
properties as below
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks
In my apache spark application, I used to provide the path of certs and keystore using --conf
option and extraJavaoptions
in spark-submit as below
--conf 'spark.driver.extraJavaOptions=
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks'
The following is a terrible approach that would get you fired at any job...
It depends on you getting a Stack Overflow Exception [or whatever Java calls it]... And it would only work for positive numbers that don't deviate from 0 like crazy.
Negative numbers are fine, since you would overflow to positive, and then get a stack overflow exception eventually [which would return false, or "yes, it is negative"]
Boolean isPositive<T>(T a)
{
if(a == 0) return true;
else
{
try
{
return isPositive(a-1);
}catch(StackOverflowException e)
{
return false; //It went way down there and eventually went kaboom
}
}
}
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress;
import java.net.UnknownHostException;
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
Just right click on the ConstrainLayout and select the "convert view" and then "RelativeLayout":
In docker container phpmyadmin/phpmyadmin no php.ini file. But there are two files : php.ini-debug and php.ini-production
To solve the problem, simply rename one of the files to php.ini and restart docker container.
This is old thread, but I have find new answer on https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php
The problem with previous solution is that you need to have special div around video code, which is not suitable for most uses. So here is JavaScript solution without special div.
// Find all YouTube videos - RESIZE YOUTUBE VIDEOS!!!
var $allVideos = $("iframe[src^='https://www.youtube.com']"),
// The element that is fluid width
$fluidEl = $("body");
// Figure out and save aspect ratio for each video
$allVideos.each(function() {
$(this)
.data('aspectRatio', this.height / this.width)
// and remove the hard coded width/height
.removeAttr('height')
.removeAttr('width');
});
// When the window is resized
$(window).resize(function() {
var newWidth = $fluidEl.width();
// Resize all videos according to their own aspect ratio
$allVideos.each(function() {
var $el = $(this);
$el
.width(newWidth)
.height(newWidth * $el.data('aspectRatio'));
});
// Kick off one resize to fix all videos on page load
}).resize();
// END RESIZE VIDEOS