I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"
The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.
Putting this code at the end of your body
tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.
<script>
(function(){
var forms = document.forms || [];
for(var i = 0; i < forms.length; i++){
for(var j = 0; j < forms[i].length; j++){
if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
forms[i][j].focus();
return;
}
}
}
})();
</script>
reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])
incase there are keys not in dict.
Perhaps a simple way to remember: add a dot after the numerator (or denominator)
16 ** (1. / 2) # 4
289 ** (1. / 2) # 17
27 ** (1. / 3) # 3
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError
popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
I was not able to get rsync to connect via ssh on a different port, but I was able to redirect the ssh connection to the computer I wanted via iptables. This is not the solution I was looking for, but it solved my problem.
Create a dictionary with tuple as the key, and print the keys.
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
dict_tuple = {tuple(item): index for index, item in enumerate(k)}
print [list(itm) for itm in dict_tuple.keys()]
# prints [[1, 2], [5, 6, 2], [3], [4]]
At runtime they behave a exactly the same.The bytecode may/not be same (For above Incase,it generates the same bytecode(complie above and check javaap -c;))
At runtime they behave a exactly the same.method(math::max);,it generates the same math (complie above and check javap -c;))
string apppath =
(new System.IO.FileInfo
(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;
Try This
<!DOCTYPE html>
<html>
<head>
<title>Sticky Header and Footer</title>
<style type="text/css">
/* Reset body padding and margins */
body {
margin:0;
padding:0;
}
/* Make Header Sticky */
#header_container {
background:#eee;
border:1px solid #666;
height:60px;
left:0;
position:fixed;
width:100%;
top:0;
}
#header {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/
#container {
margin:0 auto;
overflow:auto;
padding:80px 0;
width:940px;
}
#content {
}
/* Make Footer Sticky */
#footer_container {
background:#eee;
border:1px solid #666;
bottom:0;
height:60px;
left:0;
position:fixed;
width:100%;
}
#footer {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
</style>
</head>
<body>
<!-- BEGIN: Sticky Header -->
<div id="header_container">
<div id="header">
Header Content
</div>
</div>
<!-- END: Sticky Header -->
<!-- BEGIN: Page Content -->
<div id="container">
<div id="content">
content
<br /><br />
blah blah blah..
...
</div>
</div>
<!-- END: Page Content -->
<!-- BEGIN: Sticky Footer -->
<div id="footer_container">
<div id="footer">
Footer Content
</div>
</div>
<!-- END: Sticky Footer -->
</body>
</html>
I understand what you want. You want to check every data of the array if all of it is empty or at least 1 is not empty
Empty array
Array ( [Tags] => SimpleXMLElement Object ( [0] => ) )
Not an Empty array
Array ( [Tags] => SimpleXMLElement Object ( [0] =>,[1] => "s" ) )
I hope I am right. You can use this function to check every data of an array if at least 1 of them has a value.
/*
return true if the array is not empty
return false if it is empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr $key => $value){
if(!empty($value) || $value != NULL || $value != ""){
return true;
break;//stop the process we have seen that at least 1 of the array has value so its not empty
}
}
return false;
}
}
if(is_array_empty($result['Tags'])){
//array is not empty
}else{
//array is empty
}
Hope that helps.
del list
above command worked for me
The easiest way to have a permanent and sustainable solution for the Docker Compose installation and the way to upgrade it, is to just use the package manager pip with:
pip install docker-compose
I was searching for a good solution for the ugly "how to upgrade to the latest version number"-problem, which appeared after you´ve read the official docs - and just found it occasionally - just have a look at the docker-compose pip package - it should reflect (mostly) the current number of the latest released Docker Compose version.
A package manager is always the best solution if it comes to managing software installations! So you just abstract from handling the versions on your own.
If you are using Java 8 then try this using lambda expression and org.apache.commons.lang.StringUtils, that will also clear null
and blank
values from array
input
public static String[] cleanArray(String[] array) {
return Arrays.stream(array).filter(x -> !StringUtils.isBlank(x)).toArray(String[]::new);
}
Awesome tutorial: 3 Different Ways to Display Progress in an ASP.NET AJAX Application
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"
## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
Vanilla JDBC only supports named parameters in a CallableStatement
(e.g. setString("name", name)
), and even then, I suspect the underlying stored procedure implementation has to support it.
An example of how to use named parameters:
//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
+ "if @id is not null "
+ "select * from sysobjects where id = @id "
+ "else if @name is not null "
+ "select * from sysobjects where name = @name "
+ " end");
stmt.execute();
//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
If anyone is still facing this issue, Captor annotation worked for me
@Captor
private ArgumentCaptor<Object> argumentCaptor;
Then I was able to mock the request by:
ResponseEntity<YourTestResponse> testEntity = new ResponseEntity<>(
getTestFactoryResponse(),
HttpStatus.OK);
when(mockRestTemplate.exchange((String) argumentCaptor.capture(),
(HttpMethod) argumentCaptor.capture(),
(HttpEntity<?>) argumentCaptor.capture(),
(Class<YourTestResponse.class>) any())
).thenReturn(testEntity);
iPhone:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25
iPad:
Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25
For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts
) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf
files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.
finish() method is used to finish the activity and remove it from back stack. You can call it in any method in activity. But make sure you close all the Database connections, all reference variables null to prevent any memory leaks.
You can't. It's a browser feature there to prevent sites from showing hundreds of alerts to prevent you from leaving.
You can, however, look into modal popups like jQuery UI Dialog. These are javascript alert boxes that show a custom dialog. They don't use the default alert()
function and therefore, bypass the issue you're running into completely.
I've found that an apps that has a lot of message boxes and confirms has a much better user experience if you use custom dialogs instead of the default alerts and confirms.
It seems that for 32-bit servers there is a JVM limitation that cannot be overcome (unless you find a special 32-bit JVM that does not impose a 2GB limit or less).
This thread on The Server Side has more details including several people who tested out various JVMs on 32-bit architectures. IBM's JVM seems to allow 100 more MB but that's not really going to get you what you want.
http://www.theserverside.com/discussions/thread.tss?thread_id=26347
The "real" solution is to use a 64-bit server with a 64-bit JVM to get heaps larger than 2GB per process. However, it's important to also consider the impact of increasing your address size (not just the addressable space) by using a 64-bit JVM. There will likely be performance and memory impacts for processing using less than 4GB of memory.
Food for thought: do each of these jobs really require 2GB of memory? Is there any way for the jobs to be modified to run within 1.8GB so this limit is not a problem?
The RegExp constructor creates a regular expression object for matching text with a pattern.
var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
str.match(regex);
Above code works perfectly for me...
Too many times I've found ways to solve what you are asking for that, in my opinion are too complicated. For instance you have to define new class types, link library etc. So I decided to write a few lines of code that allow the end user to basically be able to "thread-ize" a "void ::method(void)" of whatever class. For sure this solution I implemented can be extended, improved etc, so, if you need more specific methods or features, add them and please be so kind to keep me in the loop.
Here are 3 files that show what I did.
// A basic mutex class, I called this file Mutex.h
#ifndef MUTEXCONDITION_H_
#define MUTEXCONDITION_H_
#include <pthread.h>
#include <stdio.h>
class MutexCondition
{
private:
bool init() {
//printf("MutexCondition::init called\n");
pthread_mutex_init(&m_mut, NULL);
pthread_cond_init(&m_con, NULL);
return true;
}
bool destroy() {
pthread_mutex_destroy(&m_mut);
pthread_cond_destroy(&m_con);
return true;
}
public:
pthread_mutex_t m_mut;
pthread_cond_t m_con;
MutexCondition() {
init();
}
virtual ~MutexCondition() {
destroy();
}
bool lock() {
pthread_mutex_lock(&m_mut);
return true;
}
bool unlock() {
pthread_mutex_unlock(&m_mut);
return true;
}
bool wait() {
lock();
pthread_cond_wait(&m_con, &m_mut);
unlock();
return true;
}
bool signal() {
pthread_cond_signal(&m_con);
return true;
}
};
#endif
// End of Mutex.h
// The class that incapsulates all the work to thread-ize a method (test.h):
#ifndef __THREAD_HANDLER___
#define __THREAD_HANDLER___
#include <pthread.h>
#include <vector>
#include <iostream>
#include "Mutex.h"
using namespace std;
template <class T>
class CThreadInfo
{
public:
typedef void (T::*MHT_PTR) (void);
vector<MHT_PTR> _threaded_methods;
vector<bool> _status_flags;
T *_data;
MutexCondition _mutex;
int _idx;
bool _status;
CThreadInfo(T* p1):_data(p1), _idx(0) {}
void setThreadedMethods(vector<MHT_PTR> & pThreadedMethods)
{
_threaded_methods = pThreadedMethods;
_status_flags.resize(_threaded_methods.size(), false);
}
};
template <class T>
class CSThread {
protected:
typedef void (T::*MHT_PTR) (void);
vector<MHT_PTR> _threaded_methods;
vector<string> _thread_labels;
MHT_PTR _stop_f_pt;
vector<T*> _elements;
vector<T*> _performDelete;
vector<CThreadInfo<T>*> _threadlds;
vector<pthread_t*> _threads;
int _totalRunningThreads;
static void * gencker_(void * pArg)
{
CThreadInfo<T>* vArg = (CThreadInfo<T> *) pArg;
vArg->_mutex.lock();
int vIndex = vArg->_idx++;
vArg->_mutex.unlock();
vArg->_status_flags[vIndex]=true;
MHT_PTR mhtCalledOne = vArg->_threaded_methods[vIndex];
(vArg->_data->*mhtCalledOne)();
vArg->_status_flags[vIndex]=false;
return NULL;
}
public:
CSThread ():_stop_f_pt(NULL), _totalRunningThreads(0) {}
~CSThread()
{
for (int i=_threads.size() -1; i >= 0; --i)
pthread_detach(*_threads[i]);
for (int i=_threadlds.size() -1; i >= 0; --i)
delete _threadlds[i];
for (int i=_elements.size() -1; i >= 0; --i)
if (find (_performDelete.begin(), _performDelete.end(), _elements[i]) != _performDelete.end())
delete _elements[i];
}
int runningThreadsCount(void) {return _totalRunningThreads;}
int elementsCount() {return _elements.size();}
void addThread (MHT_PTR p, string pLabel="") { _threaded_methods.push_back(p); _thread_labels.push_back(pLabel);}
void clearThreadedMethods() { _threaded_methods.clear(); }
void getThreadedMethodsCount() { return _threaded_methods.size(); }
void addStopMethod(MHT_PTR p) { _stop_f_pt = p; }
string getStatusStr(unsigned int _elementIndex, unsigned int pMethodIndex)
{
char ch[99];
if (getStatus(_elementIndex, pMethodIndex) == true)
sprintf (ch, "[%s] - TRUE\n", _thread_labels[pMethodIndex].c_str());
else
sprintf (ch, "[%s] - FALSE\n", _thread_labels[pMethodIndex].c_str());
return ch;
}
bool getStatus(unsigned int _elementIndex, unsigned int pMethodIndex)
{
if (_elementIndex > _elements.size()) return false;
return _threadlds[_elementIndex]->_status_flags[pMethodIndex];
}
bool run(unsigned int pIdx)
{
T * myElem = _elements[pIdx];
_threadlds.push_back(new CThreadInfo<T>(myElem));
_threadlds[_threadlds.size()-1]->setThreadedMethods(_threaded_methods);
int vStart = _threads.size();
for (int hhh=0; hhh<_threaded_methods.size(); ++hhh)
_threads.push_back(new pthread_t);
for (int currentCount =0; currentCount < _threaded_methods.size(); ++vStart, ++currentCount)
{
if (pthread_create(_threads[vStart], NULL, gencker_, (void*) _threadlds[_threadlds.size()-1]) != 0)
{
// cout <<"\t\tThread " << currentCount << " creation FAILED for element: " << pIdx << endl;
return false;
}
else
{
++_totalRunningThreads;
// cout <<"\t\tThread " << currentCount << " creation SUCCEDED for element: " << pIdx << endl;
}
}
return true;
}
bool run()
{
for (int vI = 0; vI < _elements.size(); ++vI)
if (run(vI) == false) return false;
// cout <<"Number of currently running threads: " << _totalRunningThreads << endl;
return true;
}
T * addElement(void)
{
int vId=-1;
return addElement(vId);
}
T * addElement(int & pIdx)
{
T * myElem = new T();
_elements.push_back(myElem);
pIdx = _elements.size()-1;
_performDelete.push_back(myElem);
return _elements[pIdx];
}
T * addElement(T *pElem)
{
int vId=-1;
return addElement(pElem, vId);
}
T * addElement(T *pElem, int & pIdx)
{
_elements.push_back(pElem);
pIdx = _elements.size()-1;
return pElem;
}
T * getElement(int pId) { return _elements[pId]; }
void stopThread(int i)
{
if (_stop_f_pt != NULL)
{
( _elements[i]->*_stop_f_pt)() ;
}
pthread_detach(*_threads[i]);
--_totalRunningThreads;
}
void stopAll()
{
if (_stop_f_pt != NULL)
for (int i=0; i<_elements.size(); ++i)
{
( _elements[i]->*_stop_f_pt)() ;
}
_totalRunningThreads=0;
}
};
#endif
// end of test.h
// A usage example file "test.cc" that on linux I've compiled with The class that incapsulates all the work to thread-ize a method: g++ -o mytest.exe test.cc -I. -lpthread -lstdc++
#include <test.h>
#include <vector>
#include <iostream>
#include <Mutex.h>
using namespace std;
// Just a class for which I need to "thread-ize" a some methods
// Given that with OOP the objecs include both "functions" (methods)
// and data (attributes), then there is no need to use function arguments,
// just a "void xxx (void)" method.
//
class TPuck
{
public:
bool _go;
TPuck(int pVal):_go(true)
{
Value = pVal;
}
TPuck():_go(true)
{
}
int Value;
int vc;
void setValue(int p){Value = p; }
void super()
{
while (_go)
{
cout <<"super " << vc << endl;
sleep(2);
}
cout <<"end of super " << vc << endl;
}
void vusss()
{
while (_go)
{
cout <<"vusss " << vc << endl;
sleep(2);
}
cout <<"end of vusss " << vc << endl;
}
void fazz()
{
static int vcount =0;
vc = vcount++;
cout <<"Puck create instance: " << vc << endl;
while (_go)
{
cout <<"fazz " << vc << endl;
sleep(2);
}
cout <<"Completed TPuck..fazz instance "<< vc << endl;
}
void stop()
{
_go=false;
cout << endl << "Stopping TPuck...." << vc << endl;
}
};
int main(int argc, char* argv[])
{
// just a number of instances of the class I need to make threads
int vN = 3;
// This object will be your threads maker.
// Just declare an instance for each class
// you need to create method threads
//
CSThread<TPuck> PuckThreadMaker;
//
// Hera I'm telling which methods should be threaded
PuckThreadMaker.addThread(&TPuck::fazz, "fazz1");
PuckThreadMaker.addThread(&TPuck::fazz, "fazz2");
PuckThreadMaker.addThread(&TPuck::fazz, "fazz3");
PuckThreadMaker.addThread(&TPuck::vusss, "vusss");
PuckThreadMaker.addThread(&TPuck::super, "super");
PuckThreadMaker.addStopMethod(&TPuck::stop);
for (int ii=0; ii<vN; ++ii)
{
// Creating instances of the class that I need to run threads.
// If you already have your instances, then just pass them as a
// parameter such "mythreadmaker.addElement(&myinstance);"
TPuck * vOne = PuckThreadMaker.addElement();
}
if (PuckThreadMaker.run() == true)
{
cout <<"All running!" << endl;
}
else
{
cout <<"Error: not all threads running!" << endl;
}
sleep(1);
cout <<"Totale threads creati: " << PuckThreadMaker.runningThreadsCount() << endl;
for (unsigned int ii=0; ii<vN; ++ii)
{
unsigned int kk=0;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
}
sleep(2);
PuckThreadMaker.stopAll();
cout <<"\n\nAfter the stop!!!!" << endl;
sleep(2);
for (int ii=0; ii<vN; ++ii)
{
int kk=0;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl;
}
sleep(5);
return 0;
}
// End of test.cc
The accepted answer by @DavidMills is quite good, but I think it can be improved upon. For one, there is no need to define the ComparisonComparer<T>
class when the framework already includes a static method Comparer<T>.Create(Comparison<T>)
. This method can be used to create an IComparison
on the fly.
Also, it casts IList<T>
to IList
which has the potential to be dangerous. In most cases that I have seen, List<T>
which implements IList
is used behind the scenes to implement IList<T>
, but this is not guaranteed and can lead to brittle code.
Lastly, the overloaded List<T>.Sort()
method has 4 signatures and only 2 of them are implemented.
List<T>.Sort()
List<T>.Sort(Comparison<T>)
List<T>.Sort(IComparer<T>)
List<T>.Sort(Int32, Int32, IComparer<T>)
The below class implements all 4 List<T>.Sort()
signatures for the IList<T>
interface:
using System;
using System.Collections.Generic;
public static class IListExtensions
{
public static void Sort<T>(this IList<T> list)
{
if (list is List<T>)
{
((List<T>)list).Sort();
}
else
{
List<T> copy = new List<T>(list);
copy.Sort();
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparison);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparison);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparer);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparer);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, int index, int count,
IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(index, count, comparer);
}
else
{
List<T> range = new List<T>(count);
for (int i = 0; i < count; i++)
{
range.Add(list[index + i]);
}
range.Sort(comparer);
Copy(range, 0, list, index, count);
}
}
private static void Copy<T>(IList<T> sourceList, int sourceIndex,
IList<T> destinationList, int destinationIndex, int count)
{
for (int i = 0; i < count; i++)
{
destinationList[destinationIndex + i] = sourceList[sourceIndex + i];
}
}
}
Usage:
class Foo
{
public int Bar;
public Foo(int bar) { this.Bar = bar; }
}
void TestSort()
{
IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };
IList<Foo> foos = new List<Foo>()
{
new Foo(1),
new Foo(4),
new Foo(5),
new Foo(3),
new Foo(2),
};
ints.Sort();
foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));
}
The idea here is to leverage the functionality of the underlying List<T>
to handle sorting whenever possible. Again, most IList<T>
implementations that I have seen use this. In the case when the underlying collection is a different type, fallback to creating a new instance of List<T>
with elements from the input list, use it to do the sorting, then copy the results back to the input list. This will work even if the input list does not implement the IList
interface.
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
One of the scenarios I found useful to use CTE is when you want to get DISTINCT rows of data based on one or more columns but return all columns in the table. With a standard query you might first have to dump the distinct values into a temp table and then try to join them back to the original table to retrieve the rest of the columns or you might write an extremely complex partition query that can return the results in one run but in most likelihood, it will be unreadable and cause performance issue.
But by using CTE (as answered by Tim Schmelter on Select the first instance of a record)
WITH CTE AS(
SELECT myTable.*
, RN = ROW_NUMBER()OVER(PARTITION BY patientID ORDER BY ID)
FROM myTable
)
SELECT * FROM CTE
WHERE RN = 1
As you can see, this is much easier to read and maintain. And in comparison to other queries, is much better at performance.
IFNULL
, see here: http://www.sqlite.org/lang_corefunc.html#ifnull
no brackets around the function
If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.
Date.prototype.diffDays = function (date: Date): number {
var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
return (utcThis - utcOther) / 86400000;
};
Test
it('diffDays - Czech DST', function () {
// expect this to parse as local time
// with Czech calendar DST change happened 2012-03-25 02:00
var pre = new Date('2012/03/24 03:04:05');
var post = new Date('2012/03/27 03:04:05');
// regardless DST, you still wish to see 3 days
expect(pre.diffDays(post)).toEqual(-3);
});
Diff minutes or seconds is in same fashion.
We came across many situation where we need to check error and error logs to figure out issue we are facing we can check by possibly following method:
1.) On blank screen Some time we got nothing but blank screen instead of our site or message written The website encountered an unexpected error. Please try again later , so we can Print Errors to the Screen by adding
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
in index.php
at top.;
2.) We should enable optional core module for Database Logging at /admin/build/modules, and then we can check logs your_domain_name/admin/reports/dblog
3.) We can use drush command also to check logs drush watchdog-show it will show recent ten message
or if we want to continue showing logs with more information we can user
drush watchdog-show --tail --full.
4.) Also we can enable core Syslog module this module logs events of operating system of any web server.
I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.
The good news is that selectize.js does exactly this:
Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
When you do : f.readlines()
you already read all the file so f.tell()
will show you that you are in the end of the file, and doing f.next()
will result in a StopIteration
error.
Alternative of what you want to do is:
filne = "D:/testtube/testdkanimfilternode.txt"
with open(filne, 'r+') as f:
for line in f:
if line.startswith("anim "):
print f.next()
# Or use next(f, '') to return <empty string> instead of raising a
# StopIteration if the last line is also a match.
break
I use __get
(and public properties) as much as possible, because they make code much more readable. Compare:
this code unequivocally says what i'm doing:
echo $user->name;
this code makes me feel stupid, which i don't enjoy:
function getName() { return $this->_name; }
....
echo $user->getName();
The difference between the two is particularly obvious when you access multiple properties at once.
echo "
Dear $user->firstName $user->lastName!
Your purchase:
$product->name $product->count x $product->price
"
and
echo "
Dear " . $user->getFirstName() . " " . $user->getLastName() . "
Your purchase:
" . $product->getName() . " " . $product->getCount() . " x " . $product->getPrice() . " ";
Whether $a->b
should really do something or just return a value is the responsibility of the callee. For the caller, $user->name
and $user->accountBalance
should look the same, although the latter may involve complicated calculations. In my data classes i use the following small method:
function __get($p) {
$m = "get_$p";
if(method_exists($this, $m)) return $this->$m();
user_error("undefined property $p");
}
when someone calls $obj->xxx
and the class has get_xxx
defined, this method will be implicitly called. So you can define a getter if you need it, while keeping your interface uniform and transparent. As an additional bonus this provides an elegant way to memorize calculations:
function get_accountBalance() {
$result = <...complex stuff...>
// since we cache the result in a public property, the getter will be called only once
$this->accountBalance = $result;
}
....
echo $user->accountBalance; // calculate the value
....
echo $user->accountBalance; // use the cached value
Bottom line: php is a dynamic scripting language, use it that way, don't pretend you're doing Java or C#.
Building off of the chosen answer and the suggestion to use an alias, I converted it to a function so that passing a directory to list is possible.
# ls, with chmod-like permissions and more.
# @param $1 The directory to ls
function lls {
LLS_PATH=$1
ls -AHl $LLS_PATH | awk "{k=0;for(i=0;i<=8;i++)k+=((substr(\$1,i+2,1)~/[rwx]/) \
*2^(8-i));if(k)printf(\"%0o \",k);print}"
}
First at all i'm seing your code and you haven't any controller. So i suggest that you use a controller.
I think you have to use a controller because your variable {{myStyle}}
isn't compile because the 2 curly brace are visible and they shouldn't.
Second you have to use ng-model for your input, this directive will bind the value of the input to your variable.
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
Improving and Simplifying @Nate's answer:
jQuery.fn.extend({
toggleText: function (a, b){
var that = this;
if (that.text() != a && that.text() != b){
that.text(a);
}
else
if (that.text() == a){
that.text(b);
}
else
if (that.text() == b){
that.text(a);
}
return this;
}
});
Use as:
$("#YourElementId").toggleText('After', 'Before');
I'm not sure if this has been changed, or if it has something to do with which version of PS you're using, but using Andy's example, I can remove the -Name parameter and I still get the value of the reg item:
PS C:\> $key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
PS C:\> (Get-ItemProperty -Path $key).ProgramFilesDir
C:\Program Files
PS C:\> $psversiontable.psversion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
Here are a few ways to create a list with N of continuous natural numbers starting from 1.
1 range:
def numbers(n):
return range(1, n+1);
2 List Comprehensions:
def numbers(n):
return [i for i in range(1, n+1)]
You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!
The copyright notice on a work establishes a claim to copyright. The date on the notice establishes how far back the claim is made. This means if you update the date, you are no longer claiming the copyright for the original date and that means if somebody has copied the work in the meantime and they claim its theirs on the ground that their publishing the copy was before your claim, then it will be difficult to establish who is the originator of the work.
Therefore, if the claim is based on common law copyright (not formally registered), then the date should be the date of first publication. If the claim is a registered copyright, then the date should be the date claimed in the registration. In cases where the work was substantially revised you may establish a new copyright claim to the revised work by adding another copyright notice with a newer date or by adding an additional date to the existing notice as in "© 2000, 2010". Again, the added date establishes how far back the claim is made on the revision.
Step1:
Go to cordova\platforms\android
ant create a fille called ant.properties
file with the keystore file info (this keystore can be generated from your favorite Android SDK, studio...):
key.store=C:\\yourpath\\Yourkeystore.keystore
key.alias=youralias
Step2:
Go to cordova path and execute:
cordova build android --release
Note: You will be prompted asking your keystore and key password
An YourApp-release.apk will appear in \cordova\platforms\android\ant-build
isset($_POST['fromPerson'])
Insert this code in your .htaccess file. And it should work
RewriteCond %{HTTP_HOST} yourDomainName\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourDomainName.com/$1 [R,L]
I had the same problem. I fixed it by makinbg the following entry in org.eclipse.wst.common.project.facet.core.xml
<runtime name="Apache Tomcat v7.0" />
Now this complete file looks like -
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="Apache Tomcat v7.0" />
<fixed facet="wst.jsdt.web" />
<installed facet="java" version="1.5" />
<installed facet="jst.web" version="2.3" />
<installed facet="wst.jsdt.web" version="1.0" />
</faceted-project>
For showing result of batch file in text file, you can use
this command
chdir > test.txt
This command will redirect result to test.txt.
When you open test.txt you will found current path of directory in test.txt
I had the same problem and i saw waruna manjula giving the best answer. However writing it all down on the console is not what you might want. To get string off al info use the following
Step one: declare values at begin
//drive 1
public static string drivename = "";
public static string drivetype = "";
public static string drivevolumelabel = "";
public static string drivefilesystem = "";
public static string driveuseravailablespace = "";
public static string driveavailablespace = "";
public static string drivetotalspace = "";
//drive 2
public static string drivename2 = "";
public static string drivetype2 = "";
public static string drivevolumelabel2 = "";
public static string drivefilesystem2 = "";
public static string driveuseravailablespace2 = "";
public static string driveavailablespace2 = "";
public static string drivetotalspace2 = "";
//drive 3
public static string drivename3 = "";
public static string drivetype3 = "";
public static string drivevolumelabel3 = "";
public static string drivefilesystem3 = "";
public static string driveuseravailablespace3 = "";
public static string driveavailablespace3 = "";
public static string drivetotalspace3 = "";
Step 2: actual code
DriveInfo[] allDrives = DriveInfo.GetDrives();
int drive = 1;
foreach (DriveInfo d in allDrives)
{
if (drive == 1)
{
drivename = String.Format("Drive {0}", d.Name);
drivetype = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 2;
}
else if (drive == 2)
{
drivename2 = String.Format("Drive {0}", d.Name);
drivetype2 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel2 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem2 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace2 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace2 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace2 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 3;
}
else if (drive == 3)
{
drivename3 = String.Format("Drive {0}", d.Name);
drivetype3 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel3 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem3 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace3 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace3 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace3 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 4;
}
if (drive == 4)
{
drive = 1;
}
}
//part 2: possible debug - displays in output
//drive 1
Console.WriteLine(drivename);
Console.WriteLine(drivetype);
Console.WriteLine(drivevolumelabel);
Console.WriteLine(drivefilesystem);
Console.WriteLine(driveuseravailablespace);
Console.WriteLine(driveavailablespace);
Console.WriteLine(drivetotalspace);
//drive 2
Console.WriteLine(drivename2);
Console.WriteLine(drivetype2);
Console.WriteLine(drivevolumelabel2);
Console.WriteLine(drivefilesystem2);
Console.WriteLine(driveuseravailablespace2);
Console.WriteLine(driveavailablespace2);
Console.WriteLine(drivetotalspace2);
//drive 3
Console.WriteLine(drivename3);
Console.WriteLine(drivetype3);
Console.WriteLine(drivevolumelabel3);
Console.WriteLine(drivefilesystem3);
Console.WriteLine(driveuseravailablespace3);
Console.WriteLine(driveavailablespace3);
Console.WriteLine(drivetotalspace3);
I want to note that you can just make all the console writelines comment code, but i thought it would be nice for you to test it. If you display all these after each other you get the same list as waruna majuna
Drive C:\ Drive type: Fixed Volume label: File system: NTFS Available space to current user: 134880153600 bytes Total available space: 134880153600 bytes Total size of drive: 499554185216 bytes
Drive D:\ Drive type: CDRom
Drive H:\ Drive type: Fixed Volume label: HDD File system: NTFS Available space to current user: 2000010817536 bytes Total available space: 2000010817536 bytes Total size of drive: 2000263573504 bytes
However you can now acces all of the loose information at strings
There is a C# wrapper for that which is open source, hosted on Codeplex called Web Image Cropping
Register the control
<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>
Resizing
<asp:Image ID="Image1" runat="server" ImageUrl="images/328.jpg" />
<cs:CropImage ID="wci1" runat="server" Image="Image1"
X="10" Y="10" X2="50" Y2="50" />
Cropping in code behind - Call Crop method when button clicked for example;
wci1.Crop(Server.MapPath("images/sample1.jpg"));
Use this:
return this.RedirectToAction<AccountController>(m => m.LogIn());
You can find information on this page:
http://www.mkyong.com/java/java-properties-file-examples/
Properties prop = new Properties();
try {
//load a properties file from class path, inside static method
prop.load(App.class.getClassLoader().getResourceAsStream("config.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
}
catch (IOException ex) {
ex.printStackTrace();
}
In your controller, add,
public function create()
{
$items = array(
'itemlist' => DB::table('itemtable')->get()
);
return view('prices.create', $items);
}
And in your view, use
<select name="categories" id="categories" class="form-control">
@foreach($itemlist as $item)
<option value="{{ $item->id }}">{{ $item->name }}</option>
@endforeach
</select>
In select box, it will be like this,
<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
...
</select>
Borrowing from @Khan's answer, I would do:
IF OBJECT_ID('dbo.test_abc_def', 'V') IS NOT NULL
DROP VIEW dbo.test_abc_def
GO
CREATE VIEW dbo.test_abc_def AS
SELECT
VCV.xxxx
,VCV.yyyy AS yyyy
,VCV.zzzz AS zzzz
FROM TABLE_A
Because Convert.ToInt32
rounds:
Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
...while the cast truncates:
When you convert from a double or float value to an integral type, the value is truncated.
Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score
is a real number as is the case here).
Try this one
string redirect = "<script>window.open('http://www.google.com');</script>";
Response.Write(redirect);
Here is a work around I found if you want to only shuffle a subset of the DataFrame:
shuffle_to_index = 20
df = pd.concat([df.iloc[np.random.permutation(range(shuffle_to_index))], df.iloc[shuffle_to_index:]])
For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You'll immediately see the red circle with a cross in it on the failing line. It's a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.
In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.
http://chromedriver.storage.googleapis.com/index.html?path=2.24/
It is working for me in Win7 64 bit.
Here are two functions that don't introduce a temporary string, which could be useful when needles are substantially big:
function startsWith($haystack, $needle)
{
return strncmp($haystack, $needle, strlen($needle)) === 0;
}
function endsWith($haystack, $needle)
{
return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
You can start by reading the documentation.
Here is a link:
How to change the launcher logo of an app in Android Studio?
If additional table doesn't fit, you can write your own function for translation.
The plus of sql function over case is, that you can use it in various places, and keep translation logic in one place.
I assume you are meaning "internally" within your application.
you can create your own <a>
tag and insert a url in the href like this
<a href="<?php echo site_url('controller/function/uri') ?>">Link</a>
OR you can use the URL helper this way to generate an <a>
tag
anchor(uri segments, text, attributes)
So... to use it...
<?php echo anchor('controller/function/uri', 'Link', 'class="link-class"') ?>
and that will generate
<a href="http://domain.com/index.php/controller/function/uri" class="link-class">Link</a>
For the additional commented question
I would use my first example
so...
<a href="<?php echo site_url('controller/function') ?>"><img src="<?php echo base_url() ?>img/path/file.jpg" /></a>
for images (and other assets) I wouldn't put the file path within the php, I would just echo the base_url() and then add the path normally.
grep -nr "search string" directory
This gives you the line with the line number.
I would like to add more details to Stan's answer #2 for below reasons:
I faced this issue myself more than dozen times and depending on project conditions, I chose between stan's voodoo magic answer #1 or #2. When I kept on facing it again, I become more inquistive that why it happens in first place.
I'd like to add answer for Mac users too.
There are limitations with both these possible answers:
It may happen due to any of the below reasons:
Operating system not allocating system resources to the Excel process. (Solution: One needs to just start the operating system - success rate is very low but has known to work many times)
P-code is the intermediate code that was used in Visual Basic (before .NET) and hence it is still used in the VBA. It enabled a more compact executable at the expense of slower execution. Why I am talking about p-code? Because it gets corrupted sometimes between multiple executions and large files or just due to installation of the software (Excel) went corrupt somewhere. When p-code corrupts. the code execution keeps getting interrupted. Solution: In these cases, it is assumed that your code has started to corrupt and chances in future are that your Excel workbook also get corrupt giving you messages like "excel file corrupted and cannot be opened". Hence, as a quick solution, you can rely on answer #1 or answer #2 as per your requirements. However, never ignore the signs of corruption. It's better to copy your code modules in notepad, delete the modules, save & close the workbook, close the excel. Now, re-open the workbook and start creating new modules with the code copied earlier to notepad.
Mac users, try any of the below option and of them will definitely work depending on your system architecture i.e. OS and Office version
You will be put into break mode using the above key combinations as the macro suspends execution immediately finishing the current task. This is replacement of Step 2.
xlErrorHandler
along with Resume
statement in the Error Handler if the error code is 18. Then, the interrupt is sent to the running procedure as an error, trappable by an error handler set up with an On Error GoTo statement. The trappable error code is 18. The current procedure is interrupted, and the user can debug or end the procedure. Microsoft gives caution that do not use this if your error handler has resume statement else your error handler always returns to the same statement. That's exactly we want in unwanted meaningless interruptions of code execution.if the entity contains a lot of entries the best way is like this because it saves memory
- (void)deleteAll:(NSManagedObjectContext *)managedObjectContext entityName:(NSString *)entityName
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[managedObjectContext setUndoManager:nil];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setIncludesPropertyValues:NO];
[fetchRequest setFetchLimit:100]; // you can change this number if you want
NSError *error;
NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
while ([items count] > 0) {
@autoreleasepool {
for (NSManagedObject *item in items) {
[managedObjectContext deleteObject:item];
}
if (![managedObjectContext save:&error]) {
NSLog(@"Error deleting %@ - error:%@",self.entityName, error);
}
}
items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
}
}
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
EclipseLink provided an annotation (e.g. @Index) to define an index on columns. There is an example of its use. Part of the example is included...
The firstName and lastName fields are indexed, together and individually.
@Entity
@Index(name="EMP_NAME_INDEX", columnNames={"F_NAME","L_NAME"}) // Columns indexed together
public class Employee{
@Id
private long id;
@Index // F_NAME column indexed
@Column(name="F_NAME")
private String firstName;
@Index // L_NAME column indexed
@Column(name="L_NAME")
private String lastName;
...
}
This will do:
#include <fstream>
#include <iostream>
using std::fstream;
int main(int argc, char *argv[]) {
fstream file;
file.open("test.txt",std::ios::out);
file << fflush;
file.close();
}
export ROOT_DIR=<path/value>
Then use the variable, $(ROOT_DIR)
in the Makefile.
In the management studio diagram choose the table, right click to add new column if desired, right-click on the column and choose "Check Constraints", there you can add one.
Arrays are non-negative integer indexed , so maximum array size you can access would be Integer.MAX_VALUE
. The other thing is how big array you can create. It depends on the maximum memory available to your JVM
and the content type of the array. Each array element has it's size, example. byte = 1 byte
, int = 4 bytes
, Object reference = 4 bytes (on a 32 bit system)
So if you have 1 MB
memory available on your machine, you could allocate an array of byte[1024 * 1024]
or Object[256 * 1024]
.
Answering your question - You can allocate an array of size (maximum available memory / size of array item).
Summary - Theoretically the maximum size of an array will be Integer.MAX_VALUE
. Practically it depends on how much memory your JVM
has and how much of that has already been allocated to other objects.
For port 80, the command would be : netstat -an | find "80" For port n, the command would be : netstat -an | find "n"
Here, netstat is the instruction to your machine
-a : Displays all connections and listening ports -n : Displays all address and instructions in numerical format (This is required because output from -a can contain machine names)
Then, a find command to "Pattern Match" the output of previous command.
gitk --all
You can either
fig, ax = plt.subplots() #create figure and axes
candlestick(ax, quotes, ...)
or
candlestick(plt.gca(), quotes) #get the axis when calling the function
The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot
For others like me that happen upon this very old question, a modern solution:
const roundValue = (num, decimals = 2) => {
let scaling = 10 ** decimals;
return Math.round((num + Number.EPSILON) * scaling) / scaling;
}
As mentioned in other people's comments, the top solution given here was not working for me in Ansible 2.2, particularly when also using with_items
.
It appears that OP's intended approach does work now with a slight change to the quoting of item
.
- set_fact: something="{{ something + [ item ] }}"
with_items:
- one
- two
- three
And a longer example where I've handled the initial case of the list being undefined and added an optional when
because that was also causing me grief:
- set_fact: something="{{ something|default([]) + [ item ] }}"
with_items:
- one
- two
- three
when: item.name in allowed_things.item_list
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
First make sure that mysql gem is installed, if not? than type following command in your console
gem install mysql2
Than create new rails app and set mysql database as default database by typing following command in your console
rails new app-name -d mysql
Try to modify your eclipse.ini with below
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20120913-144807
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Dhelp.lucene.tokenizer=standard
-Xms2G
-Xmx3G
-XX:MaxPermSize=2G
-XX:+UseCompressedOops
-XX:+UseParallelGC
Once you open your eclipse you can try below
Looks like your application consumes more memory than allocated (Default). I will try two things
As suggested by Harmlezz increase your memory allocation to JVM to -Xms2g -Xmx2g (If needed increase it more and try it out)
Download eclipse memory analyzer and check for what causing memory leak OR even you can use JConsole to see JVM memory utilization in order to figure out application memory leak issue.
try use keyup.enter or keydown.enter
<button type="submit" (keyup.enter)="search(...)">Search</button>
Consider using <span>
to isolate small segments of markup to be styled without breaking up layout. This would seem to be more idiomatic than trying to force a <div>
not to display itself--if in fact the checkbox itself cannot be styled in the way you want.
Using awk for it. Test files:
$ cat a.txt
one
two
three
four
four
$ cat b.txt
three
two
one
The awk:
$ awk '
NR==FNR { # process b.txt or the first file
seen[$0] # hash words to hash seen
next # next word in b.txt
} # process a.txt or all files after the first
!($0 in seen)' b.txt a.txt # if word is not hashed to seen, output it
Duplicates are outputed:
four
four
To avoid duplicates, add each newly met word in a.txt to seen
hash:
$ awk '
NR==FNR {
seen[$0]
next
}
!($0 in seen) { # if word is not hashed to seen
seen[$0] # hash unseen a.txt words to seen to avoid duplicates
print # and output it
}' b.txt a.txt
Output:
four
If the word lists are comma-separated, like:
$ cat a.txt
four,four,three,three,two,one
five,six
$ cat b.txt
one,two,three
you have to do a couple of extra laps (for
loops):
awk -F, ' # comma-separated input
NR==FNR {
for(i=1;i<=NF;i++) # loop all comma-separated fields
seen[$i]
next
}
{
for(i=1;i<=NF;i++)
if(!($i in seen)) {
seen[$i] # this time we buffer output (below):
buffer=buffer (buffer==""?"":",") $i
}
if(buffer!="") { # output unempty buffers after each record in a.txt
print buffer
buffer=""
}
}' b.txt a.txt
Output this time:
four
five,six
You may also find a global .gitignore directly at the ~ path if you haven't created it in your folder project. This file is taken into account by all your .git projects.
You use runas
to launch a program as a specific user:
runas /user:Administrator Example1Server.exe
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this
$("#panel").toggle().toggle();
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
Rollback-and-reapply is realy simple solution, but it can help only with the last commit. Mercurial Queues is much more powerful thing (note that you need to enable Mercurial Queues Extension in order to use "hg q*" commands).
I tested the following batch file on Windows 7 x64/x86 and Windows XP x86 and it's fine, but I haven't tried Windows XP x64 yet, but this will probably work:
If Defined ProgramW6432 (Do x64 stuff or end if you are aiming for x86) else (Do x86 stuff or end if you are aiming for x64)
The simplest fix is to make the comparator function be static:
static int comparator (const Bar & first, const Bar & second);
^^^^^^
When invoking it in Count
, its name will be Foo::comparator
.
The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo
.
Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo
.
Actually, there is one that works flawlessly:
display: flex; flex-direction: column;
as long as you can live with supporting only IE10 and up
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
background: #ddd;_x000D_
width: 15em;_x000D_
}_x000D_
_x000D_
.square {_x000D_
margin: 15px;_x000D_
height: 3em;_x000D_
background: yellow;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
</div>_x000D_
<div class="container">_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
</div>
_x000D_
This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.
To keep the text which falls between the equal sign and the comma:
-replace "^.*?=(.*?),.*?$",'$1'
This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
The rouine is pretty good, however it causes my app to hang, so I needed to add the case:
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<xsl:value-of select="$text" />
<!-- Prevent thsi routine from hanging -->
</xsl:when>
before the function gets called recursively.
I got the answer from here: When test hanging in an infinite loop
Thank you!
Use this and form the query
SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.TABLES where table_schema in (db1,db2)
INTO OUTFILE '/path/to/file.sql';
Now use this to use this query
mysql -u username -p </path/to/file.sql
if you get an error like this
ERROR 1701 (42000) at line 3: Cannot truncate a table referenced in a foreign key constraint
the easiest way to go through is at the top of your file add this line
SET FOREIGN_KEY_CHECKS=0;
which says that we don't want to check the foreign key constraints while going through this file.
It will truncate all tables in databases db1 and bd2.
C has 'for' and 'while' keywords. If a foreach statement in a language like C# looks like this ...
foreach (Element element in collection)
{
}
... then the equivalent of this foreach statement in C might be be like:
for (
Element* element = GetFirstElement(&collection);
element != 0;
element = GetNextElement(&collection, element)
)
{
//TODO: do something with this element instance ...
}
Solution with Jquery
$(window).resize(function () {
var width = $("#map").width();
$("#map").height(width * 1.72);
});
Array
subscript with rangeWith Swift 5, when you write…
let newNumbers = numbers[0...position]
… newNumbers
is not of type Array<Int>
but is of type ArraySlice<Int>
. That's because Array
's subscript(_:?)
returns an ArraySlice<Element>
that, according to Apple, presents a view onto the storage of some larger array.
Besides, Swift also provides Array
an initializer called init(_:?)
that allows us to create a new array from a sequence
(including ArraySlice
).
Therefore, you can use subscript(_:?)
with init(_:?)
in order to get a new array from the first n elements of an array:
let array = Array(10...14) // [10, 11, 12, 13, 14]
let arraySlice = array[0..<3] // using Range
//let arraySlice = array[0...2] // using ClosedRange also works
//let arraySlice = array[..<3] // using PartialRangeUpTo also works
//let arraySlice = array[...2] // using PartialRangeThrough also works
let newArray = Array(arraySlice)
print(newArray) // prints [10, 11, 12]
Array
's prefix(_:)
methodSwift provides a prefix(_:)
method for types that conform to Collection
protocol (including Array
). prefix(_:)
has the following declaration:
func prefix(_ maxLength: Int) -> ArraySlice<Element>
Returns a subsequence, up to maxLength in length, containing the initial elements.
Apple also states:
If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.
Therefore, as an alternative to the previous example, you can use the following code in order to create a new array from the first elements of another array:
let array = Array(10...14) // [10, 11, 12, 13, 14]
let arraySlice = array.prefix(3)
let newArray = Array(arraySlice)
print(newArray) // prints [10, 11, 12]
Async arrow functions look like this:
const foo = async () => {
// do something
}
Async arrow functions look like this for a single argument passed to it:
const foo = async evt => {
// do something with evt
}
Async arrow functions look like this for multiple arguments passed to it:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
The anonymous form works as well:
const foo = async function() {
// do something
}
An async function declaration looks like this:
async function foo() {
// do something
}
Using async function in a callback:
const foo = event.onCall(async () => {
// do something
})
Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:
The following program would determine that:
#include <stdio.h>
#include <stdint.h>
int is_big_endian(void)
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
int main(void)
{
printf("System is %s-endian.\n",
is_big_endian() ? "big" : "little");
return 0;
}
You also have this approach; from Quake II:
byte swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
bigendien = false;
And !is_big_endian()
is not 100% to be little as it can be mixed/middle.
Believe this can be checked using same approach only change value from 0x01000000
to i.e. 0x01020304
giving:
switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE
But not entirely sure about that one ...
The values of list can be changed any time but the values of tuples can't be change.
The advantages and disadvantages depends upon the use. If you have such a data which you never want to change then you should have to use tuple, otherwise list is the best option.
Try this Query
select NUM, count(1) as count
from tbl
where num = 1
group by NUM
--having count(1) (You condition)
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n)
is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange()
was renamed to range()
- if you want a list, you have to specifically request it via list(range(n))
.
The code:
public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
The output of java Test abcdef
:
last character: f
You can try the cases
env in amsmath.
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
f(x)=\begin{cases}
1, & \text{if $x<0$}.\\
0, & \text{otherwise}.
\end{cases}
\end{equation}
\end{document}
Try this
$(this).datepicker("destroy").datepicker({
changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy", showOn: "focus", yearRange: "-5:+10"
}).focus();
You want to create a "Dynamic Web Project". Follow the steps here: Spring MVC Tutorial with Eclipse and Tomcat.
Also, here is the Eclipse documentation for Dynamic Web Projects: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.webtools.doc.user/topics/ccwebprj.html
An example usage:
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.
This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray
:
>>> s = bytearray(1000000) # a million zeroed bytes
>>> t = buffer(s, 1) # slice cuts off the first byte
>>> s[1] = 5 # set the second element in s
>>> t[0] # which is now also the first element in t!
'\x05'
This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.
Note that buffer
has been replaced by the better named memoryview
in Python 3, though you can use either in Python 2.7.
Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.
Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.
From the Oracle 10g SQL Reference:
Notes on Updatable Views
An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.
To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:
In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.
If you want a join view to be updatable, then all of the following conditions must be true:
the prime number method is very clear here . P[] is a list of prime number less than or equal the sq = sqrt(n) ;
for (int i = 0 ; i < size && P[i]<=sq ; i++){
nd = 1;
while(n%P[i]==0){
n/=P[i];
nd++;
}
count*=nd;
if (n==1)break;
}
if (n!=1)count*=2;//the confusing line :D :P .
i will lift the understanding for the reader .
i now look forward to a method more optimized .
Sequence to follow
$ heroku login
$ ssh-keygen -t rsa
$ heroku keys:add
When executing second statement it would ask for input, just press Enter(return) three times and a key will be added.
You don't need to set name , just giving an id is enough.
<input type="hidden" id="testId" />
and than with jquery you can use 'val()' method like below:
$('#testId').val("work");
from IPython.display import display
display(df) # OR
print df.to_html()
I know its 3 years too late, but maybe it can help someone else because I haven't found anything like that except for the moment-timezone library, which is not exactly the same as what he's asking for here.
I've done something similar for german timezone, this is a little complex because of daylight saving time and leap years where you have 366 days.
it might need a little work with the "isDaylightSavingTimeInGermany" function while different timezones change on different times the daylight saving time.
anyway, check out this page: https://github.com/zerkotin/german-timezone-converter/wiki
the main methods are: convertLocalDateToGermanTimezone convertGermanDateToLocalTimezone
I've put an effort into documenting it, so it won't be so confusing.
Check out this post
According to it
No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
A single element in a JavaScript String is considered to be a single UTF-16 code unit. That is to say, Strings characters are stored in 16-bit (1 code unit), and 16-bit is equal to 2 bytes (8-bit = 1 byte).
The charCodeAt()
method can be used to return an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
The codePointAt()
can be used to return the entire code point value for Unicode characters, e.g. UTF-32.
When a UTF-16 character can't be represented in a single 16-bit code unit, it will have a surrogate pair and therefore use two code units( 2 x 16-bit = 4 bytes)
See Unicode encodings for different encodings and their code ranges.
Figure out the full file path to the assembly you're trying to work with
Press the start button, type "dev". Launch the program called "Developer Command Prompt for VS 2017"
In the window that opens, type dumpbin /dependents [path]
, where [path]
is the path you figured out in step 1
press the enter key
Bam, you've got your dependency information. The window should look like this:
Update for VS 2019: you need this package in your VS installation:
Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.
Android code - Main.java
package test12.tt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test12Activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt1 = (TextView) findViewById(R.id.sm);
new Thread(new Runnable() {
public void run(){
txt1.setText("Thread!!");
}
}).start();
}
}
Android application xml - main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id = "@+id/sm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
Generally, I think your USB connection should be set to use MTP (Media Transfer), however, I couldn't get my computer to recognize my device (Nexus 4). Oddly, setting the USB connection to Camera got it working for me.
PyCryptodome is an almost-compatible fork of PyCrypto with Windows wheels available on pypi.
You can install it with a simple:
pip install pycryptodome
The website includes instructions to build it from sources with the Microsoft compilers too.
Regarding conventions in C#. Let's say you're reading a cell that contains a date, e.g. 2014-10-22.
When using:
.Text
, you'll get the formatted representation of the date, as seen in the workbook on-screen:
2014-10-22. This property's type is always string
but may not always return a satisfactory result.
.Value
, the compiler attempts to convert the date into a DateTime
object: {2014-10-22 00:00:00} Most probably only useful when reading dates.
.Value2
, gives you the real, underlying value of the cell. In the case for dates, it's a date serial: 41934. This property can have a different type depending on the contents of the cell. For date serials though, the type is double
.
So you can retrieve and store the value of a cell in either dynamic
, var
or object
but note that the value will always have some sort of innate type that you will have to act upon.
dynamic x = ws.get_Range("A1").Value2;
object y = ws.get_Range("A1").Value2;
var z = ws.get_Range("A1").Value2;
double d = ws.get_Range("A1").Value2; // Value of a serial is always a double
<div></div>
div {
display: table;
margin-right: auto;
margin-left: auto;
}
update 4.0.0
See Angular docs for more details https://angular.io/guide/router#fetch-data-before-navigating
original
Using a service is the way to go. In route params you should only pass data that you want to be reflected in the browser URL bar.
See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
The router shipped with RC.4 re-introduces data
constructor(private route: ActivatedRoute) {}
const routes: RouterConfig = [
{path: '', redirectTo: '/heroes', pathMatch : 'full'},
{path : 'heroes', component : HeroDetailComponent, data : {some_data : 'some value'}}
];
class HeroDetailComponent {
ngOnInit() {
this.sub = this.route
.data
.subscribe(v => console.log(v));
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
See also the Plunker at https://github.com/angular/angular/issues/9757#issuecomment-229847781
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DBDemo2
{
public partial class Form1 : Form
{
string connectionString = "Database=company;Uid=sa;Pwd=mypassword";
System.Data.SqlClient.SqlConnection connection;
System.Data.SqlClient.SqlCommand command;
SqlParameter idparam = new SqlParameter("@eid", SqlDbType.Int, 0);
SqlParameter nameparam = new SqlParameter("@name", SqlDbType.NChar, 20);
SqlParameter addrparam = new SqlParameter("@addr", SqlDbType.NChar, 10);
public Form1()
{
InitializeComponent();
connection = new System.Data.SqlClient.SqlConnection(connectionString);
connection.Open();
command = new System.Data.SqlClient.SqlCommand(null, connection);
command.CommandText = "insert into employee(ename, city) values(@name, @addr);select SCOPE_IDENTITY();";
command.Parameters.Add(nameparam);
command.Parameters.Add(addrparam);
command.Prepare();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
int id = Int32.Parse(textBoxID.Text);
String name = textBoxName.Text;
String address = textBoxAddress.Text;
command.Parameters[0].Value = name;
command.Parameters[1].Value = address;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
int nid = Convert.ToInt32(reader[0]);
MessageBox.Show("ID : " + nid);
}
/*int af = command.ExecuteNonQuery();
MessageBox.Show(command.Parameters["ID"].Value.ToString());
*/
}
catch (NullReferenceException ne)
{
MessageBox.Show("Error is : " + ne.StackTrace);
}
catch (Exception ee)
{
MessageBox.Show("Error is : " + ee.StackTrace);
}
}
private void buttonSave_Leave(object sender, EventArgs e)
{
}
private void Form1_Leave(object sender, EventArgs e)
{
connection.Close();
}
}
}
I have found that if the view model contains many div bindings the best way to clear the ko.applyBindings(new someModelView);
is to use: ko.cleanNode($("body")[0]);
This allows you to call a new ko.applyBindings(new someModelView2);
dynamically without the worry of the previous view model still being binded.
Besides LocalBroadcastManager , Event Bus and Messenger already answered in this question,we can use Pending Intent to communicate from service.
As mentioned here in my blog post
Communication between service and Activity can be done using PendingIntent.For that we can use createPendingResult().createPendingResult() creates a new PendingIntent object which you can hand to service to use and to send result data back to your activity inside onActivityResult(int, int, Intent) callback.Since a PendingIntent is Parcelable , and can therefore be put into an Intent extra,your activity can pass this PendingIntent to the service.The service, in turn, can call send() method on the PendingIntent to notify the activity via onActivityResult of an event.
Activity
public class PendingIntentActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PendingIntent pendingResult = createPendingResult( 100, new Intent(), 0); Intent intent = new Intent(getApplicationContext(), PendingIntentService.class); intent.putExtra("pendingIntent", pendingResult); startService(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 100 && resultCode==200) { Toast.makeText(this,data.getStringExtra("name"),Toast.LENGTH_LONG).show(); } super.onActivityResult(requestCode, resultCode, data); } }
Service
public class PendingIntentService extends Service { private static final String[] items= { "lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus" }; private PendingIntent data; @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { data = intent.getParcelableExtra("pendingIntent"); new LoadWordsThread().start(); return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); } class LoadWordsThread extends Thread { @Override public void run() { for (String item : items) { if (!isInterrupted()) { Intent result = new Intent(); result.putExtra("name", item); try { data.send(PendingIntentService.this,200,result); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); } SystemClock.sleep(400); } } } } }
A simpler method that answers the original question "How to use local docker images with Minikube?", is to save the image to a tar file and load it into minikube:
# export the docker image to a tar file
docker save --output my-image.tar the.full.path.to/the/docker/image:the-tag
# set local environment variables so that docker commands go to the docker in minikube
eval $(minikube docker-env)
# or if on windows: @FOR /f "tokens=*" %i IN ('minikube docker-env') DO @%i
# import the docker image from the tar file into minikube
docker load --input my-image.tar
# cleanup - put docker back to normal
eval $(minikube docker-env -u)
# or if on windows: @FOR /f "tokens=*" %i IN ('minikube docker-env -u') DO @%i
Then running the image involves a command like the following. Make sure to include the "--image-pull-policy=Never" parameter.
kubectl run my-image --image=the.full.path.to/the/docker/image:the-tag --image-pull-policy=Never --port=80
Generic Collection classes cant be used with primitives. Use the Character and Integer wrapper classes instead.
Map<Character , Integer > checkSum = new HashMap<Character, Integer>();
The only thing that worked for me is deleting the project and then importing it again. Works like a charm :)
I have the similar problem and fixed it by temporarily disabling my antivirus(Kaspersky Free 18.0.0.405). This AV has HTTPS interception module that automatically self-sign all certificates it finds in HTTPS responses.
Wget from Cygwin does not know anything about AV root certificate, so when it finds that website's certificate was signed with non trust certificate it prints that error.
To fix this permanently without disabling AV you should copy the AV root certificate from Windows certificate store to /etc/pki/ca-trust/source/anchors
as .pem file(base64 encoding) and run update-ca-trust
This prints the number of processes whose basename is "chromium-browser":
ps -e -o args= | awk 'BEGIN{c=0}{
if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"
If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.
Tested using gwak
as the awk
alternative in Linux.
Here is a more versatile solution with some example usage:
#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
local quiet=1;
shift
else
local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
name=$2
if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}
process='chromium-browser'
printf "Process \"${process}\" is "
if isProcessRunning -q "$process"
then printf "running.\n"
else printf "not running.\n"; fi
printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"
You can also do the following if you really don't want to initialise it.
makes?: any[];
You can use bash. Note for very large files in terms of GB, use awk/wc
. However it should still be manageable in performance for files with a few MB.
declare -i count=0
while read
do
((count++))
done < file
echo "line count: $count"
If you're not locked on MySQL you can switch to PostgreSQL. It supports JavaScript procedures (PL/V8) inside the database. It is very fast and powerful. Checkout this post.
I still like Source Insight a lot, but I'm hesitant to recommend it anymore as I'm not sure anybody's still maintaining it. They released a very minor update back in March but haven't had a major release in years. And there seems to be no web community presence. It's a shame because I still like its auto-completion-friendly file open and symbol browsing panels (as well as syntax formatting) better than anything else I've ever used.
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
If you use a context manager, the file is closed automatically for you
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
If you're using Python2.6 or higher, it's preferred to use str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
For python2.7 and higher you can use {}
instead of {0}
In Python3, there is an optional file
parameter to the print
function
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduced f-strings for another alternative
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
You do not need any external command at all, just use Parameter Expansion in bash:
hostname=aaa0.bbb.ccc
echo ${hostname%%.*}
OS independence is critical for me, so mkdir -p
is not an option. I created this series of functions that use eval
to create directory targets with the prerequisite on the parent directory. This has the benefit that make -j 2
will work without issue since the dependencies are correctly determined.
# convenience function for getting parent directory, will eventually return ./
# $(call get_parent_dir,somewhere/on/earth/) -> somewhere/on/
get_parent_dir=$(dir $(patsubst %/,%,$1))
# function to create directory targets.
# All directories have order-only-prerequisites on their parent directories
# https://www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html#Prerequisite-Types
TARGET_DIRS:=
define make_dirs_recursively
TARGET_DIRS+=$1
$1: | $(if $(subst ./,,$(call get_parent_dir,$1)),$(call get_parent_dir,$1))
mkdir $1
endef
# function to recursively get all directories
# $(call get_all_dirs,things/and/places/) -> things/ things/and/ things/and/places/
# $(call get_all_dirs,things/and/places) -> things/ things/and/
get_all_dirs=$(if $(subst ./,,$(dir $1)),$(call get_all_dirs,$(call get_parent_dir,$1)) $1)
# function to turn all targets into directories
# $(call get_all_target_dirs,obj/a.o obj/three/b.o) -> obj/ obj/three/
get_all_target_dirs=$(sort $(foreach target,$1,$(call get_all_dirs,$(dir $(target)))))
# create target dirs
create_dirs=$(foreach dirname,$(call get_all_target_dirs,$1),$(eval $(call make_dirs_recursively,$(dirname))))
TARGETS := w/h/a/t/e/v/e/r/things.dat w/h/a/t/things.dat
all: $(TARGETS)
# this must be placed after your .DEFAULT_GOAL, or you can manually state what it is
# https://www.gnu.org/software/make/manual/html_node/Special-Variables.html
$(call create_dirs,$(TARGETS))
# $(TARGET_DIRS) needs to be an order-only-prerequisite
w/h/a/t/e/v/e/r/things.dat: w/h/a/t/things.dat | $(TARGET_DIRS)
echo whatever happens > $@
w/h/a/t/things.dat: | $(TARGET_DIRS)
echo whatever happens > $@
For example, running the above will create:
$ make
mkdir w/
mkdir w/h/
mkdir w/h/a/
mkdir w/h/a/t/
mkdir w/h/a/t/e/
mkdir w/h/a/t/e/v/
mkdir w/h/a/t/e/v/e/
mkdir w/h/a/t/e/v/e/r/
echo whatever happens > w/h/a/t/things.dat
echo whatever happens > w/h/a/t/e/v/e/r/things.dat
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
Building upon Fabien Kruba's already excellent answer, I thought it would be nice if the **
portion of the URL could be given as a parameter to the controller method via an annotation, in a way which was similar to @RequestParam
and @PathVariable
, rather than always using a utility method which explicitly required the HttpServletRequest
. So here's an example of how that might be implemented. Hopefully someone finds it useful.
Create the annotation, along with the argument resolver:
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WildcardParam {
class Resolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(WildcardParam.class) != null;
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
return request == null ? null : new AntPathMatcher().extractPathWithinPattern(
(String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE),
(String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
}
}
}
Register the method argument resolver:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new WildcardParam.Resolver());
}
}
Use the annotation in your controller handler methods to have easy access to the **
portion of the URL:
@RestController
public class SomeController {
@GetMapping("/**")
public void someHandlerMethod(@WildcardParam String wildcardParam) {
// use wildcardParam here...
}
}
The following property can be used: {{alignItems: 'center'}}
<View style={{alignItems: 'center'}}>
<Text> Hello i'm centered text</Text>
</View>
If you prefer immutable data objects, or if you just dont want to be destructive to the input list, you can use Guava's predicates.
ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))
Insert else update both
public void InsertUpdateData()
{
//Here TestEntities is the class which is given from "Save entity connection setting in web.config"
TestEntities context = new TestEntities();
var query = from data in context.Employee
orderby data.name
select data;
foreach (Employee details in query)
{
if (details.id == 1)
{
//Assign the new values to name whose id is 1
details.name = "Sanjay";
details. Surname="Desai";
details.address=" Desiwadi";
}
else if(query==null)
{
details.name="Sharad";
details.surname=" Chougale ";
details.address=" Gargoti";
}
}
//Save the changes back to database.
context.SaveChanges();
}
If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date
is a MySQL date field, the python variable publish_date
is datetime.date
.
# make the record for the passed link info
sql_stmt = "INSERT INTO snippet_links (" + \
"link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
"VALUES(%s, %s, %s, %s, %s, %s, %s) ;"
sql_data = ( title, link, str(publish_date), \
author, posted_by, \
str(coco_id), str(link_id) )
try:
dbc.execute(sql_stmt, sql_data )
except Exception, e:
...
This error appears because the spring project doesn't read the file properties (bootstrap.yml or application.yml). In order to resolve this, you must add dependency in your pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
For me, I was getting this error on the com/sun/javadoc/Doclet
class. After some digging, I found that I accidentally copied the tools.jar
from Java 8 into my Java 7 folder.
Finding the tools.jar
for Java 7 and putting it back into the folder fixed my issue. So something to try.
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
In addition to doing the following, you may experience this issue if your app's Storyboard's files are localized. First, do each of these:
DerivedData
folder in ~/Library/Developer/Xcode/DerivedDataWhat finally worked for me was re-generating the storyboard localization files and deleting the English localization (which was unneeded because the Base Locale is English). To reload your Storyboard strings, see this answer on StackOverflow.
I had noticed that the non-text parts of my Storyboard were being updated, but not the localized text. If you have a localization in your app, I would recommend checking to make sure your localizations are updated (even if they're .strings
files).
<?php if ($foo) { ?>
<div class="mydiv">Condition is true</div>
<?php } else { ?>
<div class="myotherdiv">Condition is false</div>
<?php } ?>
a = 5
print '%02d' % a
# output: 05
The '%' operator is called string formatting operator when used with a string on the left side. '%d'
is the formatting code to print out an integer number (you will get a type error if the value isn't numeric). With '%2d
you can specify the length, and '%02d'
can be used to set the padding character to a 0 instead of the default space.
I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.
However, I noticed that .Wait() is working properly inside the void method.
and since async void and void have the same signature, you might need to do the following.
void LoadBlahBlah()
{
blah().Wait(); //this blocks
}
Confusingly enough async/await does not block on the next code.
async void LoadBlahBlah()
{
await blah(); //this does not block
}
When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks
this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.
So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.
hopefully my rambling makes sense to anybody also looking for answers.
Edit: I made some example code and decompiled it to see what is actually going on.
static async void Test()
{
await Task.Delay(5000);
}
static async Task TestAsync()
{
await Task.Delay(5000);
}
Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)
private static void Test()
{
<Test>d__1 stateMachine = new <Test>d__1();
stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
<TestAsync>d__2 stateMachine = new <TestAsync>d__2();
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.
meaning without the returning Task, there would be no way to check if it is complete.
as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.
so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.
This works for Swift 2.0.
navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController!.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.translucent = true
I think something like this:
btn.BackgroundImage = Properties.Resources.*Image_Identifier*;
Where *Image_Identifier*
is an identifier of the image in your resources.
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
as mentioned here you can just add this line
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
BaseAdapter
is best custom adapter for listview.
Class MyAdapter extends BaseAdapter{}
and it has many functions such as getCount()
, getView()
etc.
Pure POSIX shell and sponge
:
suffix=foobar
while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file |
sponge file
xargs
and printf
:
suffix=foobar
xargs -L 1 printf "%s${suffix}\n" < file | sponge file
Using join
:
suffix=foobar
join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
Shell tools using paste
, yes
, head
& wc
:
suffix=foobar
paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge file
Note that paste
inserts a Tab char before $suffix
.
Of course sponge
can be replaced with a temp file, afterwards mv
'd over the original filename, as with some other answers...
Maybe you used findViewById
in activity instead of dialog.findViewById
and set afterwards an OnClickListener
on a null
instance and that probably caused the original error.
Use contains instead:
In [10]: df.b.str.contains('^f')
Out[10]:
0 False
1 True
2 True
3 False
Name: b, dtype: bool
You can extract the scroll position using jQuery's .scrollTop()
method
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
// Do something
});
In Swift 3.1 I have added this extension to UIView
import Foundation
import UIKit
import CoreGraphics
extension UIView {
func gradientOfView(withColours: UIColor...) {
var cgColours = [CGColor]()
for colour in withColours {
cgColours.append(colour.cgColor)
}
let grad = CAGradientLayer()
grad.frame = self.bounds
grad.colors = cgColours
self.layer.insertSublayer(grad, at: 0)
}
}
which I then call with
class OverviewVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.gradientOfView(withColours: UIColor.red,UIColor.green, UIColor.blue)
}
}
The accepted answer is fine. However, I ran into "is not json serializable" error using that.
Here's how I fixed it
with open("file-name.json", 'w')
as output:
output.write(str(response))
Although it is not a good fix as the json file it creates will not have double quotes, however it is great if you are looking for quick and dirty.
Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
Example:
"http://yourdomain.com/read_result.php"
should be
"https://yourdomain.com/read_result.php"
or either way.
add or remove the "s" to match your URL.
I first tried the accepted answer by Mr Green, but I found my columns didn't align, that float:left seems very suspicious. When I went from no scollbar to scrollbar -- my table body shifted a few pixels and I lost alignment.
CODE PEN https://codepen.io/majorp/pen/gjrRMx
CSS
.width50px {
width: 100px !important;
}
.width100px {
width: 100px !important;
}
.fixed_headers {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
}
th {
padding: 5px;
text-align: left;
font-weight:bold;
height:50px;
}
td {
padding: 5px;
text-align: left;
}
thead, tr
{
display: block;
position: relative;
}
tbody {
display: block;
overflow: auto;
width: 100%;
height: 500px;
}
.tableColumnHeader {
height: 50px;
font-weight: bold;
}
.lime {
background-color: lime;
}
Note that the answers that suggest using unbind()
are now out of date as that method has been deprecated and will be removed in future versions of jQuery.
As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.
Instead, you should now use off()
:
$(window).off('scroll');
You can always jump right to the root controller:
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [storyboard instantiateInitialViewController];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];
It is also worth noting that even without creating your own model binder multiple different formats may be parsable.
For instance in the US all the following strings are equivalent and automatically get bound to the same DateTime value:
/company/press/may%2001%202008
/company/press/2008-05-01
/company/press/05-01-2008
I'd strongly suggest using yyyy-mm-dd because its a lot more portable. You really dont want to deal with handling multiple localized formats. If someone books a flight on 1st May instead of 5th January you're going to have big issues!
NB: I'm not clear exaclty if yyyy-mm-dd is universally parsed in all cultures so maybe someone who knows can add a comment.
Its a simple trick. This is jQuery code that can exploit the html5 validation by changing the required
properties if any one is checked. Following is your html code (make sure that you add required for all the elements in the group.)
<input type="checkbox" name="option[]" id="option-1" value="option1" required/> Option 1
<input type="checkbox" name="option[]" id="option-2" value="option2" required/> Option 2
<input type="checkbox" name="option[]" id="option-3" value="option3" required/> Option 3
<input type="checkbox" name="option[]" id="option-4" value="option4" required/> Option 4
<input type="checkbox" name="option[]" id="option-5" value="option5" required/> Option 5
Following is jQuery script, which disables further validation check if any one is selected. Select using name element.
$cbx_group = $("input:checkbox[name='option[]']");
$cbx_group = $("input:checkbox[id^='option-']"); // name is not always helpful ;)
$cbx_group.prop('required', true);
if($cbx_group.is(":checked")){
$cbx_group.prop('required', false);
}
Small gotcha here: Since you are using html5 validation, make sure you execute this before the it gets validated i.e. before form submit.
// but this might not work as expected
$('form').submit(function(){
// code goes here
});
// So, better USE THIS INSTEAD:
$('button[type="submit"]').on('click', function() {
// skipping validation part mentioned above
});
After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.
The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.
Give it a try :)
*only tested in chrome so far
HTML:
<div class="frame">
<img src="image.jpg"/>
</div>
CSS:
.frame {
border: 1px solid red;
min-height: 98%;
max-height: 98%;
min-width: 99%;
max-width: 99%;
text-align: center;
margin: auto;
position: absolute;
}
img {
border: 1px solid blue;
min-height: 98%;
max-width: 99%;
max-height: 98%;
width: auto;
height: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
You can use <CTRL-V><Tab>
in "insert mode". In insert mode, <CTRL-V>
inserts a literal copy of your next character.
If you need to do this often, @Dee`Kej suggested (in the comments) setting Shift+Tab to insert a real tab with this mapping:
:inoremap <S-Tab> <C-V><Tab>
Also, as noted by @feedbackloop, on Windows you may need to press <CTRL-Q>
rather than <CTRL-V>
.
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}
echo(var_export($var));
When $var
is boolean variable, true
or false
will be printed out.
Try to implement dynamic data structure such as a linked list
Here are the two functions I use. They are based on matrix rotations. and can rotate around arbitrary axes. To rotate using the world's axes you would want to use the second function rotateAroundWorldAxis().
// Rotate an object around an arbitrary axis in object space
var rotObjectMatrix;
function rotateAroundObjectAxis(object, axis, radians) {
rotObjectMatrix = new THREE.Matrix4();
rotObjectMatrix.makeRotationAxis(axis.normalize(), radians);
// old code for Three.JS pre r54:
// object.matrix.multiplySelf(rotObjectMatrix); // post-multiply
// new code for Three.JS r55+:
object.matrix.multiply(rotObjectMatrix);
// old code for Three.js pre r49:
// object.rotation.getRotationFromMatrix(object.matrix, object.scale);
// old code for Three.js r50-r58:
// object.rotation.setEulerFromRotationMatrix(object.matrix);
// new code for Three.js r59+:
object.rotation.setFromRotationMatrix(object.matrix);
}
var rotWorldMatrix;
// Rotate an object around an arbitrary axis in world space
function rotateAroundWorldAxis(object, axis, radians) {
rotWorldMatrix = new THREE.Matrix4();
rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
// old code for Three.JS pre r54:
// rotWorldMatrix.multiply(object.matrix);
// new code for Three.JS r55+:
rotWorldMatrix.multiply(object.matrix); // pre-multiply
object.matrix = rotWorldMatrix;
// old code for Three.js pre r49:
// object.rotation.getRotationFromMatrix(object.matrix, object.scale);
// old code for Three.js pre r59:
// object.rotation.setEulerFromRotationMatrix(object.matrix);
// code for r59+:
object.rotation.setFromRotationMatrix(object.matrix);
}
So you should call these functions within your anim
function (requestAnimFrame callback), resulting in a rotation of 90 degrees on the x-axis:
var xAxis = new THREE.Vector3(1,0,0);
rotateAroundWorldAxis(mesh, xAxis, Math.PI / 180);
In your_controller write this...
public function update_title()
{
$data = array
(
'table_id' => $this->input->post('table_id'),
'table_title' => $this->input->post('table_title')
);
$this->load->model('your_model'); // First load the model
if($this->your_model->update_title($data)) // call the method from the controller
{
// update successful...
}
else
{
// update not successful...
}
}
While in your_model...
public function update_title($data)
{
$this->db->set('table_title',$data['title'])
->where('table_id',$data['table_id'])
->update('your_table');
}
This will works fine...
type T1 = Omit<XYZ, "z"> // { x: number; y: number; }
type T2 = Omit<XYZ, "y" | "z"> // { x: number; }
type Keys_StringExcluded<T> =
{ [K in keyof T]: T[K] extends string ? never : K }[keyof T]
type XYZ = { x: number; y: string; z: number; }
type T3a = Pick<XYZ, Keys_StringExcluded<XYZ>> // { x: number; z: number; }
Shorter version with TS 4.1 key remapping / as
clause in mapped types (PR):
type T3b = { [K in keyof XYZ as XYZ[K] extends string ? never : K]: XYZ[K] }
// { x: number; z: number; }
string
patterntype OmitGet<T> = {[K in keyof T as K extends `get${infer _}` ? never : K]: T[K]}
type XYZ2 = { getA: number; b: string; getC: boolean; }
type T4 = OmitGet<XYZ2> // { b: string; }
Note: Above template literal types are supported with TS 4.1.
Note 2: You can also write get${string}
instead of get${infer _}
here.
Pick
, Omit
and other utility types
How to Pick and rename certain keys using Typescript? (rename instead of exclude)
You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.
just make sure it built.
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
there's your bitmap as the screen saw it.
Here's an answer, based on (and I think an improvement on) Tester101's answer, expressed as a subroutine, with the CopyFile line once instead of three times, and prepared to handle changing the file name as the copy is made (no hard-coded destination directory). I also found I had to delete the target file before copying to get this to work, but that might be a Windows 7 thing. The WScript.Echo statements are because I didn't have a debugger and can of course be removed if desired.
Sub CopyFile(SourceFile, DestinationFile)
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
Dim wasReadOnly
wasReadOnly = False
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is read-only.
WScript.Echo "Removing the read-only attribute"
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
wasReadOnly = True
End If
WScript.Echo "Deleting the file"
fso.DeleteFile DestinationFile, True
End If
'Copy the file
WScript.Echo "Copying " & SourceFile & " to " & DestinationFile
fso.CopyFile SourceFile, DestinationFile, True
If wasReadOnly Then
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Set fso = Nothing
End Sub
According to experiments run on this page: http://www.dotnetguru2.org/sebastienros/index.php/2006/02/24/cast_vs_as
(this page is having some "illegal referrer" errors show up sometimes, so just refresh if it does)
Conclusion is, the "as" operator is normally faster than a cast. Sometimes by many times faster, sometimes just barely faster.
I peronsonally thing "as" is also more readable.
So, since it is both faster and "safer" (wont throw exception), and possibly easier to read, I recommend using "as" all the time.
Looking at Standard .NET event patterns we find
The standard signature for a .NET event delegate is:
void OnEventRaised(object sender, EventArgs args);
[...]
The argument list contains two arguments: the sender, and the event arguments. The compile time type of sender is System.Object, even though you likely know a more derived type that would always be correct. By convention, use object.
Below on same page we find an example of the typical event definition which is something like
public event EventHandler<EventArgs> EventName;
Had we defined
class MyClass
{
public event Action<MyClass, EventArgs> EventName;
}
the handler could have been
void OnEventRaised(MyClass sender, EventArgs args);
where sender
has the correct (more derived) type.
Try to replace the
padding: 2px 30px 2px 2px;
with
padding: 2px 2px 2px 2px;
It should work.
You can just use the +
operator!
irb(main):001:0> a = [1,2]
=> [1, 2]
irb(main):002:0> b = [3,4]
=> [3, 4]
irb(main):003:0> a + b
=> [1, 2, 3, 4]
You can read all about the array class here: http://ruby-doc.org/core/classes/Array.html
Up to and including txt
you would need to change your regex like so:
^(.*?\\.txt)
JetBrains is going to add a decompiler to its ReSharper, and release a stand-alone decompiler too.
The good news is that we’re preparing a standalone binary-as-a-source application, i.e. a decompiler + assembly browser to explore whatever .NET compiled code is legal to explore. We don’t have any specific date for release, but it’s going to be released this year, and it’s going to be free of charge. And by saying “free”, we actually mean “free”.
Here is more information.
UPDATE: JetBrains has now released the product called dotPeek and it can be found here.
It's been a while but for future reference: the method shouldComponentUpdate() can be used.
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The ggpubr package offers a shortcut that does the right thing by default (right align text, middle align text box to tick):
library(ggplot2)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
q <- qplot(cut, carat, data = diamonds, geom = "boxplot")
q + ggpubr::rotate_x_text()
Created on 2018-11-06 by the reprex package (v0.2.1)
Found with a GitHub search for the relevant argument names: https://github.com/search?l=R&q=element_text+angle+90+vjust+org%3Acran&type=Code
If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.
insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)
There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:
CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int
AS
If you want to know what the ID of the newly inserted record is add
SELECT @@IDENTITY
to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx
You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.
P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.
If you have jQuery enabled you can use an escapeXml function and not have to worry about escaping arrows or special characters.
<pre>
${fn:escapeXml('
<!-- all your code -->
')};
</pre>
Another SIMPLE option is to delete the node_modules and package-lock.json
rm -rf node_modules
rm -rf package-lock.json
After this you can try reinstalling the npm packages
From MSDN:
Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.
This means that you can use a single underscore as a member variable prefix, as long as it's followed by a lower-case letter.
This is apparently taken from section 17.4.3.1.2 of the C++ standard, but I can't find an original source for the full standard online.
See also this question.
Not out of the box in Sql Server Management Studio, but it is a feature of the very good SSMS Tools Pack
i use this:
for (Map.Entry<Object, Object> entry:properties.entrySet()) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
You can create text columns with CSS Multiple Columns property. You don't need any table or multiple divs.
HTML
<div class="column">
<!-- paragraph text comes here -->
</div>
CSS
.column {
column-count: 2;
column-gap: 40px;
}
Read more about CSS Multiple Columns at https://www.w3schools.com/css/css3_multiple_columns.asp
Check if Tensorflow was installed successfully using:
pip3 show tensorflow
If you get something like
Name: tensorflow
Version: 1.2.1
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Author: Google Inc.
Author-email: [email protected]
License: Apache 2.0
Location: /usr/local/lib/python3.5/dist-packages
Requires: bleach, markdown, html5lib, backports.weakref, werkzeug, numpy, protobuf, wheel, six
You may try adding the path of your tensorflow location by:
export PYTHONPATH=/your/tensorflow/path:$PYTHONPATH.
I received this error out of the blue. Eclipse stopped working even though I made no config changes and did not install any new jdk's.
Here was my eclipse.ini file :
--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:/Program Files (x86)/Java/jre7/bin/javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx1024m
To get Eclipse to start successfully I removed
-vmargs
-Dosgi.requiredJavaVersion=1.6
-vm
C:/Program Files (x86)/Java/jre7/bin/javaw.exe
So here is my updated file :
--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-Xms40m
-Xmx1024m
I have no idea why removing osgi.requiredJavaVersion=1.6 fixed this as my jvm version is 1.6. From the doc http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html
osgi.requiredJavaVersion
The minimum java version that is required to launch Eclipse. The default value is "1.4.1".
I think my java version was set correctly. Anyway Eclipse starts and runs for me now......
If they are not very big, what's probably your case export it as JSON.
Also this makes it portable among all platforms.
using Newtonsoft.Json;
[TestMethod]
public void ExportJson()
{
double[,] b = new double[,]
{
{ 110, 120, 130, 140, 150 },
{1110, 1120, 1130, 1140, 1150},
{1000, 1, 5, 9, 1000},
{1110, 2, 6, 10, 1110},
{1220, 3, 7, 11, 1220},
{1330, 4, 8, 12, 1330}
};
string jsonStr = JsonConvert.SerializeObject(b);
Console.WriteLine(jsonStr);
string path = "X:\\Programming\\workspaceEclipse\\PyTutorials\\src\\tensorflow_tutorials\\export.txt";
File.WriteAllText(path, jsonStr);
}
bar
is your static variable and you can access it using Foo.bar
.
Basically, you need to qualify your static variable with Class name.
Make sure that the Object
s in your list have equals()
defined on them. Then
assertThat(generatedList, is(equalTo(expectedList)));
works.
Though this question is rather old, here's a answer :)
What you are asking for can be achieved by using jQuery's .click() event method and .on() event method
So this could be the code:
// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");
$(document).ready(function() {
// When the document is ready/loaded, execute function
// Hide hangoutButton
hangoutButton.hide();
// Assign "click"-event-method to userImage
userImage.on("click", function() {
console.log("in onclick");
hangoutButton.click();
});
});