I'd look around to find some (3rd party?) components that do what you want. I've had to create custom Swing components for an agenda view where you can book multiple resources, as well as an Excel-like grid that works well with keyboard navigation and so on. I had a terrible time getting them to work nicely because I needed to delve into many of Swing's many intricacies whenever I came upon a problem. Mouse and focus behaviour and a lot of other things can be very difficult to get right, especially for a casual Swing user. I would hope that JavaFX is a bit more future-orientated and smooth out of the box.
#use a regular expression to parse the column count
#https://docs.python.org/3/library/re.html
buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
pat=re.search(r"total\s{1}[0-9]\s{1}column",s)
print(s)
phrase=pat.group(0)
value=re.findall(r'[0-9]+',phrase)[0]
print(int(value))
If you've scrolled far enough to reach this answer, I wrote a library for equal spacing which supports Vertical/Horizontal, LTR/RTL, LinearLayout/GridLayout manager and Edge inclusion. Its basically a single file, so you can copy paste that file into your code.
I tried to support StaggeredGridLayout
but span index returned by this layout is not reliable. I would be glad to hear any suggestion for that.
Use BigInt datatype with its implicit operations. The plus point for it is it will not give answers in exponential representation. It will give full length result
Here is an example of addition
BigInteger big1 = new BigInteger("1234567856656567242177779");
BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
BigInteger bigSum = big1.add(big2);
System.out.println(bigSum );
The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.
In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)
EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!
put .; at classpath value in beginning..it will start working...it happens because it searches the class file in classpath which is mentioned in path variable.
Select * from table where name like search_criteria
if you are expecting the user to add their own wildcards...
nobody wants to go to the clutter of using a class, try this:
<asp:button Style="margin:0px" runat="server" />
Intellisense won't suggest it but it will get the job done without throwing errors, warnings, or messages. Don't forget the capital S in Style
Installing Google play services (latest version) + including
android {
defaultConfig {
multiDexEnabled true
}
}
in build.gradle solved the issue for me, make sure to clean and rebuild project!
On any other element, I would use the scrollHeight
of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.
Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the offsetHeight
:
function setHeight() {
parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}
And attach that to run with the iframe-body's onLoad
event.
You can now use useRef
from react hook API
https://reactjs.org/docs/hooks-reference.html#useref
let myRef = useRef()
<div ref={myRef}>My Component</div>
window.scrollTo({ behavior: 'smooth', top: myRef.current.offsetTop })
ACID is a set of properties that you would like to apply when modifying a database.
A transaction is a set of related changes which is used to achieve some of the ACID properties. Transactions are tools to achieve the ACID properties.
Atomicity means that you can guarantee that all of a transaction happens, or none of it does; you can do complex operations as one single unit, all or nothing, and a crash, power failure, error, or anything else won't allow you to be in a state in which only some of the related changes have happened.
Consistency means that you guarantee that your data will be consistent; none of the constraints you have on related data will ever be violated.
Isolation means that one transaction cannot read data from another transaction that is not yet completed. If two transactions are executing concurrently, each one will see the world as if they were executing sequentially, and if one needs to read data that is written by another, it will have to wait until the other is finished.
Durability means that once a transaction is complete, it is guaranteed that all of the changes have been recorded to a durable medium (such as a hard disk), and the fact that the transaction has been completed is likewise recorded.
So, transactions are a mechanism for guaranteeing these properties; they are a way of grouping related actions together such that as a whole, a group of operations can be atomic, produce consistent results, be isolated from other operations, and be durably recorded.
<div class="leads-search-table">
<div class="row col-md-6 col-md-offset-2 custyle">
<table class="table custab bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Parent ID</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>News</td>
<td>News Cate</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
<tr>
<td>2</td>
<td>Products</td>
<td>Main Products</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
<tr>
<td>3</td>
<td>Blogs</td>
<td>Parent Blogs</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
</table>
</div>
</div>
Css
.custab{
border: 1px solid #ccc;
margin: 5% 0;
transition: 0.5s;
background-color: #fff;
-webkit-border-radius:4px;
border-radius: 4px;
border-collapse: separate;
}
It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies
I think I found convenient approach to handle StaleElementReferenceException. Usually you have to write wrappers for every WebElement method to retry actions, which is frustrating and wastes lots of time.
Adding this code
webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")));
if ((Boolean) ((JavascriptExecutor) webDriver).executeScript("return window.jQuery != undefined")) {
webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return jQuery.active == 0")));
}
before every WebElement action can increase stability of your tests but you still can get StaleElementReferenceException from time to time.
So this is what I came up with (using AspectJ):
package path.to.your.aspects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.pagefactory.DefaultElementLocator;
import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@Aspect
public class WebElementAspect {
private static final Logger LOG = LogManager.getLogger(WebElementAspect.class);
/**
* Get your WebDriver instance from some kind of manager
*/
private WebDriver webDriver = DriverManager.getWebDriver();
private WebDriverWait webDriverWait = new WebDriverWait(webDriver, 10);
/**
* This will intercept execution of all methods from WebElement interface
*/
@Pointcut("execution(* org.openqa.selenium.WebElement.*(..))")
public void webElementMethods() {}
/**
* @Around annotation means that you can insert additional logic
* before and after execution of the method
*/
@Around("webElementMethods()")
public Object webElementHandler(ProceedingJoinPoint joinPoint) throws Throwable {
/**
* Waiting until JavaScript and jQuery complete their stuff
*/
waitUntilPageIsLoaded();
/**
* Getting WebElement instance, method, arguments
*/
WebElement webElement = (WebElement) joinPoint.getThis();
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
Object[] args = joinPoint.getArgs();
/**
* Do some logging if you feel like it
*/
String methodName = method.getName();
if (methodName.contains("click")) {
LOG.info("Clicking on " + getBy(webElement));
} else if (methodName.contains("select")) {
LOG.info("Selecting from " + getBy(webElement));
} else if (methodName.contains("sendKeys")) {
LOG.info("Entering " + args[0].toString() + " into " + getBy(webElement));
}
try {
/**
* Executing WebElement method
*/
return joinPoint.proceed();
} catch (StaleElementReferenceException ex) {
LOG.debug("Intercepted StaleElementReferenceException");
/**
* Refreshing WebElement
* You can use implementation from this blog
* http://www.sahajamit.com/post/mystery-of-stale-element-reference-exception/
* but remove staleness check in the beginning (if(!isElementStale(elem))), because we already caught exception
* and it will result in an endless loop
*/
webElement = StaleElementUtil.refreshElement(webElement);
/**
* Executing method once again on the refreshed WebElement and returning result
*/
return method.invoke(webElement, args);
}
}
private void waitUntilPageIsLoaded() {
webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")));
if ((Boolean) ((JavascriptExecutor) webDriver).executeScript("return window.jQuery != undefined")) {
webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return jQuery.active == 0")));
}
}
private static String getBy(WebElement webElement) {
try {
if (webElement instanceof RemoteWebElement) {
try {
Field foundBy = webElement.getClass().getDeclaredField("foundBy");
foundBy.setAccessible(true);
return (String) foundBy.get(webElement);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} else {
LocatingElementHandler handler = (LocatingElementHandler) Proxy.getInvocationHandler(webElement);
Field locatorField = handler.getClass().getDeclaredField("locator");
locatorField.setAccessible(true);
DefaultElementLocator locator = (DefaultElementLocator) locatorField.get(handler);
Field byField = locator.getClass().getDeclaredField("by");
byField.setAccessible(true);
return byField.get(locator).toString();
}
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
}
To enable this aspect create file
src\main\resources\META-INF\aop-ajc.xml
and write
<aspectj>
<aspects>
<aspect name="path.to.your.aspects.WebElementAspect"/>
</aspects>
</aspectj>
Add this to your pom.xml
<properties>
<aspectj.version>1.9.1</aspectj.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
</build>
And thats all. Hope it helps.
I was looking to make a checkbox that was just a little bit larger and looked at the source code for 37Signals Basecamp to find the following solution-
You can change the font size to make the checkbox slightly larger:
font-size: x-large;
Then, you can align the checkbox properly by doing:
vertical-align: top;
margin-top: 3px; /* change to center it */
You can use .attr() as a part of however you plan to toggle it:
$("button").attr("aria-expanded","true");
After 8 years the situation is changed a bit.
I'm unable to open a new session of Google Chrome without other parameters and allow 'file:' schema.
On macOS I do:
open -n -a "Google Chrome" --args \
--disable-web-security \ # This disable all CORS and other security checks
--user-data-dir=$HOME/fakeChromeDir # This let you to force open a new Google Chrome session
Without this arguments I'm unable to test the XSL stylesheet in local.
The following is taken from Mozilla Firefox's internal html.css:
sup {
vertical-align: super;
font-size: smaller;
line-height: normal;
}
So, in your case it would be something, like:
.superscript {
vertical-align: super;
font-size: smaller;
line-height: normal;
}
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
You can also use JSON.generate
:
require 'json'
JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"
Or its alias, JSON.unparse
:
require 'json'
JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"
You do not exactly define what the dictionaries should look like, but most likely you are referring to QuerySet.values()
. From the official django documentation:
Returns a
ValuesQuerySet
— aQuerySet
subclass that returns dictionaries when used as an iterable, rather than model-instance objects.Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.
You also use this below to expand the memory
export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"
Xmx
specifies the maximum memory allocation pool for a Java virtual machine (JVM)
Xms
specifies the initial memory allocation pool.
Xss
setting memory size of thread stack
XX:MaxPermSize
: the maximum permanent generation size
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
First create an xpath selector function.
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
To use the xpath selector with jquery, you can do like this:
$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');
Hope this can help.
I also faced the same issue while running JUnit test. I resolved this by putting the annotation @Test just above the main test function.
The var
keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var
keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var
keyword has a type. For instance, you'll find that the following code outputs "String".
var myString = "";
Console.Write(myString.GetType().Name);
Furthermore, the code above is equivalent to:
String myString = "";
Console.Write(myString.GetType().Name);
The var
keyword is simply C#'s way of saying "I can figure out the type for myString
from the context, so don't worry about specifying the type."
var myVariable = (MyType)null
or MyType myVariable = null
should work because you are giving the C# compiler context to figure out what type myVariable
should will be.
For more information:
If you're using zsh, you can use multiple redirections, so you don't even need tee
:
./cmd 1>&1 2>&2 1>out_file 2>err_file
Here you're simply redirecting each stream to itself and the target file.
Full example
% (echo "out"; echo "err">/dev/stderr) 1>&1 2>&2 1>/tmp/out_file 2>/tmp/err_file
out
err
% cat /tmp/out_file
out
% cat /tmp/err_file
err
Note that this requires the MULTIOS
option to be set (which is the default).
MULTIOS
Perform implicit
tee
s orcat
s when multiple redirections are attempted (see Redirection).
The only way I think then to get the functionality you want would be to do something like
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("TestEverything");
//$JUnit-BEGIN$
suite.addTestSuite(TestOne.class);
suite.addTestSuite(TestTwo.class);
suite.addTestSuite(TestThree.class);
//$JUnit-END$
}
public static void main(String[] args)
{
AllTests test = new AllTests();
Test testCase = test.suite();
TestResult result = new TestResult();
setUp();
testCase.run(result);
tearDown();
}
public void setUp() {}
public void tearDown() {}
}
I use something like this in eclipse, so I'm not sure how portable it is outside of that environment
If you have a hash, you can add items to it by referencing them by key:
hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'
Here, like [ ]
creates an empty array, { }
will create a empty hash.
Arrays have zero or more elements in a specific order, where elements may be duplicated. Hashes have zero or more elements organized by key, where keys may not be duplicated but the values stored in those positions can be.
Hashes in Ruby are very flexible and can have keys of nearly any type you can throw at it. This makes it different from the dictionary structures you find in other languages.
It's important to keep in mind that the specific nature of a key of a hash often matters:
hash = { :a => 'a' }
# Fetch with Symbol :a finds the right value
hash[:a]
# => 'a'
# Fetch with the String 'a' finds nothing
hash['a']
# => nil
# Assignment with the key :b adds a new entry
hash[:b] = 'Bee'
# This is then available immediately
hash[:b]
# => "Bee"
# The hash now contains both keys
hash
# => { :a => 'a', :b => 'Bee' }
Ruby on Rails confuses this somewhat by providing HashWithIndifferentAccess where it will convert freely between Symbol and String methods of addressing.
You can also index on nearly anything, including classes, numbers, or other Hashes.
hash = { Object => true, Hash => false }
hash[Object]
# => true
hash[Hash]
# => false
hash[Array]
# => nil
Hashes can be converted to Arrays and vice-versa:
# Like many things, Hash supports .to_a
{ :a => 'a' }.to_a
# => [[:a, "a"]]
# Hash also has a handy Hash[] method to create new hashes from arrays
Hash[[[:a, "a"]]]
# => {:a=>"a"}
When it comes to "inserting" things into a Hash you may do it one at a time, or use the merge
method to combine hashes:
{ :a => 'a' }.merge(:b => 'b')
# {:a=>'a',:b=>'b'}
Note that this does not alter the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the merge!
method:
hash = { :a => 'a' }
# Returns the result of hash combined with a new hash, but does not alter
# the original hash.
hash.merge(:b => 'b')
# => {:a=>'a',:b=>'b'}
# Nothing has been altered in the original
hash
# => {:a=>'a'}
# Combine the two hashes and store the result in the original
hash.merge!(:b => 'b')
# => {:a=>'a',:b=>'b'}
# Hash has now been altered
hash
# => {:a=>'a',:b=>'b'}
Like many methods on String and Array, the !
indicates that it is an in-place operation.
For c++ you should use g++.
It's the same compiler (e.g. the GNU compiler collection). GCC or G++ just choose a different front-end with different default options.
In a nutshell: if you use g++ the frontend will tell the linker that you may want to link with the C++ standard libraries. The gcc frontend won't do that (also it could link with them if you pass the right command line options).
I found out that inflating the header view as:
inflater.inflate(R.layout.listheader, container, false);
being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.
So, my problem was solved solved by inflating the header view passing the list as container:
ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);
then
list.addHeaderView(headerView, null, false);
Kinda late answer but I hope this can help someone
You can do this by calling the constructor each time with is slightly better
var tupleList = new List<Tuple<int, string>>
{
new Tuple<int, string>(1, "cow" ),
new Tuple<int, string>( 5, "chickens" ),
new Tuple<int, string>( 1, "airplane" )
};
I had this issue and realized it was because I was calling setContentView(int id)
twice in my Activity
's onCreate
How about this solution:
$type = gettype($your_iteratable);
$types = array(
'array',
'object'
);
if (in_array($type, $types)) {
// foreach code comes here
}
i have same issue and resolved by
data: "Id1=" + id1 + "&Id2=" + id2
You can use the str.split method.
>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']
If you want to convert it to a tuple, just
>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')
If you are looking to append to a list, try this:
>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']
from time import clock
from random import sample
n = 500
myList = sample(xrange(10000),n)
#print myList
A,B,C,D = [],[],[],[]
for i in xrange(100):
t0 = clock()
ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
A.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
B.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
C.append(clock()-t0)
t0 = clock()
ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
D.append(clock()-t0)
print '\n'.join(('t1 = '+str(min(A))+' '+'{:.1%}.'.format(min(A)/min(D)),
't2 = '+str(min(B))+' '+'{:.1%}.'.format(min(B)/min(D)),
't3 = '+str(min(C))+' '+'{:.1%}.'.format(min(C)/min(D)),
't4 = '+str(min(D))+' '+'{:.1%}.'.format(min(D)/min(D))))
For n=500:
150.8%.
142.7%.
110.8%.
100.0%.
For n=5000:
153.5%.
176.2%.
109.7%.
100.0%.
Oh, I see now: only the solution 3 with map() fits with the title of the question.
The problem is here:
answer = newList.sort()
sort
does not return the sorted list; rather, it sorts the list in place.
Use:
answer = sorted(newList)
var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ...
I find this solution easy to understand.
It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:
class Program
{
protected static Dictionary<string, string> _tags = new Dictionary<string,string>();
static void Main(string[] args)
{
string strValue;
_tags.Add("101", "C#");
_tags.Add("102", "ASP.NET");
if (_tags.ContainsKey("101"))
{
strValue = _tags["101"];
Console.WriteLine(strValue);
}
if (_tags.TryGetValue("101", out strValue))
{
Console.WriteLine(strValue);
}
}
}
What I do in these cases is:
In the server, move the cursor back to the last known good commit:
git push -f origin <last_known_good_commit>:<branch_name>
Locally, do the same:
git reset --hard <last_known_good_commit>
# ^^^^^^
# optional
See a full example on a branch my_new_branch
that I created for this purpose:
$ git branch
my_new_branch
This is the recent history after adding some stuff to myfile.py
:
$ git log
commit 80143bcaaca77963a47c211a9cbe664d5448d546
Author: me
Date: Wed Mar 23 12:48:03 2016 +0100
Adding new stuff in myfile.py
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date: Tue Mar 18 12:46:59 2016 +0100
Initial commit
I want to get rid of the last commit, which was already pushed, so I run:
$ git push -f origin b4zad078237fa48746a4feb6517fa409f6bf238e:my_new_branch
Total 0 (delta 0), reused 0 (delta 0)
To [email protected]:me/myrepo.git
+ 80143bc...b4zad07 b4zad078237fa48746a4feb6517fa409f6bf238e -> my_new_branch (forced update)
Nice! Now I see the file that was changed on that commit (myfile.py
) shows in "not staged for commit":
$ git status
On branch my_new_branch
Your branch is up-to-date with 'origin/my_new_branch'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: myfile.py
no changes added to commit (use "git add" and/or "git commit -a")
Since I don't want these changes, I just move the cursor back locally as well:
$ git reset --hard b4zad078237fa48746a4feb6517fa409f6bf238e
HEAD is now at b4zad07 Initial commit
So now HEAD is in the previous commit, both in local and remote:
$ git log
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date: Tue Mar 18 12:46:59 2016 +0100
Initial commit
Use prop() instead of attr() to set the value of checked
. Also use :checkbox
in find method instead of input
and be specific.
$("#news_list tr").click(function() {
var ele = $(this).find('input');
if(ele.is(':checked')){
ele.prop('checked', false);
$(this).removeClass('admin_checked');
}else{
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Use prop instead of attr for properties like checked
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method
JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
add(mycombo); //Adds it to the jframe.
mycombo.addItem("Hello Nepal"); //Adds data to the JComboBox.
String s=String.valueOf(mycombo.getSelectedItem()); //Assigns "Hello Nepal" to s.
System.out.println(s); //Prints "Hello Nepal".
yes block are the most used functionality , so in order to avoid the retain cycle we should avoid using the strong variable,including self inside the block, inspite use the _weak or weakself.
I found next workaround. You may escape the redirection after processing POST
request by manipulating history
object.
So you have the HTML form:
<form method=POST action='/process.php'>
<input type=submit value=OK>
</form>
When you process this form on your server you instead of redirecting user to /the/result/page
by setting up the Location
header like this:
$cat process.php
<?php
process POST data here
...
header('Location: /the/result/page');
exit();
?>
After processing POST
ed data you render small <script>
and the result /the/result/page
<?php
process POST data here
render the <script> // see below
render `/the/result/page` // OK
?>
The <script>
you should render:
<script>
window.onload = function() {
history.replaceState("", "", "/the/result/page");
}
</script>
The result is:
as you can see the form data is POST
ed to process.php
script.
This script process POST
ed data and rendering /the/result/page
at once with:
POST
data when you refresh page (F5) POST
when you navigate to previous/next page through the browser historyUPD
As another solution I ask feature request the Mozilla FireFox team to allow users to setup NextPage
header which will work like Location
header and make post/redirect/get
pattern obsolete.
In short. When server process form POST
data successfully it:
NextPage
header instead of Location
POST
form data as it would render for GET
request in post/redirect/get
patternThe browser in turn when see the NextPage
header:
window.location
with NextPage
valueGET
request to NextPage
instead of rePOST
form dataI think this would be excelent if implemented, would not? =)
dev.Dockerfile
, test.Dockerfile
, build.Dockerfile
etc.
On VS Code I use <purpose>.Dockerfile
and it gets recognized correctly.
The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.
Take a look at the URL
object:
var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol; // "http:"
url.hostname; // "aaa.bbb.ccc.com"
url.pathname; // "/asdf/asdf/sadf.aspx"
url.search; // "?blah"
try this:
ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";
EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):
The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue
So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:
comboBox1.DisplayMember = "Text";
comboBox1.ValueMember = "Value";
List<ComboboxItem> list = new List<ComboboxItem>();
ComboboxItem item = new ComboboxItem();
item.Text = "choose a server...";
item.Value = "-1";
list.Add(item);
item = new ComboboxItem();
item.Text = "S1";
item.Value = "1";
list.Add(item);
item = new ComboboxItem();
item.Text = "S2";
item.Value = "2";
list.Add(item);
cbx.DataSource = list; // bind combobox to a datasource
or use SelectedItem property:
if (cbx.SelectedItem != null)
Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());
I hope the code below will help you.
String s="Welcome to Java Programming";
char arr[]=s.toCharArray();
for(int i=0;i<arr.length;i++){
System.out.println("Data at ["+i+"]="+arr[i]);
}
It's working and the output is:
Data at [0]=W
Data at [1]=e
Data at [2]=l
Data at [3]=c
Data at [4]=o
Data at [5]=m
Data at [6]=e
Data at [7]=
Data at [8]=t
Data at [9]=o
Data at [10]=
Data at [11]=J
Data at [12]=a
Data at [13]=v
Data at [14]=a
Data at [15]=
Data at [16]=P
Data at [17]=r
Data at [18]=o
Data at [19]=g
Data at [20]=r
Data at [21]=a
Data at [22]=m
Data at [23]=m
Data at [24]=i
Data at [25]=n
Data at [26]=g
Caveat: you can't prevent users from pirating, but only make it easier for honest users to do the right thing.
Assuming you don't want to do a special build for each user, then:
But, I repeat: this won't prevent piracy
I have recently read that this approach is not cryptographically very sound. But this solution is already weak (as the software itself has to include the secret key somewhere), so I don't think this discovery invalidates the solution as far as it goes.
Just thought I really ought to mention this, though; if you're planning to derive something else from this, beware.
If you put blah="/usr/bin/blah"
in your ~/.bashrc
then you can use $blah
in your login shell as a substitute for typing /usr/bin/blah
Note this solution will not let the user wait more: the delay of the splash screen depends on the start up time of the application.
When you open any android app you will get by default a some what black screen with the title and icon of the app on top, you can change that by using a style/theme.
First, create a style.xml in values folder and add a style to it.
<style name="splashScreenTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
</style>
Instead of using @android:style/Theme.DeviceDefault.Light.NoActionBar
you can use any other theme as a parent.
Second, in your app Manifest.xml add android:theme="@style/splashScreenTheme"
to your main activity.
<activity
android:name="MainActivity"
android:label="@string/app_name"
android:theme="@style/splashScreenTheme" >
Third, Update your theme in your onCreate() launch activity.
protected void onCreate(Bundle savedInstanceState) {
// Make sure this is before calling super.onCreate
setTheme(R.style.mainAppTheme);
super.onCreate(savedInstanceState);
}
UPDATE Check out this post.
Thanks to @mat1h and @adelriosantiago
I was having similar problem recently with version 2.6.6.
@JsonInclude(JsonInclude.Include.NON_NULL)
Using above annotation either on filed or class level was not working as expected. The POJO was mutable where I was applying the annotation. When I changed the behaviour of the POJO to be immutable the annotation worked its magic.
I am not sure if its down to new version or previous versions of this lib had similar behaviour but for 2.6.6 certainly you need to have Immutable POJO for the annotation to work.
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Above option mentioned in various answers of setting serialisation inclusion in ObjectMapper directly at global level works as well but, I prefer controlling it at class or filed level.
So if you wanted all the null fields to be ignored while JSON serialisation then use the annotation at class level but if you want only few fields to ignored in a class then use it over those specific fields. This way its more readable & easy for maintenance if you wanted to change behaviour for specific response.
Here is a tutorial which does exactly what you are looking for: the MFMessageComposeViewController
.
http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/
Essentially:
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = @"SMS message here";
controller.recipients = [NSArray arrayWithObjects:@"1(234)567-8910", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
And a link to the docs.
https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller
Yesterday, I got the same error: Failed building wheel for hddfancontrol
when I ran pip3 install hddfancontrol
. The result was Failed to build hddfancontrol
. The cause was error: invalid command 'bdist_wheel'
and Running setup.py bdist_wheel for hddfancontrol ... error
. The error was fixed by running the following:
pip3 install wheel
(From here.)
Alternatively, the "wheel" can be downloaded directly from here. When downloaded, it can be installed by running the following:
pip3 install "/the/file_path/to/wheel-0.32.3-py2.py3-none-any.whl"
libpostal: an open-source library to parse addresses, training with data from OpenStreetMap, OpenAddresses and OpenCage.
https://github.com/openvenues/libpostal (more info about it)
Other tools/services:
http://www.gisgraphy.com Free, open source, and ready to use geocoder and geolocalisation webservices, integrating OpenStreetMap, GeoNames and Quattroshapes.
https://github.com/kodapan/osm-common Library for accessing OpenStreetMap services, parsing and processing data.
var element = document.getElementById("main");
var values = element.childNodes[1].innerText;
alert('the value is:' + values);
To further refine it and retrieve the value Alec for example, use another .childNodes[1]
var element = document.getElementById("main");
var values = element.childNodes[1].childNodes[1].innerText;
alert('the value is:' + values);
Historically (we're talking the 1980s and early 1990s), there were some architectures in which this was true. The root issue is that integer comparison is inherently implemented via integer subtractions. This gives rise to the following cases.
Comparison Subtraction
---------- -----------
A < B --> A - B < 0
A = B --> A - B = 0
A > B --> A - B > 0
Now, when A < B
the subtraction has to borrow a high-bit for the subtraction to be correct, just like you carry and borrow when adding and subtracting by hand. This "borrowed" bit was usually referred to as the carry bit and would be testable by a branch instruction. A second bit called the zero bit would be set if the subtraction were identically zero which implied equality.
There were usually at least two conditional branch instructions, one to branch on the carry bit and one on the zero bit.
Now, to get at the heart of the matter, let's expand the previous table to include the carry and zero bit results.
Comparison Subtraction Carry Bit Zero Bit
---------- ----------- --------- --------
A < B --> A - B < 0 0 0
A = B --> A - B = 0 1 1
A > B --> A - B > 0 1 0
So, implementing a branch for A < B
can be done in one instruction, because the carry bit is clear only in this case, , that is,
;; Implementation of "if (A < B) goto address;"
cmp A, B ;; compare A to B
bcz address ;; Branch if Carry is Zero to the new address
But, if we want to do a less-than-or-equal comparison, we need to do an additional check of the zero flag to catch the case of equality.
;; Implementation of "if (A <= B) goto address;"
cmp A, B ;; compare A to B
bcz address ;; branch if A < B
bzs address ;; also, Branch if the Zero bit is Set
So, on some machines, using a "less than" comparison might save one machine instruction. This was relevant in the era of sub-megahertz processor speed and 1:1 CPU-to-memory speed ratios, but it is almost totally irrelevant today.
This is how I did it,
Menu Tools → Options on the Environment → Keyboard window
One can alter the default shortcuts following the below steps
<TextView
android:id="@+id/layone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous Page"
android:textColor="#000000"
android:textSize="16dp"
android:paddingLeft="10dp"
android:layout_marginTop="10dp"
android:visibility="gone" />
layone is a TextView.
You got your id wrong.
LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here
layone.setVisibility(View.VISIBLE);
should do the job.
or change like this to show the TextView:
TextView layone= (TextView) view.findViewById(R.id.layone);
layone.setVisibility(View.VISIBLE);
Unfortunately, Date
object in javascript returns information about months only in numeric format. The faster thing you can do is to create an array of months (they are not supposed to change frequently!) and create a function which returns the name based on the number.
Something like this:
function getMonthNameByMonthNumber(mm) {
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return months[mm];
}
Your code therefore becomes:
var prnDt = "Printed on Thursday, " + now.getDate() + " " + getMonthNameByMonthNumber(now.getMonth) + " "+ now.getFullYear() + " at " + h + ":" + m + ":" s;
You need to treat a table valued udf like a table, eg JOIN it
select Emp_Id
from Employee E JOIN dbo.Splitfn(@Id,',') CSV ON E.Emp_Id = CSV.items
Since bootstrap 4 use div class="form-row" in combination with div class="form-group col-X". X is the width you need. You will get nice inline columns. See fiddle.
<form class="form-horizontal" name="FORMNAME" method="post" action="ACTION" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-sm-2" for="naam">Naam: *</label>
<div class="col-sm-10">
<input type="text" require class="form-control" id="naam" name="Naam" placeholder="Uw naam" value="{--NAAM--}" >
<div id="naamx" class="form-error form-hidden">Wat is uw naam?</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-5">
<label class="control-label col-sm-4" for="telefoon">Telefoon: *</label>
<div class="col-sm-12">
<input type="tel" require class="form-control" id="telefoon" name="Telefoon" placeholder="Telefoon nummer" value="{--TELEFOON--}" >
<div id="telefoonx" class="form-error form-hidden">Wat is uw telefoonnummer?</div>
</div>
</div>
<div class="form-group col-5">
<label class="control-label col-sm-4" for="email">E-mail: </label>
<div class="col-sm-12">
<input type="email" require class="form-control" id="email" name="E-mail" placeholder="E-mail adres" value="{--E-MAIL--}" >
<div id="emailx" class="form-error form-hidden">Wat is uw e-mail adres?</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="titel">Titel: *</label>
<div class="col-sm-10">
<input type="text" require class="form-control" id="titel" name="Titel" placeholder="Titel van uw vraag of aanbod" value="{--TITEL--}" >
<div id="titelx" class="form-error form-hidden">Wat is de titel van uw vraag of aanbod?</div>
</div>
</div>
<from>
I have been using jQuery and calling a function to populate drop downs.
function loadDropDowns(name,value)
{
var ddl = "#Categories";
$(ddl).append('<option value="' + value + '">' + name + "</option>'");
}
In general this should be fine, but it's possible for this to not work if there is an intermediate cache (a proxy) that is configured to ignore the request parameters.
For example, if you are serving static content through Akamai CDN, it can be configured to ignore request parameters to prevent cache busting using this method.
It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.
This is actually a bit trickier than you'd think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check is.null(foo$a)
. A more stringent test might be to check that the name is actually defined in the list:
foo <- list(a=42, b=NULL)
foo
is.null(foo[["a"]]) # FALSE
is.null(foo[["b"]]) # TRUE, but the element "exists"...
is.null(foo[["c"]]) # TRUE
"a" %in% names(foo) # TRUE
"b" %in% names(foo) # TRUE
"c" %in% names(foo) # FALSE
...and foo[["a"]]
is safer than foo$a
, since the latter uses partial matching and thus might also match a longer name:
x <- list(abc=4)
x$a # 4, since it partially matches abc
x[["a"]] # NULL, no match
[UPDATE] So, back to the question why exists('foo$a')
doesn't work. The exists
function only checks if a variable exists in an environment, not if parts of a object exist. The string "foo$a"
is interpreted literary: Is there a variable called "foo$a"? ...and the answer is FALSE
...
foo <- list(a=42, b=NULL) # variable "foo" with element "a"
"bar$a" <- 42 # A variable actually called "bar$a"...
ls() # will include "foo" and "bar$a"
exists("foo$a") # FALSE
exists("bar$a") # TRUE
A lot of the existing answers don't seem to answer the actual question. They are about what the commands do, not about what you (the user) want — the use case. But that is what the OP asked about!
It might be more helpful to couch the description in terms of what it is precisely that you regret at the time you give a git reset
command. Let's say we have this:
A - B - C - D <- HEAD
Here are some possible regrets and what to do about them:
git reset --soft A
. I can now immediately commit and presto, all the changes since A are one commit.
git reset --mixed A
. The commits are gone and the index is back at A, but the work area still looks as it did after D. So now I can add-and-commit in a whole different grouping.
Make a new branch otherbranch
, and then git reset --hard A
. The current branch now ends at A, with otherbranch
stemming from it.
(Of course you could also use a hard reset because you wish B, C, and D had never happened at all.)
The other option for using PHP scripts sans extension is
Options +MultiViews
Or even just following in the directories .htaccess
:
DefaultType application/x-httpd-php
The latter allows having all filenames without extension script
being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).
In the page file:
<script type="text/javascript">
var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>
while in code behind:
public int[] numbers = WhatEverGetTheArray();
You can use the following tag
<body oncontextmenu="return false"><!-- your page body hear--></body>
OR you can create your own menu when right click:
Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...
So you can copy as in your first example without any problem :
String s = "hello";
String backup_of_s = s;
s = "bye";
In my case this error is happening because of not connected to firebase firestore but using the same.
To rectify the issue please go to Tools-> Firebase
when a window will open on RHS choose the options to -> Connect your app to Firebase -> Add Cloud Firestore to your app
Solution in Python using list comprehension
f= [[i,j] for i in list for j in list if j+i==X];
O(N2)
also gives two ordered pairs- (a,b) and (b,a) as well
public class Organization {
@Id
@Column(name="org_id")
@GeneratedValue
private int id;
@Column(name="org_name")
private String name;
@Column(name="org_office_address1")
private String address1;
@Column(name="org_office_addres2")
private String address2;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
@Column(name="country")
private String country;
@JsonIgnore
@OneToOne
@JoinColumn(name="pkg_id")
private int pkgId;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="pincode")
private String pincode;
@OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);
@Column(name="status")
private String status = "ACTIVE";
@Column(name="project_id")
private int redmineProjectId;
public int getRedmineProjectId() {
return redmineProjectId;
}
public void setRedmineProjectId(int redmineProjectId) {
this.redmineProjectId = redmineProjectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set<OrganizationBranch> getOrganizationBranch() {
return organizationBranch;
}
public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
this.organizationBranch = organizationBranch;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired
Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf
- obviously this file can only be edited with root access, but is viewable on non-rooted devices.
I would just query for the for
attribute instead of repetitively recursing the DOM tree.
$("input:checkbox").on("change", function() {
$("label[for='"+this.id+"']").text("TESTTTT");
});
[0]=> string(141)
means $message is an array so you should do strlen($message[0]) < 141
...
If you are allowed to go further then javascript/html facilities - I would use the apache web server to represent your directory listing via http.
If this solution is appropriate. these are the steps:
download apache hhtp server from one of the mirrors http://httpd.apache.org/download.cgi
unzip/install (if msi) it to the directory e.g C:\opt\Apache (the instruction is for windows)
map the network forlder as a local drive on windows (\server\folder to let's say drive H:)
open conf/httpd.conf file
make sure the next line is present and not commented
LoadModule autoindex_module modules/mod_autoindex.so
Add directory configuration
<Directory "H:/path">
Options +Indexes
AllowOverride None
Order allow,deny
Allow from all
</Directory>
7. Start the web server and make sure the directory listingof the remote folder is available by http. hit localhost/path
8. use a frame inside your web page to access the listing
What is missed: 1. you mignt need more fancy configuration for the host name, refer to Apache Web Server docs. Register the host name in DNS server
I know there are plenty of answers here, but I think git reset --soft HEAD~1
deserves some attention, because it let you keep changes in the last local (not pushed) commit while solving the diverged state. I think this is a more versatile solution than pull with rebase
, because the local commit can be reviewed and even moved to another branch.
The key is using --soft
, instead of the harsh --hard
. If there is more than 1 commit, a variation of HEAD~x
should work. So here are all the steps that solved my situation (I had 1 local commit and 8 commits in the remote):
1) git reset --soft HEAD~1
to undo local commit. For the next steps, I've used the interface in SourceTree, but I think the following commands should also work:
2) git stash
to stash changes from 1). Now all the changes are safe and there's no divergence anymore.
3) git pull
to get the remote changes.
4) git stash pop
or git stash apply
to apply the last stashed changes, followed by a new commit, if wanted. This step is optional, along with 2), when want to trash the changes in local commit. Also, when want to commit to another branch, this step should be done after switching to the desired one.
This link should satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
You are actually trying to redirect a page which has some response to throw. So first you keep the information you have throw in a buffer using response.buffer = true
in beginning of the page and then flush it when required using response.flush
this error will get fixed
You could use a javascript snippit
$(function()
{
// Enable drop menu clicks
$(".nav li > a").off();
});
That will unbind the click event preventing url changing.
android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."
checkout changes for Android Support Library, revision 22.1.0 (April 2015)
You can load data from a csv or text file. If you have a text file with records from a table, you can load those records within the table. For example if you have a text file, where each row is a record with the values for each column, you can load the records this way.
id //field 1
name //field2
1,peter
2,daniel
...
--example on windows
LOAD DATA LOCAL INFILE 'C:\\directory_example\\table.txt'
INTO TABLE Table
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n';
presentModalViewController:
MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];
dismissModalViewController:
[self dismissModalViewControllerAnimated:YES];
Here's Jurgy's great nearest neighbour approach but implemented using scipy.cKDTree. In my tests it's about 100x faster.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.spatial import cKDTree
def data_coord2view_coord(p, resolution, pmin, pmax):
dp = pmax - pmin
dv = (p - pmin) / dp * resolution
return dv
n = 1000
xs = np.random.randn(n)
ys = np.random.randn(n)
resolution = 250
extent = [np.min(xs), np.max(xs), np.min(ys), np.max(ys)]
xv = data_coord2view_coord(xs, resolution, extent[0], extent[1])
yv = data_coord2view_coord(ys, resolution, extent[2], extent[3])
def kNN2DDens(xv, yv, resolution, neighbours, dim=2):
"""
"""
# Create the tree
tree = cKDTree(np.array([xv, yv]).T)
# Find the closest nnmax-1 neighbors (first entry is the point itself)
grid = np.mgrid[0:resolution, 0:resolution].T.reshape(resolution**2, dim)
dists = tree.query(grid, neighbours)
# Inverse of the sum of distances to each grid point.
inv_sum_dists = 1. / dists[0].sum(1)
# Reshape
im = inv_sum_dists.reshape(resolution, resolution)
return im
fig, axes = plt.subplots(2, 2, figsize=(15, 15))
for ax, neighbours in zip(axes.flatten(), [0, 16, 32, 63]):
if neighbours == 0:
ax.plot(xs, ys, 'k.', markersize=5)
ax.set_aspect('equal')
ax.set_title("Scatter Plot")
else:
im = kNN2DDens(xv, yv, resolution, neighbours)
ax.imshow(im, origin='lower', extent=extent, cmap=cm.Blues)
ax.set_title("Smoothing over %d neighbours" % neighbours)
ax.set_xlim(extent[0], extent[1])
ax.set_ylim(extent[2], extent[3])
plt.savefig('new.png', dpi=150, bbox_inches='tight')
Just a clarification for those new to Swift and iOS programming. Below line of code:
button.setTitle("myTitle", forState: UIControlState.Normal)
only applies to IBOutlets
, not IBActions
.
So, if your app is using a button as a function to execute some code, say playing music, and you want to change the title from Play
to Pause
based on a toggle variable, you need to also create an IBOutlet
for that button.
If you try to use button.setTitle
against an IBAction
you will get an error. Its obvious once you know it, but for the noobs (we all were) this is a helpful tip.
Using Thread.currentThread()
:
private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}
i used my .php file to put required into sessions
$_SESSION['name'] = $phparray["name"]; $ajaxoutput['name'] =$phparray["name"];
in my .js file i used
sessionStorage.setItem("name", ajaxreturnedarray["name"]);
and i retrieved this using
var myName= sessionStorage.getItem("name");
in other .js files or in same .js files
if i keep it as it is , it will return same at all times even you loggedout. so while logging out i made
sessionStorage.setItem("name", "");
using this i emptied local variable. i used this process in single page website login/logout sessions. i hope this way will work for you because it worked for me. plz let me know your experiences.
Create the index.blade.php file in the views folder, that should be all
If you don't want to use WMI, I can suggest systeminfo.exe. But, there may be a better way to do that.
(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()
It works with me only if I set the footer/header of the tableview to nil first:
self.footer = self.searchTableView.tableFooterView;
CGRect frame = self.footer.frame;
frame.size.height = 200;
self.footer.frame = frame;
self.searchTableView.tableFooterView = nil;
self.searchTableView.tableFooterView = self.footer;
Make sure that self.footer is a strong reference to prevent the footer view from being deallocated
#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"
Output:
> ./above_script.sh
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file
Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html
Its a bit late but if you don't want to use a div specifically, I usually do it like this...
var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);
ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.
I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.
DELIMITER $$
CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;
WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
SET lastParent = curParent;
SELECT ParentId from `test` where id=curId limit 1 into curParent;
IF curParent = pParentId THEN
SET isChild = 1;
END IF;
SET curId = curParent;
END WHILE;
RETURN isChild;
END$$
Here, the table test
has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.
Usage :
SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;
Result :
3 7 k
5 3 d
9 3 f
1 5 a
SQL for test creation :
CREATE TABLE IF NOT EXISTS `test` (
`Id` int(11) NOT NULL,
`ParentId` int(11) DEFAULT NULL,
`Name` varchar(300) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');
EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.
Calling an external command in Python
A simple way to call an external command is using os.system(...)
. And this function returns the exit value of the command. But the drawback is we won't get stdout and stderr.
ret = os.system('some_cmd.sh')
if ret != 0 :
print 'some_cmd.sh execution returned failure'
Calling an external command in Python in background
subprocess.Popen
provides more flexibility for running an external command rather than using os.system
. We can start a command in the background and wait for it to finish. And after that we can get the stdout and stderr.
proc = subprocess.Popen(["./some_cmd.sh"], stdout=subprocess.PIPE)
print 'waiting for ' + str(proc.pid)
proc.wait()
print 'some_cmd.sh execution finished'
(out, err) = proc.communicate()
print 'some_cmd.sh output : ' + out
Calling a long running external command in Python in the background and stop after some time
We can even start a long running process in the background using subprocess.Popen
and kill it after sometime once its task is done.
proc = subprocess.Popen(["./some_long_run_cmd.sh"], stdout=subprocess.PIPE)
# Do something else
# Now some_long_run_cmd.sh exeuction is no longer needed, so kill it
os.system('kill -15 ' + str(proc.pid))
print 'Output : ' proc.communicate()[0]
I had followed the instructions as per the ngrok download instructions:
So the file downloaded to ~/Downloads
But I still needed to move ngrok into my binaries folder, like so:
mv ~/Downloads/ngrok /usr/local/bin
Then running ngrok
in terminal works
Totally agree with @Greg Hewgill
And if you path includes spaces, you might use, try adding with apostrophe '
or `
git diff 'MyProject/My Folder/My Sub Folder/file_2.rb'
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
A more specific way:
SHOW PROCEDURE STATUS
WHERE Db = DATABASE() AND Type = 'PROCEDURE'
My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"
Not sure why both were needed. I used this to remove a dependency on glut32.dll.
Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.
I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt
1)The Component (.vue file)
//MyComponent.vue file
<template>
<div>
<div>Hello {{name}}</div>
<button @click="function_A">Read Name</button>
<button @click="function_B">Write Name</button>
<button @click="function_C">Reset</button>
<div>{{message}}</div>
</div>
</template>
<script>
import Mylib from "./Mylib"; // <-- import
export default {
name: "MyComponent",
data() {
return {
name: "Bob",
message: "click on the buttons"
};
},
methods: {
function_A() {
Mylib.myfuncA(this); // <---read data
},
function_B() {
Mylib.myfuncB(this); // <---write data
},
function_C() {
Mylib.myfuncC(this); // <---write data
}
}
};
</script>
2)The External js file
//Mylib.js
let exports = {};
// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
that.message =
"you hit ''myfuncA'' function that is located in Mylib.js and data.name = " +
that.name;
};
exports.myfuncB = (that) => {
that.message =
"you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
that.name = "Nassim"; // <-- change name to Nassim
};
exports.myfuncC = (that) => {
that.message =
"you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
that.name = "Bob"; // <-- change name to Bob
};
export default exports;
3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue
after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html
My problem was solved by uhlocking the screen rotation on my android the app which was causing me a problem now works perfectly
There are 5 cases for using the underscore in Python.
For storing the value of last expression in interpreter.
For ignoring the specific values. (so-called “I don’t care”)
To give special meanings and functions to name of variables or functions.
To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.
To separate the digits of number literal value.
Here is a nice article with examples by mingrammer.
As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.
CUBRID (open source RDBMS) explains the idea of this two algorithms:
- Two-phase locking (2PL)
The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).
- Multi-version concurrency control (MVCC)
The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.
When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).
The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).
In 2PL Transaction isolation levels control the following:
Whether locks are taken when data is read, and what type of locks are requested.
How long the read locks are held.
Whether a read operation referencing rows modified by another transaction:
Block until the exclusive lock on the row is freed.
Retrieve the committed version of the row that existed at the time the statement or transaction started.
Read the uncommitted data modification.
Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.
A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.
Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)
READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]
READ_COMMITED:
REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.
SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.
Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016.
For this reason I think, the correct calculation should be like the below simply;
var d = new Date(),
dayInMs = 1000 * 60 * 60 * 24,
weekInMs = dayInMs * 7,
startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
todayElapsedTime = d.valueOf() - startOfToday,
dayDiff = d.getDay() * dayInMs,
dateDiff = dayDiff + todayElapsedTime,
// finally
startOfWeek = d.valueOf() - dateDiff,
endOfWeek = startOfWeek + weekInMs - 1;
It is possible in css, but not for all the browsers.
The effect on all browsers:
http://www.456bereastreet.com/lab/form_controls/checkboxes/
A possibility is a custom checkbox with javascript:
http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/
Here are my findings. I also faced this problem today's morning. I just added my current user to application pool on which application was running.
Steps:
Open IIS
Click on application pool
Select your application pool on which you are getting problem
Right Click -> advanced settings
Click on three dot icon beside the identiy
Now select custom account
Give your PC user name and Password
Save
Refresh your application.. and it will start working. There was some security issue for accessing dll.
This is what i did to make it work. Make sure you put
webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.
[ServiceContract]
public interface ITestService
{
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
string GetData();
}
public class TestService : ITestService
{
public string GetJsonData()
{
return "I am good...";
}
}
Inside service model
<service name="TechCity.Business.TestService">
<endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
<endpoint address="mex"
contract="IMetadataExchange" binding="mexHttpBinding"/>
<endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
name="Http" contract="TechCity.Interfaces.ITestService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8739/test" />
</baseAddresses>
</host>
</service>
EndPoint Behaviour
<endpointBehaviors>
<behavior name="jsonBehavior">
<webHttp automaticFormatSelectionEnabled="true" />
<!-- use JSON serialization -->
</behavior>
</endpointBehaviors>
If you get this error and the terminal is not descriptive enough to help you, Heroku might be able to tell you what is wrong through their website. Try the following:
In my case, I had accidentally ignored my Gemfile.lock.
\9 doesn’t work with font-family, instead you’d need to use “\0/ !important” as Chris mentioned above, for example:
p { font-family: Arial \0/ !important; }
I was looking for a similar solution and this is what I would suggest. In the OnTouch method, record the time for MotionEvent.ACTION_DOWN event and then for MotionEvent.ACTION_UP, record the time again. This way you can set your own threshold also. After experimenting few times you will know the max time in millis it would need to record a simple touch and you can use this in move or other method as you like.
Hope this helped. Please comment if you used a different method and solved your problem.
rand() return a int between 0 and RAND_MAX. To get a random number between 0.0 and 1.0, first cast the int return by rand() to a float, then divide by RAND_MAX.
public enum EXIT_CODE {
A(104), B(203);
private int numVal;
EXIT_CODE(int numVal) {
this.numVal = numVal;
}
public int getNumVal() {
return numVal;
}
}
Make sure the scp command is available on both sides - both on the client and on the server.
If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:
yum -y install openssh-clients
If you work with Debian or Ubuntu and clones, install this package:
apt-get install openssh-client
Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found
or similar although you have it locally. This already confused thousands of people, I guess :)
The reason you are getting this error is that you are trying to convert a space character to an integer, which is totally impossible and restricted.And that's why you are getting this error.
Check your code and correct it, it will work fine
As pointed out by Tanis.7x, the support library version (23) does not match the targetSdkVersion (22)
You can fix this by doing the following:
In the build.grade
file of your app module, change the following line of code
compile 'com.android.support:appcompat-v7:23.0.0'
To
compile 'com.android.support:appcompat-v7:22.+'
This will use the latest version of the appcompat version that is compatible with SdkVersion 22.
You can set string limit as below example:
<td>{{str_limit($biodata ->description, $limit = 20, $end = '...')}}</td>
It will display only the 20 letters including whitespaces and ends with ....
I'm a fan of gitk
's graphical UI to visualize git repos. You can view the last item stashed with:
gitk stash
You can also use view any of your stashed changes (as listed by git stash list
). For example:
gitk stash@{2}
In the below screenshot, you can see the stash as a commit in the upper-left, when and where it came from in commit history, the list of files modified on the bottom right, and the line-by-line diff in the lower-left. All while the stash is still tucked away.
you can use the InvariantCulture
string priceSameInAllCultures = price.ToString(System.Globalization.CultureInfo.InvariantCulture);
another possibility would be to do something like that:
private int GetDecimals(decimal d, int i = 0)
{
decimal multiplied = (decimal)((double)d * Math.Pow(10, i));
if (Math.Round(multiplied) == multiplied)
return i;
return GetDecimals(d, i+1);
}
One liner as suggested here
How to determine one year from now in Javascript by JP DeVries
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
Or you can get the number of years from somewhere in a variable:
const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
From this forum:
parseInt()
returns primitive integer type (int), wherebyvalueOf
returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.
# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}
import boto3
import io
s3 = boto3.resource('s3')
obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)
# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))
print(new_dict['status'])
# Should print "Error"
http://wsnippets.com/export-html-table-data-excel-sheet-using-jquery/ try this link it might solve your problem
I Used Datatable JS plugin for my purpose of exporting an html table data into various formats. With my experience it was very quick, easy to use and configure with minimal coding.
Below is a sample jquery call using datatable plugin, #example
is your table id
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );
Please find the complete example in below datatable reference link :
https://datatables.net/extensions/buttons/examples/html5/simple.html
This is how it looks after configuration( from reference site) :
You need to have following library references in your html ( some can be found in the above reference link)
jquery-1.12.3.js
jquery.dataTables.min.js
dataTables.buttons.min.js
jszip.min.js
pdfmake.min.js
vfs_fonts.js
buttons.html5.min.js
For me no work i need upgrade pip....
Debian/Ubuntu
install dependencies
sudo apt-get install libpython-dev libssl-dev libffi-dev
upgrade pip and install packages
sudo pip install -U pip
sudo pip install -U pyopenssl ndg-httpsclient pyasn1
If you want remove dependencies
sudo apt-get remove --purge libpython-dev libssl-dev libffi-dev
sudo apt-get autoremove
There are more api-friendly libraries than Net::HTTP
, for example httparty:
require "httparty"
File.open("/tmp/my_file.flv", "wb") do |f|
f.write HTTParty.get("http://somedomain.net/flv/sample/sample.flv").parsed_response
end
A constructor in Java doesn't actually "build" the object, it is used to initialize fields.
Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.
Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.
If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.
This should give you a start
>>> import json
>>> print json.dumps([{'name': k, 'size': v} for k,v in sample.items()], indent=4)
[
{
"name": "PointInterpolator",
"size": 1675
},
{
"name": "ObjectInterpolator",
"size": 1629
},
{
"name": "RectangleInterpolator",
"size": 2042
}
]
Adding this late answer to show a case most people will come across. If you only need to see what is the last item in the list, use the last
key word:
<div *ngFor="let item of devcaseFeedback.reviewItems; let last = last">
<divider *ngIf="!last"></divider>
</div>
This will add the divider component to every item except the last.
Because of the comment below, I will add the rest of the ngFor
exported values that can be aliased to local variables (As are shown in the docs):
You can get maximum column value and increment it:
InnoDB uses the following algorithm to initialize the auto-increment counter for a table t that contains an AUTO_INCREMENT column named ai_col: After a server startup, for the first insert into a table t, InnoDB executes the equivalent of this statement:
SELECT MAX(ai_col) FROM t FOR UPDATE;
InnoDB increments by one the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. If the table is empty, InnoDB uses the value 1.
Also you can use SHOW TABLE STATUS and its "Auto_increment" value.
In python functions aren't accessible magically from everywhere (like they are in say, php). They have to be declared first. So this will work:
def pyth_test (x1, x2):
print x1 + x2
pyth_test(1, 2)
But this won't:
pyth_test(1, 2)
def pyth_test (x1, x2):
print x1 + x2
The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use
yournumber.ToString("0.00");
SQL> alter session set "_ORACLE_SCRIPT"=true;
SQL> create user sec_admin identified by "Chutinhbk123@!";
#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();
Reference: std::thread::hardware_concurrency
In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef
lines):
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
int numCPU = sysinfo.dwNumberOfProcessors;
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
int mib[4];
int numCPU;
std::size_t len = sizeof(numCPU);
/* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
/* get the number of CPUs from the system */
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
{
mib[1] = HW_NCPU;
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
numCPU = 1;
}
int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
int numCPU = sysconf(_SC_NPROC_ONLN);
NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
Only using Angular Template
<input type="text" #searchText>
<span (click)="searchText.focus()">clear</span>
In this code you are not comparing string values, you are comparing pointer values. If you want to compare string values you need to use a string comparison function such as strcmp.
if ( 0 == strcmp(var1, "dev")) {
..
}
You've got two common situations. The first is that you want random numbers and aren't too fussed about the quality or execution speed. In that case, use the following macro
#define uniform() (rand()/(RAND_MAX + 1.0))
that gives you p in the range 0 to 1 - epsilon (unless RAND_MAX is bigger than the precision of a double, but worry about that when you come to it).
int x = (int) (uniform() * N);
Now gives a random integer on 0 to N -1.
If you need other distributions, you have to transform p. Or sometimes it's easier to call uniform() several times.
If you want repeatable behaviour, seed with a constant, otherwise seed with a call to time().
Now if you are bothered about quality or run time performance, rewrite uniform(). But otherwise don't touch the code. Always keep uniform() on 0 to 1 minus epsilon. Now you can wrap the C++ random number library to create a better uniform(), but that's a sort of medium-level option. If you are bothered about the characteristics of the RNG, then it's also worth investing a bit of time to understand how the underlying methods work, then provide one. So you've got complete control of the code, and you can guarantee that with the same seed, the sequence will always be exactly the same, regardless of platform or which version of C++ you are linking to.
You can do that using CSS3.
Here is the HTML code snippet:
<ul id="listitem_ascolun">_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li> _x000D_
<li>5</li>_x000D_
<li>6</li>_x000D_
<li>7</li>_x000D_
<li>8</li>_x000D_
<li>9</li>_x000D_
<li>10</li>_x000D_
<li>11</li>_x000D_
<li>12</li> _x000D_
</ul>
_x000D_
& Here is the CSS3 code snippet :
#listitem_ascolun ul{margin:0;padding:0;list-style:none;}_x000D_
_x000D_
#listitem_ascolun {_x000D_
height: 500px; _x000D_
column-count: 4;_x000D_
-webkit-column-count: 4;_x000D_
-moz-column-count: 4;_x000D_
}_x000D_
_x000D_
#listitem_ascolun li {_x000D_
display: inline-block;_x000D_
}
_x000D_
You could use width: 100%;
in your css.
Definitely possible with any number of libraries and/or HTML5 technologies. You could possible hack something together in pure CSS by using something like the border-bottom property, but it would probably be horribly hacky.
If you're serious about this, you should take a look at a JS library for canvas drawing or SVG. For example, something like http://www.graphjs.org/ or http://jsdraw2dx.jsfiction.com/
Had a similar issue. But it is important to understand the root cause and it may vary for different use cases.
Scenario 1
You are trying to decrypt a value which was not encoded correctly in the first place.
byte[] encryptedBytes = Base64.decodeBase64(encryptedBase64String);
If the String is misconfigured for certain reason or has not been encoded correctly, you would see the error " Input length must be multiple of 16 when decrypting with padded cipher"
Scenario 2
Now if by any chance you are using this encoded string in url (trying to pass in the base64Encoded value in url, it will fail.
You should do URLEncoding and then pass in the token, it will work.
Scenario 3
When integrating with one of the vendors, we found that we had to do encryption of Base64 using URLEncoder but then we need not decode it because it was done internally by the Vendor
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
Using Twitter Bootstrap classes may be the best choice :
pull-left
makes an element floating leftclearfix
allows the element to contain floating elements (if not already set via another class)<div class="paragraphs">
<div class="row">
<div class="span4">
<div class="clearfix content-heading">
<img class="pull-left" src="../site/img/success32.png"/>
<h3>Experience   </h3>
</div>
<p>Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
</div>
</div>
</div>
A solution with reduce()
:
int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97
In the code above, reduce()
returns data in Optional
format, which you can convert to int
by getAsInt()
.
If we want to compare the max value with a certain number, we can set a start value in reduce()
:
int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100
In the code above, when reduce()
with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:
double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html
Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html
Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm
Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html
In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).
I have just discovered a way to append text and its working fine at least.
var text = 'Put any text here';
$('#text').append(text);
You can change text according to your need.
Hope this helps.
In my case the site that I'm connecting to has upgraded to TLS 1.2. As a result I had to install .net 4.5.2 on my web server in order to support it.
To get the 2 chars ISO 639-1 language identifier use:
System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
There is no need to use any plugin, you can do it like this:
var divPosition = $('#divId').offset();
then use this to scroll document to specific DOM:
$('html, body').animate({scrollTop: divPosition.top}, "slow");
@bninopaul 's answer is not completely for beginners
here is the code you can "copy and run"
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[13,1,1,0,2,0],
[3,9,6,0,1,0],
[0,0,16,2,0,0],
[0,0,0,13,0,0],
[0,0,0,0,15,0],
[0,0,1,0,0,15]]
df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size
plt.show()
Packages are just .xar archives with a different extension and a specified file hierarchy. Unfortunately, part of that file hierarchy is a cpio.gz archive of the actual installables, and usually that's what you want to edit. And there's also a Bom file that includes information on the files inside that cpio archive, and a PackageInfo file that includes summary information.
If you really do just need to edit one of the info files, that's simple:
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
# edit stuff
xar -cf ../Foo-new.pkg *
But if you need to edit the installable files:
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc |cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o | gzip -c > Payload
mkbom Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar -cf ../Foo-new.pkg
I believe you can get mkbom (and lsbom) for most linux distros. (If you can get ditto, that makes things even easier, but I'm not sure if that's nearly as ubiquitously available.)
Forward declaring things in C++ is very useful because it dramatically speeds up compilation time. You can forward declare several things in C++ including: struct
, class
, function
, etc...
But can you forward declare an enum
in C++?
No you can't.
But why not allow it? If it were allowed you could define your enum
type in your header file, and your enum
values in your source file. Sounds like it should be allowed right?
Wrong.
In C++ there is no default type for enum
like there is in C# (int). In C++ your enum
type will be determined by the compiler to be any type that will fit the range of values you have for your enum
.
What does that mean?
It means that your enum
's underlying type cannot be fully determined until you have all of the values of the enum
defined. Which mans you cannot separate the declaration and definition of your enum
. And therefore you cannot forward declare an enum
in C++.
The ISO C++ standard S7.2.5:
The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than
int
unless the value of an enumerator cannot fit in anint
orunsigned int
. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value ofsizeof()
applied to an enumeration type, an object of enumeration type, or an enumerator, is the value ofsizeof()
applied to the underlying type.
You can determine the size of an enumerated type in C++ by using the sizeof
operator. The size of the enumerated type is the size of its underlying type. In this way you can guess which type your compiler is using for your enum
.
What if you specify the type of your enum
explicitly like this:
enum Color : char { Red=0, Green=1, Blue=2};
assert(sizeof Color == 1);
Can you then forward declare your enum
?
No. But why not?
Specifying the type of an enum
is not actually part of the current C++ standard. It is a VC++ extension. It will be part of C++0x though.
sapSet = mbo.getThisMboSet()
sapCount = sapSet.count()
saplist = []
if sapCount > 1:
for i in range(sapCount):`enter code here`
defaultCheck = sapSet.getMbo(i)
saplist.append(defaultCheck.getInt("HNADEFACC"))
defCount = saplist.count(1)
if defCount > 1:
errorgroup = " Please Note: you are allowed"
errorkey = " only One Default Account"
if defCount < 1:
errorgroup = " Please enter "
errorkey = " at leat One Default Account"
else:
mbo.setValue("HNADEFACC",1,MboConstants.NOACCESSCHECK)
A concrete example of overhead is the difference between a "local" procedure call and a "remote" procedure call.
For example, with classic RPC (and many other remote frameworks, like EJB), a function or method call looks the same to a coder whether its a local, in memory call, or a distributed, network call.
For example:
service.function(param1, param2);
Is that a normal method, or a remote method? From what you see here you can't tell.
But you can imagine that the difference in execution times between the two calls are dramatic.
So, while the core implementation will "cost the same", the "overhead" involved is quite different.
See the Java EE 7 Json specification. This is the right way:
String json = Json.createObjectBuilder()
.add("key1", "value1")
.add("key2", "value2")
.build()
.toString();
Your data.frame mat
is rectangular (n_rows!= n_cols).
Therefore, you cannot make a data.frame
out of the column- and rownames, because each column in a data.frame must be the same length.
Maybe this suffices your needs:
require(reshape2)
mat$id <- rownames(mat)
melt(mat)
It doesn't seem like you can access this in browser. The search input is a Webkit HTML wrapper for the Cocoa NSSearchField. The cancel button seems to be contained within the browser client code with no external reference available from the wrapper.
Sources:
Looks like you'll have to figure it out through mouse position on click with something like:
$('input[type=search]').bind('click', function(e) {
var $earch = $(this);
var offset = $earch.offset();
if (e.pageX > offset.left + $earch.width() - 16) { // X button 16px wide?
// your code here
}
});
Delete this is legal as long as object is in heap. You would need to require object to be heap only. The only way to do that is to make the destructor protected - this way delete may be called ONLY from class , so you would need a method that would ensure deletion
You can also use this approach in case you want to pass some http parameters and send a json request:
(note: I have added in some extra code just incase it helps any other future readers)
public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {
//add the http parameters you wish to pass
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
//Build the server URI together with the parameters you wish to pass
URIBuilder uriBuilder = new URIBuilder("http://google.ug");
uriBuilder.addParameters(postParameters);
HttpPost postRequest = new HttpPost(uriBuilder.build());
postRequest.setHeader("Content-Type", "application/json");
//this is your JSON string you are sending as a request
String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";
//pass the json string request in the entity
HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
postRequest.setEntity(entity);
//create a socketfactory in order to use an http connection manager
PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);
connManager.setMaxTotal(20);
connManager.setDefaultMaxPerRoute(20);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(HttpClientPool.connTimeout)
.setConnectTimeout(HttpClientPool.connTimeout)
.setConnectionRequestTimeout(HttpClientPool.readTimeout)
.build();
// Build the http client.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
CloseableHttpResponse response = httpclient.execute(postRequest);
//Read the response
String responseString = "";
int statusCode = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
HttpEntity responseHttpEntity = response.getEntity();
InputStream content = responseHttpEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = buffer.readLine()) != null) {
responseString += line;
}
//release all resources held by the responseHttpEntity
EntityUtils.consume(responseHttpEntity);
//close the stream
response.close();
// Close the connection manager.
connManager.close();
}
I think you could use the following HTML and CSS combo instead:
<li>
<a href="#">Backback</a>
</li>
Then use CSS background for the basket visibility on hover:
.listblock ul li a {
padding: 5px 30px 5px 10px;
display: block;
}
.listblock ul li a:hover {
background: transparent url('../img/basket.png') no-repeat 3px 170px;
}
Simples!
If your dates
column does not contain time information, you could get away with:
WHERE dates BETWEEN '20121211' and '20121213'
However, given your dates
column is actually datetime, you want this
WHERE dates >= '20121211'
AND dates < '20121214' -- i.e. 00:00 of the next day
Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:
WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'
Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.
I don't really see a way to do this as-is. I think you might need to remove the overflow:hidden
from div#1 and add another div within div#1 (ie as a sibling to div#2) to hold your unspecified 'content' and add the overflow:hidden
to that instead. I don't think that overflow can be (or should be able to be) over-ridden.
import pickle
your_data = {'foo': 'bar'}
# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Load data (deserialize)
with open('filename.pickle', 'rb') as handle:
unserialized_data = pickle.load(handle)
print(your_data == unserialized_data)
The advantage of HIGHEST_PROTOCOL
is that files get smaller. This makes unpickling sometimes much faster.
Important notice: The maximum file size of pickle is about 2GB.
import mpu
your_data = {'foo': 'bar'}
mpu.io.write('filename.pickle', data)
unserialized_data = mpu.io.read('filename.pickle')
For your application, the following might be important:
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
You will then get another warning: “Your PHP parameter session.gc_maxlifetime is lower that cookie validity configured in phpMyAdmin, because of this, your login will expire sooner than configured in phpMyAdmin.“. That makes sense because php’s session will time out first anyways. So we will need to change /etc/php.ini .
session.gc_maxlifetime = 43200
That’s 12 hours in seconds.
Restart your apache server and you are done!
source: http://birdchan.com/home/2011/06/06/phpmyadmin-timeout-after-1440-seconds/
this works for me! :)
Segmentation is more hierarchal and "pretty" but can be limiting.
For example, if you have a url with three segments, each one passing different parameters to search for a car via make, model and color:
www.example.com/search/honda/civic/blue
This is a very pretty url and more easily remembered by the end user, but now your kind of stuck with this structure. Say you want to make it so that in the search the user could search for ALL blue cars, or ALL Honda Civics? A query parameter solves this because it give a key value pair. So you could pass:
www.example.com/search?color=blue
www.example.com/search?make=civic
Now you have a way to reference the value via it's key - either "color" or "make" in your query code.
You could get around this by possibly using more segments to create a kind of key value structure like:
www.example.com/search/make/honda/model/civic/color/blue
Hope that makes sense..
I frankly would recommend the RazorGenerator nuget package. That way your views have a .designer.cs
file generated when you save them and on top of getting compile time errors for you views, they are also precompiled into the assembly (= faster warmup) and Resharper provides some additional help as well.
To use this include the RazorGenerator nuget package in you ASP.NET MVC project and install the "Razor Generator" extension under item under Tools ? Extensions and Updates.
We use this and the overhead per compile with this approach is much less. On top of this I would probably recommend .NET Demon by RedGate which further reduces compile time impact substantially.
Hope this helps.
Swift 5.
To convert a String
to a URL
:
let stringToURL = URL(string: "your-string")
To convert a URL
to a String
:
let urlToString = stringToURL?.absoluteString
Today I faced with this problem. I used Android Studio 2.1.3, windows 10. While debugging it works fine, but if I update to release mode it does not work. I cleared all proguard conditions, updated, but this was not solution.
The solution is related with project structure. The google_maps_api.xml file was different between app\src\debug\res and app\src\release\res. I did manual copy paste from debug to release folder.
Now it works.
Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.
string text = no.ToString("0000");
use
SELECT STR_TO_DATE(date_column,'%Y-%m-%d') from table;
also gothrough
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
May be will be useful. Just all queries send via ws to node
<VirtualHost *:80>
ServerName www.domain2.com
<Location "/">
ProxyPass "ws://localhost:3001/"
</Location>
</VirtualHost>
If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:
Switch to branch "foo" and update it:
$ git checkout foo
$ git pull
You can see the branches you've got by issuing command:
$ git branch
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
Im working with mysql and registered with root user, the solution that work for me is the following:
mysql > SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
You can use PdfBox from Apache which is simple to use and has good performance.
Here is an example of extracting text from a PDF file (you can read more here) :
import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;
public class PDFTest {
public static void main(String[] args){
PDDocument pd;
BufferedWriter wr;
try {
File input = new File("C:\\Invoice.pdf"); // The PDF file from where you would like to extract
File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
pd = PDDocument.load(input);
System.out.println(pd.getNumberOfPages());
System.out.println(pd.isEncrypted());
pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
PDFTextStripper stripper = new PDFTextStripper();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
stripper.writeText(pd, wr);
if (pd != null) {
pd.close();
}
// I use close() to flush the stream.
wr.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
UPDATE:
You can get the text using PDFTextStripper:
PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created
I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:
try :
....
since python was searching for a
except Exception as e:
....
but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.
One more solution is
Rails.application.routes.routes
http://hackingoff.com/blog/generate-rails-sitemap-from-routes/
Have you tried just writing out the whole command in a single string?
{
"cmd" : ["gcc $file_name -o ${file_base_name} && ./${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path"
}
I believe (semi-speculation here), that ST3 takes the first argument as the "program" and passes the other strings in as "arguments". https://docs.python.org/2/library/subprocess.html#subprocess.Popen
You can very well use Collections.synchronizedList(List) if all you need is simple invocation synchronization:
List<Object> objList = Collections.synchronizedList(new ArrayList<Object>());
Try this:
$('#parent').on('click', '#child', function() {
// Code
});
From the $.on()
documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Your #child
element doesn't exist when you call $.on()
on it, so the event isn't bound (unlike $.live()
). #parent
, however, does exist, so binding the event to that is fine.
The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent
from #child
.
No JavaScript needed if you use a button instead:
<form action="your_url" method="post">
<button type="submit" name="your_name" value="your_value" class="btn-link">Go</button>
</form>
You can style a button to look like a link, for example:
.btn-link {
border: none;
outline: none;
background: none;
cursor: pointer;
color: #0000EE;
padding: 0;
text-decoration: underline;
font-family: inherit;
font-size: inherit;
}
<select id="mycontrolId" multiple="multiple">
<option value="1" >one</option>
<option value="2" >two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
var data = "1,3,4"; var dataarray = data.split(",");
$("#mycontrolId").val(dataarray);
The parent.children
is an Array like object. Use the following solution:
const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
The parent.children
is NodeList
type, which is an Array like object because:
length
property, which indicates the number of nodes{0: NodeObject, 1: NodeObject, length: 2, ...}
See more details in this article.
parent.children
is an HTMLCollection
: which implements the iterable protocol. In an ES2015 environment, you can use the HTMLCollection
with any construction that accepts iterables.
Use HTMLCollection
with the spread operatator:
const parent = this.el.parentElement;
[...parent.children].forEach(child => {
console.log(child);
});
Or with the for..of
cycle (which is my preferred option):
const parent = this.el.parentElement;
for (const child of parent.children) {
console.log(child);
}
The only problem is that any additional certificates in resulted file will not be recognized, as tools don't expect more than one certificate per PEM/DER encoded file. Even openssl itself. Try
openssl x509 -outform DER -in certificate.cer | openssl x509 -inform DER -outform PEM
and see for yourself.
VelocityEngine velocityEngin = new VelocityEngine();
velocityEngin.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngin.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngin.init();
Template template = velocityEngin.getTemplate("nameOfTheTemplateFile.vtl");
you could use the above code to set the properties for velocity template. You can then give the name of the tempalte file when initializing the Template and it will find if it exists in the classpath.
All the above classes come from package org.apache.velocity*
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
pylab
, not matplotlib.pyplot
You may try using hist
to put your data info along with the fitted curve as below:
import numpy as np
import scipy.stats as stats
import pylab as pl
h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]) #sorted
fit = stats.norm.pdf(h, np.mean(h), np.std(h)) #this is a fitting indeed
pl.plot(h,fit,'-o')
pl.hist(h,normed=True) #use this to draw histogram of your data
pl.show() #use may also need add this
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.
Bitmap contact_pic = BitmapFactory.decodeResource(
v.getContext().getResources(),
R.drawable.android_logo
);
Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else
Info regarding .NET / C#:
Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.
If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.
Create a Java Model using Axis wsdl2java (which can take in .xsd files).
Use a database generation tool for Java that takes in a Java Model. Surely something like Hibernate can do this? I wrote my own tool (takes a couple of days, also generates CRUD code in Java too) to save myself time at work, maybe this would be a nice personal project?
Or just do it manually so that you can check everything is correct and good! Database tools are good enough now that you can zip through creating tables for a model without too many problems.
You can use https://github.com/Mischback/django-project-skeleton repository.
Run below command:
$ django-admin startproject --template=https://github.com/Mischback/django-project-skeleton/archive/development.zip [projectname]
The structure is something like this:
[projectname]/ <- project root
+-- [projectname]/ <- Django root
¦ +-- __init__.py
¦ +-- settings/
¦ ¦ +-- common.py
¦ ¦ +-- development.py
¦ ¦ +-- i18n.py
¦ ¦ +-- __init__.py
¦ ¦ +-- production.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- apps/
¦ +-- __init__.py
+-- configs/
¦ +-- apache2_vhost.sample
¦ +-- README
+-- doc/
¦ +-- Makefile
¦ +-- source/
¦ +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦ +-- media/
¦ ¦ +-- README
¦ +-- README
¦ +-- static/
¦ +-- README
+-- static/
¦ +-- README
+-- templates/
+-- base.html
+-- core
¦ +-- login.html
+-- README