class Holder
{
private $value;
public function __construct( $value )
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function setValue( $value )
{
return $this->value = $value;
}
}
class Swap
{
public function SwapObjects( Holder $x, Holder $y )
{
$tmp = $x;
$x = $y;
$y = $tmp;
}
public function SwapValues( Holder $x, Holder $y )
{
$tmp = $x->getValue();
$x->setValue($y->getValue());
$y->setValue($tmp);
}
}
$a1 = new Holder('a');
$b1 = new Holder('b');
$a2 = new Holder('a');
$b2 = new Holder('b');
Swap::SwapValues($a1, $b1);
Swap::SwapObjects($a2, $b2);
echo 'SwapValues: ' . $a2->getValue() . ", " . $b2->getValue() . "<br>";
echo 'SwapObjects: ' . $a1->getValue() . ", " . $b1->getValue() . "<br>";
Attributes are still modifiable when not passed by reference so beware.
Output:
SwapObjects: b, a SwapValues: a, b
with Apache PDFBox it goes like this:
PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println("Text:" + text);
}
document.close();
All data is available under
window.location.search
you have to parse the string, eg.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
just call the function with GET variable name as parameter, eg.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
I just replicate the 2 attributes of the btn-navbar
(data-toggle="collapse" data-target=".nav-collapse.in"
) on each link like this:
<div class="nav-collapse">
<ul class="nav" >
<li class="active"><a href="#home" data-toggle="collapse" data-target=".nav-collapse.in">Home</a></li>
<li><a href="#about" data-toggle="collapse" data-target=".nav-collapse.in">About</a></li>
<li><a href="#portfolio" data-toggle="collapse" data-target=".nav-collapse.in">Portfolio</a></li>
<li><a href="#services" data-toggle="collapse" data-target=".nav-collapse.in">Services</a></li>
<li><a href="#contact" data-toggle="collapse" data-target=".nav-collapse.in">Contact</a></li>
</ul>
</div>
In the Bootstrap 4 Navbar, in
has changed to show
so the syntax would be:
data-toggle="collapse" data-target=".navbar-collapse.show"
You can try also this:
pathinfo(basename($_FILES["fileToUpload"]["name"]), PATHINFO_EXTENSION)
I've seen several solutions but I wasn't convinced by any of them. Either very complicated or too simple (non-reusable).
This is my favourite approach at the moment:
mEditText.setOnTouchListener(
new OnEditTextRightDrawableTouchListener(mEditText) {
@Override
public void OnDrawableClick() {
// The right drawable was clicked. Your action goes here.
}
});
And this is the reusable touch listener:
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
public abstract class OnEditTextRightDrawableTouchListener implements OnTouchListener {
private final EditText mEditText;
public OnEditTextRightDrawableTouchListener(@NonNull final EditText editText) {
mEditText = editText;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
final int DRAWABLE_RIGHT_POSITION = 2;
final Drawable drawable = mEditText.getCompoundDrawables()[DRAWABLE_RIGHT_POSITION];
if (drawable != null) {
final float touchEventX = motionEvent.getX();
final int touchAreaRight = mEditText.getRight();
final int touchAreaLeft = touchAreaRight - drawable.getBounds().width();
if (touchEventX >= touchAreaLeft && touchEventX <= touchAreaRight) {
view.performClick();
OnDrawableClick();
}
return true;
}
}
return false;
}
public abstract void OnDrawableClick();
}
I just encountered and solve a similar problem.
First you should check the directory like other threads described. Then you can check whether the Build tool version matches your SDK version.
(e.g. for my project, in build.gradle file, you have:)
android { compileSdkVersion 21 buildToolsVersion "21.1.1" }
and then open you SDK manager, make sure you have the same version of sdk(21.1.1) installed in the selected directoriy:
If not, install it and restart Android Studio. It works for me.
I've also seen other guys saying run Android Studio as administrator would also help:
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
You can't get the file size of local files with javascript in a standard way using a web browser.
But if the file is accessible from a remote path, you might be able to send a HEAD request using Javascript, and read the Content-length header, depending on the webserver
You can also use this approach in case you want to pass some http parameters and send a json request:
(note: I have added in some extra code just incase it helps any other future readers)
public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {
//add the http parameters you wish to pass
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
//Build the server URI together with the parameters you wish to pass
URIBuilder uriBuilder = new URIBuilder("http://google.ug");
uriBuilder.addParameters(postParameters);
HttpPost postRequest = new HttpPost(uriBuilder.build());
postRequest.setHeader("Content-Type", "application/json");
//this is your JSON string you are sending as a request
String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";
//pass the json string request in the entity
HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
postRequest.setEntity(entity);
//create a socketfactory in order to use an http connection manager
PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);
connManager.setMaxTotal(20);
connManager.setDefaultMaxPerRoute(20);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(HttpClientPool.connTimeout)
.setConnectTimeout(HttpClientPool.connTimeout)
.setConnectionRequestTimeout(HttpClientPool.readTimeout)
.build();
// Build the http client.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
CloseableHttpResponse response = httpclient.execute(postRequest);
//Read the response
String responseString = "";
int statusCode = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
HttpEntity responseHttpEntity = response.getEntity();
InputStream content = responseHttpEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = buffer.readLine()) != null) {
responseString += line;
}
//release all resources held by the responseHttpEntity
EntityUtils.consume(responseHttpEntity);
//close the stream
response.close();
// Close the connection manager.
connManager.close();
}
Since the third version of Swift you can do the following:
let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)
simialr to what Sunkas advised.
I just used the following code, which removed all the punctuation:
tokens = nltk.wordpunct_tokenize(raw)
type(tokens)
text = nltk.Text(tokens)
type(text)
words = [w.lower() for w in text if w.isalpha()]
You need to escape the .
as "0\.49"
.
A .
is a regex meta-character to match any character(except newline). To match a literal period, you need to escape it.
If you only have one line of text and your div has a fixed height, you can do this:
div {
line-height: (2*height - font-size);
text-align: right;
}
See fiddle.
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Here is a procedure and code using generated ProjectInstaller
in Visual Studio:
ProjectInstaller
in design editor (it should open automatically when installer is created) and set properties of generated serviceProcessInstaller1
(e.g. Account: LocalSystem) and serviceInstaller1
(e.g. StartType: Automatic)ProjectInstaller
in code editor (press F7
in design editor) and add event handler to ServiceInstaller.AfterInstall
- see the following code. It will start the service after its installation.ProjectInstaller class:
using System.ServiceProcess;
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent(); //generated code including property settings from previous steps
this.serviceInstaller1.AfterInstall += Autorun_AfterServiceInstall; //use your ServiceInstaller name if changed from serviceInstaller1
}
void Autorun_AfterServiceInstall(object sender, InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
}
}
}
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
use simplejson or cjson for speedups
import simplejson as json
json.loads(obj)
or
cjson.decode(obj)
I had an strange problem and understood an unpleasant strange difference:
when I get an URL from user as an CharField and then and use it in html a tag by href, it adds that url to my url and that's not what I want. But when I do it by Textfield it passes just the URL that user entered.
look at these:
my website address: http://myweb.com
CharField entery: http://some-address.com
when clicking on it: http://myweb.comhttp://some-address.com
TextField entery: http://some-address.com
when clicking on it: http://some-address.com
I must mention that the URL is saved exactly the same in DB by two ways but I don't know why result is different when clicking on them
Use repr
>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
Overall:You persist entity that is violating database rules like as saving entity that has varchar field over 250 chars ,something like that.
In my case it was a squishy problem with TestEntityManager ,because it use HSQL database /in memory database/ and it persist the user but when you try to find it ,it drops the same exception :/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes= Application.class)
@DataJpaTest
@ActiveProfiles("test")
public class UserServicesTests {
@Autowired
private TestEntityManager testEntityManager;
@Autowired
private UserRepository userRepository;
@Test
public void oops() {
User user = new User();
user.setUsername("Toshko");
//EMAIL IS REQUIRED:
//user.setEmail("OPS");
this.testEntityManager.persist(user);
//HERE COMES TE EXCEPTION BECAUSE THE EMAIL FIELD IN TE DATABASE IS REQUIRED :
this.userRepository.findUserByUsername("Toshko");
System.out.println();
}
}
look at String.indexOf
and String.substring
.
Make sure you check for -1 for indexOf
.
This one liner helps me while creating dump of a single database.
PGPASSWORD="yourpassword" pg_dump -U postgres -h localhost mydb > mydb.pgsql
You can validate that and much more by using an XML schema language, like XSD.
If you mean conditionally, within code, then XPath is worth a look as well.
Note the potential for an out-of-range index with "i+3". You could do something like:
with open("file.txt", "r") as f:
searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
if "searchphrase" in line:
k=min(i+3,j)
for l in searchlines[i:k]: print l,
print
Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.
Update 2019-10:
As stated in the issue tracker, Google has been working on a new Android SDK Command-line Tools release that runs on current JVMs (9, 10, 11+) and does not depend on deprecated JAXB EE modules!
You can download and use the new Android SDK Command-line Tools inside Android Studio or by manually downloading them from the Google servers:
For the latest versions check the URLs inside the repository.xml.
If you manually unpack the command line tools, take care of placing them in a subfolder inside your $ANDROID_HOME
(e.g. $ANDROID_HOME/cmdline-tools/...
).
You can set aliases for the columns that you are selecting:
$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'
Set the list style and left padding to nothing.
ul {
list-style: none;
padding-left: 0;
}?
ul {_x000D_
list-style: none;_x000D_
padding-left: 0;_x000D_
}
_x000D_
<ul>_x000D_
<li>a</li>_x000D_
<li>b</li>_x000D_
<li>c</li>_x000D_
</ul>
_x000D_
To maintain the bullets you can replace the list-style: none
with list-style-position: inside
or the shorthand list-style: inside
:
ul {
list-style-position: inside;
padding-left: 0;
}
ul {_x000D_
list-style-position: inside;_x000D_
padding-left: 0;_x000D_
}
_x000D_
<ul>_x000D_
<li>a</li>_x000D_
<li>b</li>_x000D_
<li>c</li>_x000D_
</ul>
_x000D_
Simple CASE expression:
CASE input_expression
WHEN when_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
Searched CASE expression:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
Reference: http://msdn.microsoft.com/en-us/library/ms181765.aspx
Typing brew install cmake
as you did installs cmake
. Now you can type cmake
and use it.
If typing cmake
doesn’t work make sure /usr/local/bin
is your PATH
. You can see it with echo $PATH
. If you don’t see /usr/local/bin
in it add the following to your ~/.bashrc
:
export PATH="/usr/local/bin:$PATH"
Then reload your shell session and try again.
(all the above assumes Homebrew is installed in its default location, /usr/local
. If not you’ll have to replace /usr/local
with $(brew --prefix)
in the export
line)
The first answer will not pass through all the points. This graph will exactly pass through all the points and will be a perfect curve with the points as [{x:,y:}] n such points.
var points = [{x:1,y:1},{x:2,y:3},{x:3,y:4},{x:4,y:2},{x:5,y:6}] //took 5 example points
ctx.moveTo((points[0].x), points[0].y);
for(var i = 0; i < points.length-1; i ++)
{
var x_mid = (points[i].x + points[i+1].x) / 2;
var y_mid = (points[i].y + points[i+1].y) / 2;
var cp_x1 = (x_mid + points[i].x) / 2;
var cp_x2 = (x_mid + points[i+1].x) / 2;
ctx.quadraticCurveTo(cp_x1,points[i].y ,x_mid, y_mid);
ctx.quadraticCurveTo(cp_x2,points[i+1].y ,points[i+1].x,points[i+1].y);
}
Install the pywin32 extensions. Then you can do the following:
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want
Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start here, perhaps.
EDIT: Sending F11
import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")
# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")
it's as simple as not using a table for markup, as stated by Harmen. You're not displaying data after all, you're collecting data.
I'll take for example the question 23 here: http://accessible.netscouts-ggmbh.eu/en/developer.html#fb1_22_5
On paper, it's good as it is. If you had to display the results, it'd probably be OK.
But you can replace it with ... 4 paragraphs with a label and a select (option's would be the headers of the first line). One paragraph per line, this is far more simple.
None of the above answers worked "out of the box" for me, however, the following function, obtained by copying the ideas of the other answers works:
apply_func_2_cols = @(f,M) cell2mat(cellfun(f,num2cell(M,1), 'UniformOutput',0));
It takes a function f
and applies it to every column of the matrix M
.
So for example:
f = @(v) [0 1;1 0]*v + [0 0.1]';
apply_func_2_cols(f,[0 0 1 1;0 1 0 1])
ans =
0.00000 1.00000 0.00000 1.00000
0.10000 0.10000 1.10000 1.10000
Assuming we imported pandas as pd
and df
is our dataframe
pd.to_datetime(df['date'], unit='s')
works for me.
Since Sheet.getPhysicalNumberOfRows()
does not count empty rows and Sheet.getLastRowNum()
returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.
int rowTotal = sheet.getLastRowNum();
if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
rowTotal++;
}
Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.
As an explanation to Jonathan Fingland's answer:
[position()=1 and @location='US']
) must be true as a whole[position()=1][@location='US']
) must be true one after another[position()=1][@location='US']
!= [@location='US'][position()=1]
[position()=1 and @location='US']
== [@location='US' and position()=1]
[position()=1]
can be abbreviated to [1]
You can build complex expressions in predicates with the Boolean operators "and
" and "or
", and with the Boolean XPath functions not()
, true()
and false()
. Plus you can wrap sub-expressions in parentheses.
The simpliest way
Scanner in = new Scanner(System.in);
System.out.println("Enter seconds");
int s = in.nextInt();
int sec = s % 60;
int min = (s / 60)%60;
int hours = (s/60)/60;
System.out.println(hours + ":" + min + ":" + sec);
C++ treats variables of user-defined types with value semantics. This means that objects are implicitly copied in various contexts, and we should understand what "copying an object" actually means.
Let us consider a simple example:
class person
{
std::string name;
int age;
public:
person(const std::string& name, int age) : name(name), age(age)
{
}
};
int main()
{
person a("Bjarne Stroustrup", 60);
person b(a); // What happens here?
b = a; // And here?
}
(If you are puzzled by the name(name), age(age)
part,
this is called a member initializer list.)
What does it mean to copy a person
object?
The main
function shows two distinct copying scenarios.
The initialization person b(a);
is performed by the copy constructor.
Its job is to construct a fresh object based on the state of an existing object.
The assignment b = a
is performed by the copy assignment operator.
Its job is generally a little more complicated,
because the target object is already in some valid state that needs to be dealt with.
Since we declared neither the copy constructor nor the assignment operator (nor the destructor) ourselves, these are implicitly defined for us. Quote from the standard:
The [...] copy constructor and copy assignment operator, [...] and destructor are special member functions. [ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are used. [...] end note ] [n3126.pdf section 12 §1]
By default, copying an object means copying its members:
The implicitly-defined copy constructor for a non-union class X performs a memberwise copy of its subobjects. [n3126.pdf section 12.8 §16]
The implicitly-defined copy assignment operator for a non-union class X performs memberwise copy assignment of its subobjects. [n3126.pdf section 12.8 §30]
The implicitly-defined special member functions for person
look like this:
// 1. copy constructor
person(const person& that) : name(that.name), age(that.age)
{
}
// 2. copy assignment operator
person& operator=(const person& that)
{
name = that.name;
age = that.age;
return *this;
}
// 3. destructor
~person()
{
}
Memberwise copying is exactly what we want in this case:
name
and age
are copied, so we get a self-contained, independent person
object.
The implicitly-defined destructor is always empty.
This is also fine in this case since we did not acquire any resources in the constructor.
The members' destructors are implicitly called after the person
destructor is finished:
After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X's direct [...] members [n3126.pdf 12.4 §6]
So when should we declare those special member functions explicitly? When our class manages a resource, that is, when an object of the class is responsible for that resource. That usually means the resource is acquired in the constructor (or passed into the constructor) and released in the destructor.
Let us go back in time to pre-standard C++.
There was no such thing as std::string
, and programmers were in love with pointers.
The person
class might have looked like this:
class person
{
char* name;
int age;
public:
// the constructor acquires a resource:
// in this case, dynamic memory obtained via new[]
person(const char* the_name, int the_age)
{
name = new char[strlen(the_name) + 1];
strcpy(name, the_name);
age = the_age;
}
// the destructor must release this resource via delete[]
~person()
{
delete[] name;
}
};
Even today, people still write classes in this style and get into trouble:
"I pushed a person into a vector and now I get crazy memory errors!"
Remember that by default, copying an object means copying its members,
but copying the name
member merely copies a pointer, not the character array it points to!
This has several unpleasant effects:
a
can be observed via b
.b
is destroyed, a.name
is a dangling pointer.a
is destroyed, deleting the dangling pointer yields undefined behavior.name
pointed to before the assignment,
sooner or later you will get memory leaks all over the place.Since memberwise copying does not have the desired effect, we must define the copy constructor and the copy assignment operator explicitly to make deep copies of the character array:
// 1. copy constructor
person(const person& that)
{
name = new char[strlen(that.name) + 1];
strcpy(name, that.name);
age = that.age;
}
// 2. copy assignment operator
person& operator=(const person& that)
{
if (this != &that)
{
delete[] name;
// This is a dangerous point in the flow of execution!
// We have temporarily invalidated the class invariants,
// and the next statement might throw an exception,
// leaving the object in an invalid state :(
name = new char[strlen(that.name) + 1];
strcpy(name, that.name);
age = that.age;
}
return *this;
}
Note the difference between initialization and assignment:
we must tear down the old state before assigning to name
to prevent memory leaks.
Also, we have to protect against self-assignment of the form x = x
.
Without that check, delete[] name
would delete the array containing the source string,
because when you write x = x
, both this->name
and that.name
contain the same pointer.
Unfortunately, this solution will fail if new char[...]
throws an exception due to memory exhaustion.
One possible solution is to introduce a local variable and reorder the statements:
// 2. copy assignment operator
person& operator=(const person& that)
{
char* local_name = new char[strlen(that.name) + 1];
// If the above statement throws,
// the object is still in the same state as before.
// None of the following statements will throw an exception :)
strcpy(local_name, that.name);
delete[] name;
name = local_name;
age = that.age;
return *this;
}
This also takes care of self-assignment without an explicit check. An even more robust solution to this problem is the copy-and-swap idiom, but I will not go into the details of exception safety here. I only mentioned exceptions to make the following point: Writing classes that manage resources is hard.
Some resources cannot or should not be copied, such as file handles or mutexes.
In that case, simply declare the copy constructor and copy assignment operator as private
without giving a definition:
private:
person(const person& that);
person& operator=(const person& that);
Alternatively, you can inherit from boost::noncopyable
or declare them as deleted (in C++11 and above):
person(const person& that) = delete;
person& operator=(const person& that) = delete;
Sometimes you need to implement a class that manages a resource. (Never manage multiple resources in a single class, this will only lead to pain.) In that case, remember the rule of three:
If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.
(Unfortunately, this "rule" is not enforced by the C++ standard or any compiler I am aware of.)
From C++11 on, an object has 2 extra special member functions: the move constructor and move assignment. The rule of five states to implement these functions as well.
An example with the signatures:
class person
{
std::string name;
int age;
public:
person(const std::string& name, int age); // Ctor
person(const person &) = default; // 1/5: Copy Ctor
person(person &&) noexcept = default; // 4/5: Move Ctor
person& operator=(const person &) = default; // 2/5: Copy Assignment
person& operator=(person &&) noexcept = default; // 5/5: Move Assignment
~person() noexcept = default; // 3/5: Dtor
};
The rule of 3/5 is also referred to as the rule of 0/3/5. The zero part of the rule states that you are allowed to not write any of the special member functions when creating your class.
Most of the time, you do not need to manage a resource yourself,
because an existing class such as std::string
already does it for you.
Just compare the simple code using a std::string
member
to the convoluted and error-prone alternative using a char*
and you should be convinced.
As long as you stay away from raw pointer members, the rule of three is unlikely to concern your own code.
.mat files contain binary data, so you will not be able to open them easily with a word processor. There are some options for opening them outside of MATLAB:
If all you need to do is look at the files, you could obtain Octave, which is a free, but somewhat slower implementation of MATLAB. You can refer to How do you open .mat files in Octave? for more information on the subject. You can get octave from http://www.gnu.org/software/octave/download.html. The interface is very similar to MATLAB's.
As NKN and Ergodicity mentioned, there are python libaries available for this as well.
The most hardcore solution would be to write your own processor from scratch. The MAT file specification is available from MathWorks at http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf.
This is one sample dao test using junit in spring project.
import java.util.List;
import junit.framework.Assert;
import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
@Autowired
private MemberDao memberDao;
@Test
public void testFindById()
{
Member member = memberDao.findById(0l);
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("[email protected]", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
@Test
public void testFindByEmail()
{
Member member = memberDao.findByEmail("[email protected]");
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("[email protected]", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
@Test
public void testRegister()
{
Member member = new Member();
member.setEmail("[email protected]");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
Long id = member.getId();
Assert.assertNotNull(id);
Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
Member newMember = memberDao.findById(id);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("[email protected]", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
@Test
public void testFindAllOrderedByName()
{
Member member = new Member();
member.setEmail("[email protected]");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
List<Member> members = memberDao.findAllOrderedByName();
Assert.assertEquals(2, members.size());
Member newMember = members.get(0);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("[email protected]", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
}
That is by design.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
Here's a simple Kalman filter that could be used for exactly this situation. It came from some work I did on Android devices.
General Kalman filter theory is all about estimates for vectors, with the accuracy of the estimates represented by covariance matrices. However, for estimating location on Android devices the general theory reduces to a very simple case. Android location providers give the location as a latitude and longitude, together with an accuracy which is specified as a single number measured in metres. This means that instead of a covariance matrix, the accuracy in the Kalman filter can be measured by a single number, even though the location in the Kalman filter is a measured by two numbers. Also the fact that the latitude, longitude and metres are effectively all different units can be ignored, because if you put scaling factors into the Kalman filter to convert them all into the same units, then those scaling factors end up cancelling out when converting the results back into the original units.
The code could be improved, because it assumes that the best estimate of current location is the last known location, and if someone is moving it should be possible to use Android's sensors to produce a better estimate. The code has a single free parameter Q, expressed in metres per second, which describes how quickly the accuracy decays in the absence of any new location estimates. A higher Q parameter means that the accuracy decays faster. Kalman filters generally work better when the accuracy decays a bit quicker than one might expect, so for walking around with an Android phone I find that Q=3 metres per second works fine, even though I generally walk slower than that. But if travelling in a fast car a much larger number should obviously be used.
public class KalmanLatLong {
private final float MinAccuracy = 1;
private float Q_metres_per_second;
private long TimeStamp_milliseconds;
private double lat;
private double lng;
private float variance; // P matrix. Negative means object uninitialised. NB: units irrelevant, as long as same units used throughout
public KalmanLatLong(float Q_metres_per_second) { this.Q_metres_per_second = Q_metres_per_second; variance = -1; }
public long get_TimeStamp() { return TimeStamp_milliseconds; }
public double get_lat() { return lat; }
public double get_lng() { return lng; }
public float get_accuracy() { return (float)Math.sqrt(variance); }
public void SetState(double lat, double lng, float accuracy, long TimeStamp_milliseconds) {
this.lat=lat; this.lng=lng; variance = accuracy * accuracy; this.TimeStamp_milliseconds=TimeStamp_milliseconds;
}
/// <summary>
/// Kalman filter processing for lattitude and longitude
/// </summary>
/// <param name="lat_measurement_degrees">new measurement of lattidude</param>
/// <param name="lng_measurement">new measurement of longitude</param>
/// <param name="accuracy">measurement of 1 standard deviation error in metres</param>
/// <param name="TimeStamp_milliseconds">time of measurement</param>
/// <returns>new state</returns>
public void Process(double lat_measurement, double lng_measurement, float accuracy, long TimeStamp_milliseconds) {
if (accuracy < MinAccuracy) accuracy = MinAccuracy;
if (variance < 0) {
// if variance < 0, object is unitialised, so initialise with current values
this.TimeStamp_milliseconds = TimeStamp_milliseconds;
lat=lat_measurement; lng = lng_measurement; variance = accuracy*accuracy;
} else {
// else apply Kalman filter methodology
long TimeInc_milliseconds = TimeStamp_milliseconds - this.TimeStamp_milliseconds;
if (TimeInc_milliseconds > 0) {
// time has moved on, so the uncertainty in the current position increases
variance += TimeInc_milliseconds * Q_metres_per_second * Q_metres_per_second / 1000;
this.TimeStamp_milliseconds = TimeStamp_milliseconds;
// TO DO: USE VELOCITY INFORMATION HERE TO GET A BETTER ESTIMATE OF CURRENT POSITION
}
// Kalman gain matrix K = Covarariance * Inverse(Covariance + MeasurementVariance)
// NB: because K is dimensionless, it doesn't matter that variance has different units to lat and lng
float K = variance / (variance + accuracy * accuracy);
// apply K
lat += K * (lat_measurement - lat);
lng += K * (lng_measurement - lng);
// new Covarariance matrix is (IdentityMatrix - K) * Covarariance
variance = (1 - K) * variance;
}
}
}
Few ideas:
Try something like this:
SELECT DISTINCT TOP 10 p.id, pl.nm -- , pl.val, pl.txt_val
FROM dm.labs pl
JOIN mas_data.patients p
on pl.id = p.id
where pl.nm like '%LDL%'
and val is not null
ORDER BY pl.nm
Note that i commented out some of the SELECT to limit your result set and DISTINCT logic.
document.evaluate()
(DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.
Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.
For example:
NSArray *array = @[@"a", @"b", @"c"];
int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!
if (i == NSNotFound) {
// thought we'd get here, but we don't
NSLog(@"it's not here");
}
else {
// this is what actually happens
NSLog(@"it's here: %d", i);
// **** crash horribly ****
NSLog(@"the object is %@", array[i]);
}
Do you want to make the label (except for the text) transparent? Windows Forms (I assume WinForms - is this true) doesn't really support transparency. The easiest way, sometimes, is Label's Backcolor to Transparent.
label1.BackColor = System.Drawing.Color.Transparent;
You will run into problems though, as WinForms really doesn't properly support transparency. Otherwise, see here:
http://www.doogal.co.uk/transparent.php
http://www.codeproject.com/KB/dotnet/transparent_controls_net.aspx
http://www.daniweb.com/code/snippet216425.html
Setting the parent of a usercontrol prevents it from being transparent
Good luck!
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
For my case(ubuntu 14.04, fresh installed), I just run the following command and it works!
sudo apt-get install ssh
All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.
return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track)
and not about Please move or remove them before you can merge.
. You might have a look at the answers on Git - Won't add files?
There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.
Here is from pandas docs on advanced indexing:
The section will explain exactly what you need! Turns out df.loc
(as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.
df.loc[selection criteria, columns I want] = value
So Bren's answer is saying 'find me all the places where df.A == 0
, select column B
and set it to np.nan
'
protocol//[hosts][/database][?properties]
If you don't have any properties ignore it then it will be like
jdbc:mysql://127.0.0.1:3306/test
jdbc:mysql is the protocol 127.0.0.1: is the host and 3306 is the port number test is the database
Another problem that happened me twice:
In IIS Express's applicationhost.config
the order of the bindings does matter. One binding could take precedence over your SSL binding, making it not working.
Example:
<site name="MySite007" id="1">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\Users\myuser\projects\mysolutionfolder\MyProject.Service" />
</application>
<bindings>
<binding protocol="http" bindingInformation=":8081:localhost" />
<binding protocol="http" bindingInformation=":8080:" /><!-- evil binding -->
<binding protocol="https" bindingInformation="*:44327:localhost" />
</bindings>
</site>
You may have added a binding similar to the second one to be able to access your WebService from outside localhost
. Because this binding listens on any adress, it seems to override the SSL binding although a different port was used.
Remove the evil binding or move it down.
Variable number of arguments
It is possible to pass a variable number of arguments to a method. However, there are some restrictions:
To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:
private static int largest(int... numbers) {
int currentLargest = numbers[0];
for (int number : numbers) {
if (number > currentLargest) {
currentLargest = number;
}
}
return currentLargest;
}
source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012
Using CSS you cannot, CSS will only change the appearance of the span. However you can do it without changing the structure of the div by adding an onclick handler to the span:
<html>
<head>
</head>
<body>
<div>
<a href="http://www.google.com">
<span>title<br></span>
<span onclick='return false;'>description<br></span>
<span>some url</span>
</a>
</div>
</body>
</html>
You can then style it so that it looks un-clickable too:
<html>
<head>
<style type='text/css'>
a span.unclickable { text-decoration: none; }
a span.unclickable:hover { cursor: default; }
</style>
</head>
<body>
<div>
<a href="http://www.google.com">
<span>title<br></span>
<span class='unclickable' onclick='return false;'>description<br></span>
<span>some url</span>
</a>
</div>
</body>
</html>
If you have this error while you create segues with the view controllers not with the UI elements you have to change sender: Any?
to this
@IBAction func backButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "goToMainScreen", sender: self)
}
It will work.
Heres a Swift version:
// MARK: Gesture Extensions
extension UIView {
func addTapGesture(#tapNumber: Int, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer (target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
userInteractionEnabled = true
}
func addTapGesture(#tapNumber: Int, action: ((UITapGestureRecognizer)->())?) {
let tap = BlockTap (tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
userInteractionEnabled = true
}
}
If you have "something" and need 'something', use replace(col, "\"", "\'")
and viceversa.
I modified Nico's code to work for my needs.
$.fn.textWidth = function(){
var self = $(this),
children = self.contents(),
calculator = $('<span style="white-space:nowrap;" />'),
width;
children.wrap(calculator);
width = children.parent().width(); // parent = the calculator wrapper
children.unwrap();
return width;
};
I'm using .contents() as .children() does not return text nodes which I needed. I also found that the returned width was impacted by the viewport width which was causing wrapping so I'm using white-space:nowrap; to get the correct width regardless of viewport width.
Just set the width to 100vw like this:
<div id="container" style="width: 100vw">
<div id="help_panel" style="width: 100%; margin: 0 auto;">
Content goes here.
</div>
</div>
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value
, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
Follow a simple checklist:
ping 192.168.1.2
3306
i.e. it has not been modified.3306
and allow inbound connections in general.To set the status bar color, create a style.xml file under res/values-v21 folder with this content:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppBaseTheme" parent="AppTheme">
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/blue</item>
</style>
</resources>
I think you are simply exchanging dumps and loads.
>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
The first returns as a (JSON encoded) string its data argument:
>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:
>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True
To "automate" the process of importing the generated .sql
file, while avoiding all the traps that can be hidden in trying to pass files through stdin
and stdout
, just tell MySQL to execute the generated .sql
file using the SOURCE
command in MySQL.
The syntax in the short, but excellent, answer, from Kshitij Sood, gives the best starting point. In short, modify the OP's command according to Kshitij Sood's syntax and replace the commands in that with the SOURCE
command:
#!/bin/bash
mysql -u$user -p$password $dbname -Bse "SOURCE ds_fbids.sql
SOURCE ds_fbidx.sql"
If the database name is included in the generated .sql
file, it can be dropped from the command.
The presumption here is that the generated file is valid as an .sql
file on its own. By not having the file redirected, piped, or in any other manner handled by the shell, there is no issue with needing to escape any of the characters in the generated output because of the shell. The rules with respect to what needs to be escaped in an .sql
file, of course, still apply.
How to deal with the security issues around the password on the command line, or in a my.cnf
file, etc., has been well addressed in other answers, with some excellent suggestions. My favorite answer, from Danny, covers that, including how to handle the issue when dealing with cron
jobs, or anything else.
To address a comment (question?) on the short answer I mentioned: No, it cannot be used with a HEREDOC syntax, as that shell command is given. HEREDOC can be used in the redirection version syntax, (without the -Bse
option), since I/O redirection is what HEREDOC is built around. If you need the functionality of HEREDOC, it would be better to use it in the creation of a .sql
file, even if it's a temporary one, and use that file as the "command" to execute with the MySQL batch line.
#!/bin/bash
cat >temp.sql <<SQL_STATEMENTS
...
SELECT \`column_name\` FROM \`table_name\` WHERE \`column_name\`='$shell_variable';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql
Bear in mind that because of shell expansion you can use shell and environment variables within the HEREDOC. The down-side is that you must escape each and every backtick. MySQL uses them as the delimiters for identifiers but the shell, which gets the string first, uses them as executable command delimiters. Miss the escape on a single backtick of the MySQL commands, and the whole thing explodes with errors. The whole issue can be solved by using a quoted LimitString for the HEREDOC:
#!/bin/bash
cat >temp.sql <<'SQL_STATEMENTS'
...
SELECT `column_name` FROM `table_name` WHERE `column_name`='constant_value';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql
Removing shell expansion that way eliminates the need to escape the backticks, and other shell-special characters. It also removes the ability to use shell and environment variables within it. That pretty much removes the benefits of using a HEREDOC inside the shell script to begin with.
The other option is to use the multi-line quoted strings allowed in Bash with the batch syntax version (with the -Bse
). I don't know other shells, so I cannot say if they work therein as well. You would need to use this for executing more than one .sql
file with the SOURCE
command anyway, since that is not terminated by a ;
as other MySQL commands are, and only one is allowed per line. The multi-line string can be either single or double quoted, with the normal effects on shell expansion. It also has the same caveats as using the HEREDOC syntax does for backticks, etc.
A potentially better solution would be to use a scripting language, Perl, Python, etc., to create the .sql
file, as the OP did, and SOURCE
that file using the simple command syntax at the top. The scripting languages are much better at string manipulation than the shell is, and most have in-built procedures to handle the quoting and escaping needed when dealing with MySQL.
You should be able to do this with existing bootstrap classes and a little custom styling.
<form>
<div class="input-prepend">
<span class="add-on">
<i class="icon-user"></i>
</span>
<input class="span2" id="prependedInput" type="text" placeholder="Username" style="background-color: #eeeeee;border-left: #eeeeee;">
</div>
Edit The icon is referenced via the icon-user
class. This answer was written at the time of Bootstrap version 2. You can see the reference on the following page: http://getbootstrap.com/2.3.2/base-css.html#images
That is not how the PUBLIC_URL variable is used. According to the documentation, you can use the PUBLIC_URL in your HTML:
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
Or in your JavaScript:
render() {
// Note: this is an escape hatch and should be used sparingly!
// Normally we recommend using `import` for getting asset URLs
// as described in “Adding Images and Fonts” above this section.
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
The PUBLIC_URL is not something you set to a value of your choosing, it is a way to store files in your deployment outside of Webpack's build system.
To view this, run your CRA app and add this to the src/index.js
file:
console.log('public url: ', process.env.PUBLIC_URL)
You'll see the URL already exists.
Read more in the CRA docs.
Try initializing the ks
variable inside your submit function.
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
var ks = $('#keywords').val().split("\n");
e.preventDefault();
alert(ks[0]);
$.each(ks, function(k){
alert(k);
});
});
});
})(jQuery);
Use strtol
if you have libc available like the top answer suggests. However if you like custom stuff or are on a microcontroller without libc or so, you may want a slightly optimized version without complex branching.
#include <inttypes.h>
/**
* xtou64
* Take a hex string and convert it to a 64bit number (max 16 hex digits).
* The string must only contain digits and valid hex characters.
*/
uint64_t xtou64(const char *str)
{
uint64_t res = 0;
char c;
while ((c = *str++)) {
char v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
res = (res << 4) | (uint64_t) v;
}
return res;
}
The bit shifting magic boils down to: Just use the last 4 bits, but if it is an non digit, then also add 9.
According to http://php.net/manual/en/function.error-get-last.php, use:
print_r(error_get_last());
Which will return an array of the last error generated. You can access the [message]
element to display the error.
First, create a folder named “menu” in the “res” folder.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"/>
<item
android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="Add"/>
<item
android:id="@+id/edit"
android:icon="@android:drawable/ic_menu_edit"
android:title="Edit">
<menu>
<item
android:id="@+id/share"
android:icon="@android:drawable/ic_menu_share"
android:title="Share"/>
</menu>
</item>
</menu>
Then, create your Activity Class:
public class PopupMenu1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_menu_1);
}
public void onPopupButtonClick(View button) {
PopupMenu popup = new PopupMenu(this, button);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(PopupMenu1.this,
"Clicked popup menu item " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
}
a = ('x', 'y')
b = a + ('z',)
print(b)
a = ('x', 'y')
b = a + tuple('b')
print(b)
Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
this portion to
CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT
and change the following line too.
DECLARE NAME_FOUND TEXT DEFAULT "";
It should work.
Strangely enough, the solution ended up being to change
volumes:
- ./postgres-data:/var/lib/postgresql
to
volumes:
- ./postgres-data:/var/lib/postgresql/data
Thread.wait() call make sense inside a code that synchronizes on Thread.class object. I don't think it's what you meant.
You ask
How can I make a thread wait until it will be notified?
You can make only your current thread wait. Any other thread can be only gently asked to wait, if it agree.
If you want to wait for some condition, you need a lock object - Thread.class object is a very bad choice - it is a singleton AFAIK so synchronizing on it (except for Thread static methods) is dangerous.
Details for synchronization and waiting are already explained by Tom Hawtin.
java.lang.IllegalMonitorStateException
means you are trying to wait on object on which you are not synchronized - it's illegal to do so.
Use:
x.astype(int)
Here is the reference.
in Unix(including Linux) try 'which', in Windows try 'where'.
#include <stdio.h>
#define _UNIX
int main(int argc, char** argv)
{
char cmd[128];
char buf[128];
FILE* fp = NULL;
#if defined(_UNIX)
sprintf(cmd, "which %s > my.path", argv[0]);
#else
sprintf(cmd, "where %s > my.path", argv[0]);
#endif
system(cmd);
fp = fopen("my.path", "r");
fgets(buf, sizeof(buf), fp);
fclose(fp);
printf("full path: %s\n", buf);
unlink("my.path");
return 0;
}
Take a look at np.bincount
:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html
import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
y = np.bincount(x)
ii = np.nonzero(y)[0]
And then:
zip(ii,y[ii])
# [(1, 5), (2, 3), (5, 1), (25, 1)]
or:
np.vstack((ii,y[ii])).T
# array([[ 1, 5],
[ 2, 3],
[ 5, 1],
[25, 1]])
or however you want to combine the counts and the unique values.
I was facing the same problem as value was changing in one of the array in my component. But instead of detecting the changes on value change, I changed the component change detection strategy to onPush
(which will detect changes on object change and not on value change).
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
selector: -
......
})
The trouble is that you can not return a value from an asynchronous call, like an AJAX request, and expect it to work.
The reason is that the code waiting for the response has already executed by the time the response is received.
The solution to this problem is to run the necessary code inside the success:
callback. That way it is accessing the data
only when it is available.
function isSession(selector) {
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
success: function(data) {
// Run the code here that needs
// to access the data returned
return data;
},
error: function() {
alert('Error occured');
}
});
}
Another possibility (which is effectively the same thing) is to call a function inside your success:
callback that passes the data when it is available.
function isSession(selector) {
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
success: function(data) {
// Call this function on success
someFunction( data );
return data;
},
error: function() {
alert('Error occured');
}
});
}
function someFunction( data ) {
// Do something with your data
}
There is another library lodash, it has clone and cloneDeep.
clone
will clone your object but not create a new instance for non-primitive values, instead it will use the referrence to the original object
cloneDeep
will create literally new objects without having any referrence to the original object, so it more safe when you have to change the object afterwards.
Short ES6 code
const convertFrom12To24Format = (time12) => {
const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
const PM = period === 'PM';
const hours = (+sHours % 12) + (PM ? 12 : 0);
return `${('0' + hours).slice(-2)}:${minutes}`;
}
const convertFrom24To12Format = (time24) => {
const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
const period = +sHours < 12 ? 'AM' : 'PM';
const hours = +sHours % 12 || 12;
return `${hours}:${minutes} ${period}`;
}
To answer the original question specifically (using IO.FileAttributes):
Get-ChildItem c:\mypath -Recurse | Where-Object {$_.Attributes -and [IO.FileAttributes]::Directory}
I do prefer Marek's solution though (Where-Object { $_ -is [System.IO.DirectoryInfo] }
).
In case of Allow IP to mysql server linux machine. you can do following command--
nano /etc/httpd/conf.d/phpMyAdmin.conf and add Desired IP.
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
Order allow,deny
allow from all
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
Require ip 192.168.9.1(Desired IP)
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
#Allow from All
Allow from 192.168.9.1(Desired IP)
</IfModule>
And after Update, please restart using following command--
sudo systemctl restart httpd.service
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
You have two ways:
First go to the particular path of Android SDK:
1) Open your command prompt and traverse to the platform-tools directory through it such as
$ cd Frameworks\Android-Sdk\platform-tools
2) Run your adb commands now such as to know that your adb is working properly :
$ adb devices OR adb logcat OR simply adb
Second way is :
1) Right click on your My Computer.
2) Open Environment variables.
3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).
4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.
5) Restart your computer once.
6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.
Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"
Some time we need to set PATH variable for WINDOWS
%USERPROFILE%\AppData\Roaming\npm
After that test with where grunt
Note: Do not forget to close the command prompt window and reopen it.
Here is a javascript class that detects IE10, IE11 and Edge.
Navigator object is injected for testing purposes.
var DeviceHelper = function (_navigator) {
this.navigator = _navigator || navigator;
};
DeviceHelper.prototype.isIE = function() {
if(!this.navigator.userAgent) {
return false;
}
var IE10 = Boolean(this.navigator.userAgent.match(/(MSIE)/i)),
IE11 = Boolean(this.navigator.userAgent.match(/(Trident)/i));
return IE10 || IE11;
};
DeviceHelper.prototype.isEdge = function() {
return !!this.navigator.userAgent && this.navigator.userAgent.indexOf("Edge") > -1;
};
DeviceHelper.prototype.isMicrosoftBrowser = function() {
return this.isEdge() || this.isIE();
};
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseAfter some years with node, I can say that there are no conventions for the directory/file structure. However most (professional) express applications use a setup like:
/
/bin - scripts, helpers, binaries
/lib - your application
/config - your configuration
/public - your public files
/test - your tests
An example which uses this setup is nodejs-starter.
I personally changed this setup to:
/
/etc - contains configuration
/app - front-end javascript files
/config - loads config
/models - loads models
/bin - helper scripts
/lib - back-end express files
/config - loads config to app.settings
/models - loads mongoose models
/routes - sets up app.get('..')...
/srv - contains public files
/usr - contains templates
/test - contains test files
In my opinion, the latter matches better with the Unix-style directory structure (whereas the former mixes this up a bit).
I also like this pattern to separate files:
lib/index.js
var http = require('http');
var express = require('express');
var app = express();
app.server = http.createServer(app);
require('./config')(app);
require('./models')(app);
require('./routes')(app);
app.server.listen(app.settings.port);
module.exports = app;
lib/static/index.js
var express = require('express');
module.exports = function(app) {
app.use(express.static(app.settings.static.path));
};
This allows decoupling neatly all source code without having to bother dependencies. A really good solution for fighting nasty Javascript. A real-world example is nearby which uses this setup.
Update (filenames):
Regarding filenames most common are short, lowercase filenames. If your file can only be described with two words most JavaScript projects use an underscore as the delimiter.
Update (variables):
Regarding variables, the same "rules" apply as for filenames. Prototypes or classes, however, should use camelCase.
Update (styleguides):
To delete all stashes older than 40 days, use:
git reflog expire --expire-unreachable=40.days refs/stash
Add --dry-run
to see which stashes are deleted.
See https://stackoverflow.com/a/44829516/946850 for an explanation and much more detail.
You can either send a GET with a body or send a POST and give up RESTish religiosity (it's not so bad, 5 years ago there was only one member of that faith -- his comments linked above).
Neither are great decisions, but sending a GET body may prevent problems for some clients -- and some servers.
Doing a POST might have obstacles with some RESTish frameworks.
Julian Reschke suggested above using a non-standard HTTP header like "SEARCH" which could be an elegant solution, except that it's even less likely to be supported.
It might be most productive to list clients that can and cannot do each of the above.
Clients that cannot send a GET with body (that I know of):
Clients that can send a GET with body:
Servers & libraries that can retrieve a body from GET:
Servers (and proxies) that strip a body from GET:
$(document).ready(function() {_x000D_
$('#openFile').on('change', function(evt) {_x000D_
console.log(this.files[0].size);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">_x000D_
<input id="openFile" name="img" type="file" />_x000D_
</form>
_x000D_
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
#include <stdint.h>
uintptr_t
standard type defined in the included standard header file.Complete tutorial here
Demo link
JavaScript
$('.owl-carousel').owlCarousel({
margin: 10,
nav: true,
navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
});
CSS Style for navigation
.owl-carousel .nav-btn{
height: 47px;
position: absolute;
width: 26px;
cursor: pointer;
top: 100px !important;
}
.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}
.owl-carousel .prev-slide{
background: url(nav-icon.png) no-repeat scroll 0 0;
left: -33px;
}
.owl-carousel .next-slide{
background: url(nav-icon.png) no-repeat scroll -24px 0px;
right: -33px;
}
.owl-carousel .prev-slide:hover{
background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}
Since I never can remember that LINQ calls it Where
, Select
and Aggregate
instead of Filter
, Map
and Reduce
so I created a few extension methods you can use:
IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6
Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):
public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
return self.Select(selector);
}
public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
return self.Aggregate(func);
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
return self.Where(predicate);
}
Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :
What worked for me was updating Android Studio and updating JAVA_HOME and ANDROID_HOME environment variables. I believe it was caused due to the fact that I updated Java Version (through updater) but did not update jdk.
As Anton Gogolev noted, FileStream reads 4096 bytes at a time by default, But you can specify any other value using the FileStream constructor:
new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 16 * 1024 * 1024)
Note that Brad Abrams from Microsoft wrote in 2004:
there is zero benefit from wrapping a BufferedStream around a FileStream. We copied BufferedStream’s buffering logic into FileStream about 4 years ago to encourage better default performance
In [1]: df
Out[1]:
data
0 1
1 2
2 3
3 4
You want to apply a function that conditionally returns a value based on the selected dataframe column.
In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0 true
1 true
2 false
3 false
Name: data
You can then assign that returned column to a new column in your dataframe:
In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
In [4]: df
Out[4]:
data desired_output
0 1 true
1 2 true
2 3 false
3 4 false
Using JSTL:
<c:set var="message" value='${requestScope["Error_Message"]}' />
Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.
<c:out value="${message}"/>
Make sure to double the entry with an additional "www"-prefix. If you don't addresses like "www.acme.com" will not work!
You can easily import your model and run this:
from models import User
# User is the name of table that has a column name
users = User.query.all()
for user in users:
print user.name
Had the same problem,
All i had to do whas set the oracle shell variable:
. /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh
Sorterd!
I had a similar issue while writing a newsletter. So I had to inline the style this way:
<ol>
<li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
<li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
<li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
</ol>
if(strcmp(aString, bString) == 0){
//strings are the same
}
godspeed
Go to
For me the following works good. Just add it. You can edit it as per your requirement. This is just a nice trick I use.
text-shadow : 0 0 0 #your-font-color;
https://thomashunter.name/blog/simple-php-namespace-friendly-autoloader-class/
You’ll want to put your class files into a folder named Classes
, which is in the same directory as the entry point into your PHP application. If classes use namespaces, the namespaces will be converted into the directory structure.
Unlike a lot of other auto-loaders, underscores will not be converted into directory structures (it’s tricky to do PHP < 5.3 pseudo namespaces along with PHP >= 5.3 real namespaces).
<?php
class Autoloader {
static public function loader($className) {
$filename = "Classes/" . str_replace("\\", '/', $className) . ".php";
if (file_exists($filename)) {
include($filename);
if (class_exists($className)) {
return TRUE;
}
}
return FALSE;
}
}
spl_autoload_register('Autoloader::loader');
You’ll want to place the following code into your main PHP script (entry point):
require_once("Classes/Autoloader.php");
Here’s an example directory layout:
index.php
Classes/
Autoloader.php
ClassA.php - class ClassA {}
ClassB.php - class ClassB {}
Business/
ClassC.php - namespace Business; classC {}
Deeper/
ClassD.php - namespace Business\Deeper; classD {}
In my case, I was using Relative Layout
for a emptyString
After struggling on this for an hour. Only this worked for me:
android:layout_toRightOf="@id/welcome"
android:layout_toEndOf="@id/welcome"
android:layout_alignBaseline="@id/welcome"
layout_toRightOf
or layout_toEndOf
both works, but to support it better, I used both.
To make it more clear:
This was what I was trying to do:
And this was the emulator's output
Layout:
<TextView
android:id="@+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Welcome "
android:textSize="16sp" />
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/welcome"
android:layout_toRightOf="@id/welcome"
android:text="@string/emptyString"
android:textSize="16sp" />
Notice that:
android:layout_width="wrap_content"
worksGravity
is not used$_
is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ...
so $_
represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:
write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH
It's not only the optimization1. I don't like
"" + i
because it does not express what I really want to do 2.
I don't want to append an integer to an (empty) string. I want to convert an integer to string:
Integer.toString(i)
Or, not my prefered, but still better than concatenation, get a string representation of an object (integer):
String.valueOf(i)
1. For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.
2. this is not valid for use of real concatenation like in System.out.println("Index: " + i);
or String id = "ID" + i;
For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:
from scipy.ndimage.filters import gaussian_filter1d
ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()
if you increase sigma you can get a more smoothed function.
Proceed with caution with this one. It modifies the original values and may not be what you want.
I think this is what you were looking for:
grep -E "string1|string2" filename
I think that answers like this:
grep 'string1.*string2\|string2.*string1' filename
only match the case where both are present, not one or the other or both.
Another common use is for std containers to do equality comparison on key values inside custom objects
class Foo
{
public: int val;
};
class Comparer { public:
bool operator () (Foo& a, Foo&b) const {
return a.val == b.val;
};
class Blah
{
std::set< Foo, Comparer > _mySet;
};
text='Python'
searches for elements that have the exact text you provided:
import re
from BeautifulSoup import BeautifulSoup
html = """<p>exact text</p>
<p>almost exact text</p>"""
soup = BeautifulSoup(html)
print soup(text='exact text')
print soup(text=re.compile('exact text'))
[u'exact text']
[u'exact text', u'almost exact text']
"To see if the string 'Python' is located on the page http://python.org":
import urllib2
html = urllib2.urlopen('http://python.org').read()
print 'Python' in html # -> True
If you need to find a position of substring within a string you could do html.find('Python')
.
Considering existing answers, I've copy-pasted and enhanced source code of Integer.parseInt
to do the job, and my solution
Ints.tryParse()
),int[]
, Box
, OptionalInt
),CharSequence
or a part of it instead of a whole String
,Integer.parseInt
can, i.e. [2,36],The only downside is that there's no difference between toIntOfDefault("-1", -1)
and toIntOrDefault("oops", -1)
.
public static int toIntOrDefault(CharSequence s, int def) {
return toIntOrDefault0(s, 0, s.length(), 10, def);
}
public static int toIntOrDefault(CharSequence s, int def, int radix) {
radixCheck(radix);
return toIntOrDefault0(s, 0, s.length(), radix, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int def) {
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, 10, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int radix, int def) {
radixCheck(radix);
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, radix, def);
}
private static int toIntOrDefault0(CharSequence s, int start, int endExclusive, int radix, int def) {
if (start == endExclusive) return def; // empty
boolean negative = false;
int limit = -Integer.MAX_VALUE;
char firstChar = s.charAt(start);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+') {
return def;
}
start++;
// Cannot have lone "+" or "-"
if (start == endExclusive) return def;
}
int multmin = limit / radix;
int result = 0;
while (start < endExclusive) {
// Accumulating negatively avoids surprises near MAX_VALUE
int digit = Character.digit(s.charAt(start++), radix);
if (digit < 0 || result < multmin) return def;
result *= radix;
if (result < limit + digit) return def;
result -= digit;
}
return negative ? result : -result;
}
private static void radixCheck(int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
throw new NumberFormatException(
"radix=" + radix + " ? [" + Character.MIN_RADIX + "," + Character.MAX_RADIX + "]");
}
private static void boundsCheck(int start, int endExclusive, int len) {
if (start < 0 || start > len || start > endExclusive)
throw new IndexOutOfBoundsException("start=" + start + " ? [0, min(" + len + ", " + endExclusive + ")]");
if (endExclusive > len)
throw new IndexOutOfBoundsException("endExclusive=" + endExclusive + " > s.length=" + len);
}
Run ps
and determine the PID of your node process.
Then, run sudo kill PID
Use tasklist to display the list of running processes:
tasklist /O
Then, kill the node process like so (using the PID obtained from the tasklist
command):
taskkill /pid PID
I am seeing starkly different runtimes when I take a for loop in g++ 4.7.0 and using
std::vector<double> x;
std::vector<double> y;
std::vector<double> prod;
for (int i = 0; i < 5000000; i++)
{
double r1 = ((double)rand() / double(RAND_MAX)) * 5;
double r2 = ((double)rand() / double(RAND_MAX)) * 5;
x.push_back(r1);
y.push_back(r2);
}
int sz = x.size();
#pragma omp parallel for
for (int i = 0; i< sz; i++)
prod[i] = x[i] * y[i];
the serial code (no openmp
) runs in 79 ms.
the "parallel for" code runs in 29 ms.
If I omit the for
and use #pragma omp parallel
, the runtime shoots up to 179ms,
which is slower than serial code. (the machine has hw concurrency of 8)
the code links to libgomp
Nouns.h
doesn't include <string>
, but it needs to. You need to add
#include <string>
at the top of that file, otherwise the compiler doesn't know what std::string
is when it is encountered for the first time.
There is also the env_inst_info admin view. As with CanSpice I can only vouch for LUW, but there should at least be a similar view available for Z/OS.
SELECT * FROM SYSIBMADM.ENV_INST_INFO
Use this code in Swift
func tappGeastureAction(sender: AnyObject) {
if let tap = sender as? UITapGestureRecognizer {
let point = tap.locationInView(locatedView)
if filterView.pointInside(point, withEvent: nil) == true {
// write your stuff here
}
}
}
OpenJPA allows you to specify non-standard annotation to define index on property.
Details are here.
I had Xamarin installed and tried to use Unity. Basically in any case you have to kill any application that might be talking to your device through ADB
You can use querySelectorAll:
document.querySelectorAll('[data-foo]');
I use below in my MR project.
<exclusions>
<exclusion>
<artifactId>jdk.tools</artifactId>
<groupId>jdk.tools</groupId>
</exclusion>
</exclusions>
<h1 style="display:inline-block;text-align: center;background : red;">The Last Will and Testament of Eric Jones</h1>
_x000D_
I've recently had to use eval
to force multiple brace expansions to be evaluated in the order I needed. Bash does multiple brace expansions from left to right, so
xargs -I_ cat _/{11..15}/{8..5}.jpg
expands to
xargs -I_ cat _/11/8.jpg _/11/7.jpg _/11/6.jpg _/11/5.jpg _/12/8.jpg _/12/7.jpg _/12/6.jpg _/12/5.jpg _/13/8.jpg _/13/7.jpg _/13/6.jpg _/13/5.jpg _/14/8.jpg _/14/7.jpg _/14/6.jpg _/14/5.jpg _/15/8.jpg _/15/7.jpg _/15/6.jpg _/15/5.jpg
but I needed the second brace expansion done first, yielding
xargs -I_ cat _/11/8.jpg _/12/8.jpg _/13/8.jpg _/14/8.jpg _/15/8.jpg _/11/7.jpg _/12/7.jpg _/13/7.jpg _/14/7.jpg _/15/7.jpg _/11/6.jpg _/12/6.jpg _/13/6.jpg _/14/6.jpg _/15/6.jpg _/11/5.jpg _/12/5.jpg _/13/5.jpg _/14/5.jpg _/15/5.jpg
The best I could come up with to do that was
xargs -I_ cat $(eval echo _/'{11..15}'/{8..5}.jpg)
This works because the single quotes protect the first set of braces from expansion during the parsing of the eval
command line, leaving them to be expanded by the subshell invoked by eval
.
There may be some cunning scheme involving nested brace expansions that allows this to happen in one step, but if there is I'm too old and stupid to see it.
Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo'
, then the selector will be 'td[id^="foo"]'
.
Note that the quotes are mandatory: [id^="...."]
.
Source: http://api.jquery.com/attribute-starts-with-selector/
Using xampp, this will work (php7 has been extracted to the xampp\php directory):
Make the following changes in the php.ini:
;extension=php_mbstring.dll
;extension=php_mysqli.dll
extension_dir = "ext"
to the full path, for example:
extension_dir = "C:\xammp\php\ext"
Additional, change the xampp-settings in the httpd-xampp.conf:
LoadFile "C:/xampp/php/php5ts.dll"
to
LoadFile "C:/xampp/php/php7ts.dll"
LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"
to
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
IfModule php5_module
to
IfModule php7_module
That's it.
hope this would help:
window.location.href = '/url_after_domain';
Just in case this helps anyone, when doing this from C# code behind I had to use a double escape character or I got an "unterminated string constant" JavaScript error:
ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptName", "alert(\"Line 1.\\n\\nLine 2.\");", true);
if the error is
Line 26:
Line 27: @foreach (Customers customer in Model)
Line 28: {
Line 29:
give the full name space
like
@foreach (Start.Models.customer customer in Model)
That would just be:
Console.WriteLine(Variables.name);
and it needs to be public also:
public class Variables
{
public static string name = "";
}
If we want to bind to a dictionary ie
<ComboBox SelectedValue="{Binding Pathology, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{x:Static RnxGlobal:CLocalizedEnums.PathologiesValues}" DisplayMemberPath="Value" SelectedValuePath="Key"
Margin="{StaticResource SmallMarginLeftBottom}"/>
then SelectedItem will not work whilist SelectedValue will
You can use FolderBrowserDialog instead of FileDialog and get the path from the OK result.
FolderBrowserDialog browser = new FolderBrowserDialog();
string tempPath ="";
if (browser.ShowDialog() == DialogResult.OK)
{
tempPath = browser.SelectedPath; // prints path
}
Here's a complete read, update and write example.
Input file, test.ini
[section_a]
string_val = hello
bool_val = false
int_val = 11
pi_val = 3.14
Working code.
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser # ver. < 3.0
# instantiate
config = ConfigParser()
# parse existing file
config.read('test.ini')
# read values from a section
string_val = config.get('section_a', 'string_val')
bool_val = config.getboolean('section_a', 'bool_val')
int_val = config.getint('section_a', 'int_val')
float_val = config.getfloat('section_a', 'pi_val')
# update existing value
config.set('section_a', 'string_val', 'world')
# add a new section and some values
config.add_section('section_b')
config.set('section_b', 'meal_val', 'spam')
config.set('section_b', 'not_found_val', '404')
# save to a file
with open('test_update.ini', 'w') as configfile:
config.write(configfile)
Output file, test_update.ini
[section_a]
string_val = world
bool_val = false
int_val = 11
pi_val = 3.14
[section_b]
meal_val = spam
not_found_val = 404
The original input file remains untouched.
XAMPP comes preloaded with the FileZilla FTP server. Here is how to setup the service, and create an account.
Enable the FileZilla FTP Service through the XAMPP Control Panel to make it startup automatically (check the checkbox next to filezilla to install the service). Then manually start the service.
Create an ftp account through the FileZilla Server Interface (its the essentially the filezilla control panel). There is a link to it Start Menu in XAMPP folder. Then go to Users->Add User->Stuff->Done.
Try connecting to the server (localhost, port 21).
To compare each item with the next one in an iterator without instantiating a list:
import itertools
it = (x for x in range(10))
data1, data2 = itertools.tee(it)
data2.next()
for a, b in itertools.izip(data1, data2):
print a, b
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
It is a function that has no name. For e.g. in c# you can use
numberCollection.GetMatchingItems<int>(number => number > 5);
to return the numbers that are greater than 5.
number => number > 5
is the lambda part here. It represents a function which takes a parameter (number) and returns a boolean value (number > 5). GetMatchingItems method uses this lambda on all the items in the collection and returns the matching items.
Visual Studio Code currently does not support bookmarks natively. Please add this as feature request to our Git Hub issue list (https://github.com/Microsoft/vscode).
In the meantime there are some ways to navigate around the code based on your navigation history. You can Ctrl+Tab to quickly jump to previously opened files. You can also navigate within your code based on cursor positions using Goto | Back and Goto | Forward.
I think you just need to add 2 more options (contentType
and dataType
):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
You can download and import all of Bootstrap, and Popper, with a single command using Fetch Injection:
fetchInject([
'https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js',
'https://cdn.jsdelivr.net/popper.js/1.0.0-beta.3/popper.min.js'
], fetchInject([
'https://cdn.jsdelivr.net/jquery/3.1.1/jquery.slim.min.js',
'https://npmcdn.com/[email protected]/dist/js/tether.min.js'
]));
Add CSS files if you need those too. Adjust versions and external sources to meet your needs and consider using sub-resource integrity checking if you're not hosting the files on your own domain or don't trust the source.
I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
The link has a fairly good example of when and why you may need to escape &
to &
https://jsfiddle.net/vh2h7usk/1/
Interestingly, I had to escape the character in order to represent it properly in my answer here. If I were to use the built-in code sample option (from the answer panel), I can just type in &
and it appears as it should. But if I were to manually use the <code></code>
element, then I have to escape in order to represent it correctly :)
First drop
your foreign key and try your above command, put add constraint
instead of modify constraint
.
Now this is the command:
ALTER TABLE child_table_name
ADD CONSTRAINT fk_name
FOREIGN KEY (child_column_name)
REFERENCES parent_table_name(parent_column_name)
ON DELETE CASCADE;
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
First run your application from eclipse to create launch configuration. Then just follow the steps:
- From the menu bar's File menu, select Export.
- Expand the Java node and select Runnable JAR file. Click Next.
- In the Runnable JAR File Specification page, select a 'Java Application' launch configuration to use to create a runnable JAR.
- In the Export destination field, either type or click Browse to select a location for the JAR file.
- Select an appropriate library handling strategy.
- Optionally, you can also create an ANT script to quickly regenerate a previously created runnable JAR file.
Source: Creating a New Runnable JAR File at Eclipse.org
CORS headers should be sent from the server. If you use PHP it will be like this:
header('Access-Control-Allow-Origin: your-host');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: your-methods like POST,GET');
header('Access-Control-Allow-Headers: content-type or other');
header('Content-Type: application/json');
I am surprised that none of the answers mentioned the insertAdjacentHTML()
method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.
Basic usage:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');
Edit the tty configuration in /etc/init/tty*.conf
with a shellscript as a parameter :
(...)
exec /sbin/getty -n -l theInputScript.sh -8 38400 tty1
(...)
This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.
A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.
Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
You can use result emitted from previous Observable thanks to mergeMap (or his alias flatMap) operator like this:
const one = Observable.of('https://api.github.com/users');
const two = (c) => ajax(c);//ajax from Rxjs/dom library
one.mergeMap(two).subscribe(c => console.log(c))
fyi <form>
supports :before
/ :after
as well, might be of help if you wrap your <input>
element with it... (got myself a design issue with that too)
It's new in the Bootstrap 3.0.1 release, so make sure you have the latest (10/29)...
Demo: http://bootply.com/91632
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
<div class="center-block" style="width:200px;background-color:#ccc;">...</div>_x000D_
</div>
_x000D_
In my case, Python was unable to find it because I'd put the code inside a module with hyphens, e.g. my-module
. When I changed it to my_module
it worked.
No need of use addition CSS/JS (Tested)
data-toggle="dropdown"
- for Clickable (can use Mobile as well web)data-hover="dropdown"
- for Hover (web only, because mobile doesn't have feature HOVER
)data-toggle="dropdown"
)/*!
* this CSS code just for snippet preview purpose. Please omit when using it.
*/
#bs-example-navbar-collapse-1 ul li {
float: left;
}
#bs-example-navbar-collapse-1 ul li ul li {
float: none !important;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a class="" href="">Home</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
subnav1
</a>
<ul class="dropdown-menu">
<li><a href="">Sub1</a></li>
<li><a href="">Sub2</a></li>
<li><a href="">Sub3</a></li>
<li><a href="">Sub4</a></li>
<li><a href="">Sub5</a></li>
<li><a href="">Sub6</a></li>
</ul>
<div class="clear"></div>
</li>
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">
subnav2
</a>
<ul class="dropdown-menu">
<li><a href="">Sub1</a></li>
<li><a href="">Sub2</a></li>
<li><a href="">Sub3</a></li>
<li><a href="">Sub4</a></li>
<li><a href="">Sub5</a></li>
<li><a href="">Sub6</a></li>
</ul>
<div class="clear"></div>
</li>
</ul>
</div>
<br>
<br>
<p><b>Please Note:</b> added css code not related to Bootstrap navigation. It's just for snippet preview purpose </p>
_x000D_
Output
I received this error when I had a config file with <?php
on the second line instead of the first.
adb uninstall <package_name>
can be used to uninstall an app via your PC. If you want this to happen automatically every time you launch your app via Android Studio, you can do this:
adb
in Program: and uninstall <your-package-name>
in Parameters:.
Make sure that the new item is selected when you click Ok in the popup window.Note: If you do not have adb in your PATH environment variable, give the full path to adb in Program: field (eg /home/user/android/sdk/platform-tools/adb).
Explanation and working solution here: Howto: div with onclick inside another div with onclick javascript
by executing this script in your inner click handler:
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
use:
std::vector <Acard> playerHand;
everywhere qualify it by std::
or do:
using std::vector;
in your cpp file.
You have to do this because vector
is defined in the std
namespace and you do not tell your program to find it in std
namespace, you need to tell that.
This is my test. Hope it is useful.
# $COMMAND is the command used to create the reverse ssh tunnel
COMMAND="ssh -p $SSH_PORT -q -N -R $REMOTE_HOST:$REMOTE_HTTP_PORT:localhost:80 $USER_NAME@$REMOTE_HOST"
# Is the tunnel up? Perform two tests:
# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND
# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
ssh -p $SSH_PORT $USER_NAME@$REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_HTTP_PORT.*LISTEN" \
> /dev/null 2>&1
if [ $? -ne 0 ] ; then
pkill -f -x "$COMMAND"
$COMMAND
fi
How can I check to see if a database in SQL Server is case-sensitive?
You can use below query that returns your informed database is case sensitive or not or is in binary sort(with null result):
;WITH collations AS (
SELECT
name,
CASE
WHEN description like '%case-insensitive%' THEN 0
WHEN description like '%case-sensitive%' THEN 1
END isCaseSensitive
FROM
sys.fn_helpcollations()
)
SELECT *
FROM collations
WHERE name = CONVERT(varchar, DATABASEPROPERTYEX('yourDatabaseName','collation'));
For more read this MSDN information ;).
I use this code in the SQLiteOpenHelper
in one of my applications to import a database file.
EDIT: I pasted my FileUtils.copyFile()
method into the question.
SQLiteOpenHelper
public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";
/**
* Copies the database file at the specified location over the current
* internal application database.
* */
public boolean importDatabase(String dbPath) throws IOException {
// Close the SQLiteOpenHelper so it will commit the created empty
// database to internal storage.
close();
File newDb = new File(dbPath);
File oldDb = new File(DB_FILEPATH);
if (newDb.exists()) {
FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
// Access the copied database so SQLiteHelper will cache it and mark
// it as created.
getWritableDatabase().close();
return true;
}
return false;
}
FileUtils
public class FileUtils {
/**
* Creates the specified <code>toFile</code> as a byte for byte copy of the
* <code>fromFile</code>. If <code>toFile</code> already exists, then it
* will be replaced with a copy of <code>fromFile</code>. The name and path
* of <code>toFile</code> will be that of <code>toFile</code>.<br/>
* <br/>
* <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
* this function.</i>
*
* @param fromFile
* - FileInputStream for the file to copy from.
* @param toFile
* - FileInputStream for the file to copy to.
*/
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
}
Don't forget to delete the old database file if necessary.
$ is used to DISTINGUISH between common variables and jquery variables in case of normal variables. let you place a order in FLIPKART then if the order is a variable showing you the string output then it is named simple as "order" but if we click on place order then an object is returned that object will be denoted by $ as "$order" so that the programmer may able to snip out the javascript variables and jquery variables in the entire code.
java.exe
is the console app while javaw.exe
is windows app (console-less). You can't have Console
with javaw.exe
.
Popen expect a list of strings for non-shell calls and a string for shell calls.
Call subprocess.Popen with shell=True:
process = subprocess.Popen(command, stdout=tempFile, shell=True)
Hopefully this solves your issue.
This issue is listed here: https://bugs.python.org/issue17023
Here is an example of SIGSEGV.
root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
int * p ;
* p = 0x1234;
return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c
root@pierr-desktop:/opt/playGround# ./test
Segmentation fault
And here is the detail.
How to handle it?
Avoid it as much as possible in the first place.
Program defensively: use assert(), check for NULL pointer , check for buffer overflow.
Use static analysis tools to examine your code.
compile your code with -Werror -Wall.
Has somebody review your code.
When that actually happened.
Examine you code carefully.
Check what you have changed since the last time you code run successfully without crash.
Hopefully, gdb will give you a call stack so that you know where the crash happened.
EDIT : sorry for a rush. It should be *p = 0x1234;
instead of p = 0x1234
;
To be honest, as other posters have mentioned, Wikipedia has a very good article on this so have a look there. This type of error is very common and often called other things such as Access Violation or General Protection Fault.
They are no different in C, C++ or any other language that allows pointers. These kinds of errors are usually caused by pointers that are
Some readable python:
def JoeCalimar(l):
masterList = []
for i in l:
for j in l:
masterList.append(1.*i/j)
pos = masterList.index(min(masterList))
a = pos/len(masterList)
b = pos%len(masterList)
return (l[a],l[b])
Let me know if something is not clear.
Rollback one step. Natively.
php artisan migrate:rollback --step=1
And here's the manual page: docs.
No way to do without some hassle. For details, check Martin Bean's answer.
There are many metrics out there for evaluating whether two images look like/how much they look like.
I will not go into any code here, because I think it should be a scientific problem, other than a technical problem.
Generally, the question is related to human's perception on images, so each algorithm has its support on human visual system traits.
Classic approaches are:
Visible differences predictor: an algorithm for the assessment of image fidelity (https://www.spiedigitallibrary.org/conference-proceedings-of-spie/1666/0000/Visible-differences-predictor--an-algorithm-for-the-assessment-of/10.1117/12.135952.short?SSO=1)
Image Quality Assessment: From Error Visibility to Structural Similarity (http://www.cns.nyu.edu/pub/lcv/wang03-reprint.pdf)
FSIM: A Feature Similarity Index for Image Quality Assessment (https://www4.comp.polyu.edu.hk/~cslzhang/IQA/TIP_IQA_FSIM.pdf)
Among them, SSIM (Image Quality Assessment: From Error Visibility to Structural Similarity ) is the easiest to calculate and its overhead is also small, as reported in another paper "Image Quality Assessment Based on Gradient Similarity" (https://www.semanticscholar.org/paper/Image-Quality-Assessment-Based-on-Gradient-Liu-Lin/2b819bef80c02d5d4cb56f27b202535e119df988).
There are many more other approaches. Take a look at Google Scholar and search for something like "visual difference", "image quality assessment", etc, if you are interested/really care about the art.
1.Define Function to get Token from server
@function
{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
2.Get token and set header before send to server
var token = '@TokenHeaderValue()';
$http({
method: "POST",
url: './MainBackend/MessageDelete',
data: dataSend,
headers: {
'RequestVerificationToken': token
}
}).success(function (data) {
alert(data)
});
3. Onserver Validation on HttpRequestBase on method you handle Post/get
string cookieToken = "";
string formToken = "";
string[] tokens = Request.Headers["RequestVerificationToken"].Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
AntiForgery.Validate(cookieToken, formToken);
^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$
should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.
Explanation:
^ # start of string
\s* # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s* # optional whitespace
\( # a (
\s* # optional whitespace
(\d+) # a number, capture the match
\D+ # one or more non-digits
(\d+) # a number, capture the match
\D+ # one or more non-digits
\) # a )
\s* # optional whitespace
$ # end of string
With JUnit5 I think the best way is to @ExtendWith(MockitoExtension.class) with @Mock in the method parameter or the field.
The following example demonstrates that with Hamcrest matchers.
package com.vogella.junit5;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.verify;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class MockitoArgumentCaptureTest {
@Captor
private ArgumentCaptor<List<String>> captor;
@Test
public final void shouldContainCertainListItem(@Mock List<String> mockedList) {
var asList = Arrays.asList("someElement_test", "someElement");
mockedList.addAll(asList);
verify(mockedList).addAll(captor.capture());
List<String> capturedArgument = captor.getValue();
assertThat(capturedArgument, hasItem("someElement"));
}
}
See https://www.vogella.com/tutorials/Mockito/article.html for the required Maven/Gradle dependencies.
Check the following example:
// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'
That would be the modulo operator, which produces the remainder of the division of two numbers.
Note, disable wordwrap, otherwise it will not work properly if your lines are longer than sublime's width.
Try this:
<?php
$servername = "localhost";
$database = "database";
$username = "user";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
You can also simply convert a 2D array into hash using:
1.9.3p362 :005 > a= [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
1.9.3p362 :006 > h = Hash[a]
=> {1=>2, 3=>4}
Not sure if this work everywhere.
I'm using ipython in ubuntu.
If you want to read file in current folder's sub-directory:
/current-folder/sub-directory/data.csv
your script is in current-folder simply try this:
import pandas as pd
path = './sub-directory/data.csv'
pd.read_csv(path)
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
//works in IE, not sure about other browsers...
alert(classes[x].style.cssText);
I use this type of decorator in some debugging situations, it allows overriding class properties by decorating, without having to find the calling function.
class myclass(object):
def __init__(self):
self.property = "HELLO"
@adecorator(property="GOODBYE")
def method(self):
print self.property
Here is the decorator code
class adecorator (object):
def __init__ (self, *args, **kwargs):
# store arguments passed to the decorator
self.args = args
self.kwargs = kwargs
def __call__(self, func):
def newf(*args, **kwargs):
#the 'self' for a method function is passed as args[0]
slf = args[0]
# replace and store the attributes
saved = {}
for k,v in self.kwargs.items():
if hasattr(slf, k):
saved[k] = getattr(slf,k)
setattr(slf, k, v)
# call the method
ret = func(*args, **kwargs)
#put things back
for k,v in saved.items():
setattr(slf, k, v)
return ret
newf.__doc__ = func.__doc__
return newf
Note: because I've used a class decorator you'll need to use @adecorator() with the brackets on to decorate functions, even if you don't pass any arguments to the decorator class constructor.
(function(f){
if(document.readyState != "loading") f();
else document.addEventListener("DOMContentLoaded", f);
})(function(){
console.log("The Document is ready");
});
Your CLASSPATH
needs to know of the location of your HelloWorld
class also.
In simple terms you should append dot .
(means current directory) in the CLASSPATH
if you are running javac
and java
commands from DOS prompt.
This appear to be default behaviour now, so it's enough to do:
$("#press-enter").on("click", function(){alert("You `clicked' or 'Entered' me!")})
You can try it in this JSFiddle
Tested on: Chrome 56.0 and Firefox (Dev Edition) 54.0a2, both with jQuery 2.2.x and 3.x
//best and simple way to show keys and values
//initialize map
Map<Integer, String> map = new HashMap<Integer, String>();
//Add some values
map.put(1, "Hi");
map.put(2, "Hello");
// iterate map using entryset in for loop
for(Entry<Integer, String> entry : map.entrySet())
{ //print keys and values
System.out.println(entry.getKey() + " : " +entry.getValue());
}
//Result :
1 : Hi
2 : Hello
These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x)
to ask the question you want to ask with respect to the type of x:
js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false