The accepted answer works for me only for the first 30 characters. This works for me:
select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name
You are making it complicated. string
is already nullable. You don't need to make it more nullable. Take out the ?
on the property type.
I branched off from the accepted answer to only run when the click is being HELD down and dragged.
My function was running when I wasn't holding the mouse down. Here's the updated code if you also want this functionality:
var isDragging = false;
var mouseDown = false;
$('.test_area')
.mousedown(function() {
isDragging = false;
mouseDown = true;
})
.mousemove(function(e) {
isDragging = true;
if (isDragging === true && mouseDown === true) {
my_special_function(e);
}
})
.mouseup(function(e) {
var wasDragging = isDragging;
isDragging = false;
mouseDown = false;
if ( ! wasDragging ) {
my_special_function(e);
}
}
);
You can simply use This one line code to get date in year-month-date format
var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
This is very late, but I just wanted to add that there is a more elegant way: using reversed
for i in reversed(range(10)):
print i
gives:
4
3
2
1
0
I finally discover the error. The problem is that the primary key constraint name is equal the table name. I don know how postgres represents constraints, but I think the error "Relation already exists" was being triggered during the creation of the primary key constraint because the table was already declared. But because of this error, the table wasnt created at the end.
source URL for image can be a URL on a website like http://www.google.co.il/images/srpr/nav_logo73.png or https://https.openbsd.org/images/tshirt-26_front.gif or if you want to use a local file try this: url("file:///MacintoshHDOriginal/Users/lowri/Desktop/acgnx/image s/images/acgn-site-background-X_07.jpg")
Use it in this way:
buttonOBJ.getBackground().setColorFilter(Color.parseColor("#YOUR_HEX_COLOR_CODE"), PorterDuff.Mode.MULTIPLY);
if your using @Aspect an option is add this method inside your Aspect and send the JoinPoint and the name of parameter you need.
private Object getParameter(ProceedingJoinPoint joinPoint, String parameterName) {
Object valueParameter = null;
if (Objects.nonNull(joinPoint) && joinPoint.getSignature() instanceof MethodSignature
&& Objects.nonNull(parameterName) ) {
MethodSignature method = (MethodSignature)joinPoint.getSignature();
String[] parameters = method.getParameterNames();
for (int t = 0; t< parameters.length; t++) {
if( Objects.nonNull(parameters[t]) && parameters[t].equals(parameterName)) {
Object[] obj = joinPoint.getArgs();
valueParameter = obj[t];
}
}
}
return valueParameter;
}
and the call example:
Object parameterObject = getParameter(joinPoint, "nameClient");
if ( Objects.nonNull(parameterObject) ) {
String parametro = String.valueOf(parameterObject);
}
Only need know the type of object for convert
You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
then you change your user to postgresql, you may login successfully.
su postgresql
for (String key : Collections.list(e))
System.out.println(key);
Another method is to use the io/ioutil
and strings
libraries to read the entire file's bytes, convert them into a string and split them using a "\n
" (newline) character as the delimiter, for example:
import (
"io/ioutil"
"strings"
)
func main() {
bytesRead, _ := ioutil.ReadFile("something.txt")
file_content := string(bytesRead)
lines := strings.Split(file_content, "\n")
}
Technically you're not reading the file line-by-line, however you are able to parse each line using this technique. This method is applicable to smaller files. If you're attempting to parse a massive file use one of the techniques that reads line-by-line.
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
Node.js v10.0.0+
const fs = require('fs')
const { promisify } = require('util')
const pipeline = promisify(require('stream').pipeline)
await pipeline(
fs.createReadStream('source/file/path'),
fs.createWriteStream('destination/file/path')
).catch(err => {
// error handling
})
fs.unlink('source/file/path')
The simplest solution for removing that error was running the command
cap.release()
cv2.closeAllWindows()
That worked for me and also sometimes restarting the kernel was required because of old processes running in the background.
If the image isn't in the working directory then also it wont be working for that try to place the image file in pwd in the same folder as there is code else provide the full path to the image file or folder.
To avoid this problem in future try to code with exceptional handling so that if incorrect termination happens for some random reason the capturing device would get released after the program gets over.
WAI-ARIA is a spec defining support for accessible web apps. It defines bunch of markup extensions (mostly as attributes on HTML5 elements), which can be used by the web app developer to provide additional information about the semantics of the various elements to assistive technologies like screen readers. Of course, for ARIA to work, the HTTP user agent that interprets the markup needs to support ARIA, but the spec is created in such a way, as to allow down-level user agents to ignore the ARIA-specific markup safely without affecting the web app's functionality.
Here's an example from the ARIA spec:
<ul role="menubar">
<!-- Rule 2A: "File" label via aria-labelledby -->
<li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel"><span id="fileLabel">File</span>
<ul role="menu">
<!-- Rule 2C: "New" label via Namefrom:contents -->
<li role="menuitem" aria-haspopup="false">New</li>
<li role="menuitem" aria-haspopup="false">Open…</li>
...
</ul>
</li>
...
</ul>
Note the role
attribute on the outer <ul>
element. This attribute does not affect in any way how the markup is rendered on the screen by the browser; however, browsers that support ARIA will add OS-specific accessibility information to the rendered UI element, so that the screen reader can interpret it as a menu and read it aloud with enough context for the end-user to understand (for example, an explicit "menu" audio hint) and is able to interact with it (for example, voice navigation).
A quicker way to write it
var arrayBuffer = new Uint8Array(nodeBuffer).buffer;
However, this appears to run roughly 4 times slower than the suggested toArrayBuffer function on a buffer with 1024 elements.
This works in Swift 3.0:
btn.titleLabel?.font = UIFont(name:"Times New Roman", size: 20)
The u means the strings are unicode. Translate all the strings to ascii to get rid of it:
a.encode('ascii', 'ignore')
extern "C"
is a linkage specification which is used to call C functions in the Cpp source files. We can call C functions, write Variables, & include headers. Function is declared in extern entity & it is defined outside. Syntax is
Type 1:
extern "language" function-prototype
Type 2:
extern "language"
{
function-prototype
};
eg:
#include<iostream>
using namespace std;
extern "C"
{
#include<stdio.h> // Include C Header
int n; // Declare a Variable
void func(int,int); // Declare a function (function prototype)
}
int main()
{
func(int a, int b); // Calling function . . .
return 0;
}
// Function definition . . .
void func(int m, int n)
{
//
//
}
I just ran into a similar issue. When I changed my script reference from self-closing tags (ie, <script src=".." />
) to empty nodes (ie, <script src=".."></script>
) my errors went away and I could suddenly reference the jQuery UI functions.
At the time, I didn't realize this was just a brain-fart of me not closing it properly to begin with. (I'm posting this simply on the chance that anyone else coming across the thread is having a similar issue.)
Well, for starters, you might not wanna overuse echo, because (as is the problem in your case) you can very easily make mistakes on quotation marks.
This would fix your problem:
echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";
but you should really do this
<?php
$param = "test";
?>
<a href="http://www.whatever.com/<?php echo $param; ?>">Click Here</a>
Your best bet is to right click > inspect the element.
I am using Bootstrap 4 and none of the suggestions worked until I did this.
Once I found where the relevant code was in the inspect window, I copied and pasted the relevant code that was causing the :focus to be outlined blue and changed it accordingly.
This is the code that worked in my css
.btn.focus, .btn:focus
{
outline: 0;
box-shadow: 0 0 0 0;
}
Converting is simple:
std::string myString;
LPCSTR lpMyString = myString.c_str();
One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.
As often, numbers says more than feeling, here are some data: Pipe vs Unix Socket Performance (opendmx.net).
This benchmark shows a difference of about 12 to 15% faster speed for pipes.
you must use import android.support.v7.app.ActionBarDrawerToggle;
and use the constructor
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.
You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html
select count(*)
from user_tab_columns
where table_name='MYTABLE' --use upper case
Instead of uppercase you can use lower function. Ex: select count(*) from user_tab_columns where lower(table_name)='table_name';
I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.
It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.
Pick the values in a servlet ie.
String username = request.getParameter("username");
String password = request.getParameter("password");
Then Store the Values inside the Session:
HttpSession sess = request.getSession();
sess.setAttribute("username", username);
sess.setAttribute("password", password);
These values Will be available anywhere in the Application as long as the session is valid.
HttpSession sess = request.getSession(false); //use false to use the existing session
sess.getAttribute("username");//this will return username anytime in the session
sess.getAttribute("password");//this will return password Any time in the session
I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl
in the JSPs:
${username}//this will give you the username in the JSP
${password}// this will give you the password in the JSP
A few steps you have to follow:
Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.
I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called rows
that will give you the number of rows.
So, if you have a named data range called Data
that has 7 rows, then =ROWS(Data)
will show 7 in that cell.
powershell ".\MyScript.ps1" > test.log
To read the html file from server using http
module. This is one way to read file from server. If you want to get it on console just remove http
module declaration.
var http = require('http');_x000D_
var fs = require('fs');_x000D_
var server = http.createServer(function(req, res) {_x000D_
fs.readFile('HTMLPage1.html', function(err, data) {_x000D_
if (!err) {_x000D_
res.writeHead(200, {_x000D_
'Content-Type': 'text/html'_x000D_
});_x000D_
res.write(data);_x000D_
res.end();_x000D_
} else {_x000D_
console.log('error');_x000D_
}_x000D_
});_x000D_
});_x000D_
server.listen(8000, function(req, res) {_x000D_
console.log('server listening to localhost 8000');_x000D_
});
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<h1>My Header</h1>_x000D_
<p>My paragraph.</p>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I think you are trying to configure your service in a similar way to the following config. There is more information here: Specify a Service with Two Endpoints Using Different Binding Values. Also, other than for development, it's probably not a good idea to have both HTTP & HTTPS endpoints to the same service. It kinda defeats the purpose of HTTPS. Hope this helps!
<service type="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null">
<endpoint
address="http://computer:8080/Hello"
contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
binding="basicHttpBinding"
bindingConfiguration="shortTimeout"
</endpoint>
<endpoint
address="http://computer:8080/Hello"
contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
binding="basicHttpBinding"
bindingConfiguration="Secure"
</endpoint>
</service>
<bindings>
<basicHttpBinding
name="shortTimeout"
timeout="00:00:00:01"
/>
<basicHttpBinding
name="Secure">
<Security mode="Transport" />
</basicHttpBinding>
</bindings>
For windows
;extension=php_mcrypt.dll to extension=php_mcrypt.dll
then restart your apache server
For Redhat
sudo yum install php55-mcrypt //if php5.5
sudo yum install php-mcrypt //if less than 5.4
sudo service httpd restart //if apache 2.4
sudo /etc/init.d/httpd restart //if apache 2.2 or less
For Ubuntu
sudo apt-get install php5-mcrypt
sudo service apache2 restart //if server not reloaded automatically
Still not working?
sudo php5enmod mcrypt && sudo service apache2 restart
It's because there is no long
in javascript.
In my case, Server had lower version framework than your application. installed latest version framework and it fixed this issue.
If you're looking for an HTML only way of doing this in angular...
<div #myDiv class="my_class" (click)="myDiv.classList.toggle('active')">
Some content
</div>
The important bit is the #myDiv
part.
It's a HTML Node reference, so you can use that variable as if it was assigned to document.querySelector('.my_class')
NOTE: this variable is scope specific, so you can use it in *ngFor
statements
Have a look at this one: http://aquantum-demo.appspot.com/file-upload
It also handles multiple file upload!
In Android Studio, open the Device Manager: Tools -> Android -> Android Device Monitor
In Eclipse open the Device Manager:
In the device manager you can add files to the SD Card here:
Rather than browse the ouput of the :ls command and delete (unload, wipe..) a buffer by specifying its number, I find that using file names is often more effective.
For instance, after I opened a couple of .txt file to refresh my memories of some fine point.. copy and paste a few lines of text to use as a template of sorts.. etc. I would type the following:
:bd txt <Tab>
Note that the matching string does not have to be at the start of the file name.
The above displays the list of file names that match 'txt' at the bottom of the screen and keeps the :bd command I initially typed untouched, ready to be completed.
Here's an example:
doc1.txt doc2.txt
:bd txt
I could backspace over the 'txt' bit and type in the file name I wish to delete, but where this becomes really convenient is that I don't have to: if I hit the Tab key a second time, Vim automatically completes my command with the first match:
:bd doc1.txt
If I want to get rid of this particular buffer I just need to hit Enter.
And if the buffer I want to delete happens to be the second (third.. etc.) match, I only need to keep hitting the Tab key to make my :bd command cycle through the list of matches.
Naturally, this method can also be used to switch to a given buffer via such commands as :b.. :sb.. etc.
This approach is particularly useful when the 'hidden' Vim option is set, because the buffer list can quickly become quite large, covering several screens, and making it difficult to spot the particular buffer I am looking for.
To make the most of this feature, it's probably best to read the following Vim help file and tweak the behavior of Tab command-line completion accordingly so that it best suits your workflow:
:help wildmode
The behavior I described above results from the following setting, which I chose for consistency's sake in order to emulate bash completion:
:set wildmode=list:longest,full
As opposed to using buffer numbers, the merit of this approach is that I usually remember at least part of a given file name letting me target the buffer directly rather than having to first look up its number via the :ls command.
Just Javascript (as requested)
Add this function somewhere on your page (preferably in the <head>
)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
This was an eye-opener for me, what Christopher Kramer wrote in 2014 on https://www.php.net/manual/en/session.configuration.php#115842
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime). [...]
When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path)
directly or the copy-pasted code:
def s3_read(source, profile_name=None):
"""
Read a file from an S3 source.
Parameters
----------
source : str
Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
profile_name : str, optional
AWS profile
Returns
-------
content : bytes
botocore.exceptions.NoCredentialsError
Botocore is not able to find your credentials. Either specify
profile_name or add the environment variables AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
See https://boto3.readthedocs.io/en/latest/guide/configuration.html
"""
session = boto3.Session(profile_name=profile_name)
s3 = session.client('s3')
bucket_name, key = mpu.aws._s3_path_split(source)
s3_object = s3.get_object(Bucket=bucket_name, Key=key)
body = s3_object['Body']
return body.read()
Aggregate is basically used to Group or Sum up data.
According to MSDN "Aggregate Function Applies an accumulator function over a sequence."
Example 1: Add all the numbers in a array.
int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate((total, nextValue) => total + nextValue);
*important: The initial aggregate value by default is the 1 element in the sequence of collection. i.e: the total variable initial value will be 1 by default.
variable explanation
total: it will hold the sum up value(aggregated value) returned by the func.
nextValue: it is the next value in the array sequence. This value is than added to the aggregated value i.e total.
Example 2: Add all items in an array. Also set the initial accumulator value to start adding with from 10.
int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate(10, (total, nextValue) => total + nextValue);
arguments explanation:
the first argument is the initial(starting value i.e seed value) which will be used to start addition with the next value in the array.
the second argument is a func which is a func that takes 2 int.
1.total: this will hold same as before the sum up value(aggregated value) returned by the func after the calculation.
2.nextValue: : it is the next value in the array sequence. This value is than added to the aggregated value i.e total.
Also debugging this code will give you a better understanding of how aggregate work.
Both memcpy and memove do similar things.
But to sight out one difference:
#include <memory.h>
#include <string.h>
#include <stdio.h>
char str1[7] = "abcdef";
int main()
{
printf( "The string: %s\n", str1 );
memcpy( (str1+6), str1, 10 );
printf( "New string: %s\n", str1 );
strcpy_s( str1, sizeof(str1), "aabbcc" ); // reset string
printf("\nstr1: %s\n", str1);
printf( "The string: %s\n", str1 );
memmove( (str1+6), str1, 10 );
printf( "New string: %s\n", str1 );
}
gives:
The string: abcdef
New string: abcdefabcdefabcd
The string: abcdef
New string: abcdefabcdef
Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.
They can be removed using pod spec remove SPEC_NAME
then pod setup
It may help to do pod spec remove master
then pod setup
Go to "Microsoft Visual C++ Compiler for Python 2.7" and continue based on "System Requirements" (this is what I did to put below steps together).
Install setuptools (setuptools 6.0 or later is required for Python to automatically detect this compiler package)
either by: pip install setuptools
or download "Setuptools bootstrapping installer" source from, save this file somwhere on your filestystem as "ez_python.py" and install with: python ez_python.py
Install wheel (wheel is recommended for producing pre-built binary packages). You can install it with: pip install wheel
Open Windows elevated Command Prompt cmd.exe (with "Run as administrator") to install "Microsoft Visual C++ Compiler for Python 2.7" for all users. You can use following command to do so: msiexec /i C:\users\jozko\download\VCForPython27.msi ALLUSERS=1
just use your own path to file: msiexec /i <path to MSI> ALLUSERS=1
Now you should be able to install pycrypto with: pip install pycrypto
Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision
From the docs:
Modals have two optional sizes, available via modifier classes to be placed on a .modal-dialog
: modal-lg
and modal-sm
(as of 3.1).
Also the modal dialogue will scale itself on small screens (as of 3.1.1).
There are at least three places where you may find shared_ptr
:
If your C++ implementation supports C++11 (or at least the C++11 shared_ptr
), then std::shared_ptr
will be defined in <memory>
.
If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr
will likely be in <memory>
(Microsoft Visual C++) or <tr1/memory>
(g++'s libstdc++). Boost also provides a TR1 implementation that you can use.
Otherwise, you can obtain the Boost libraries and use boost::shared_ptr
, which can be found in <boost/shared_ptr.hpp>
.
Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.
I was able to solve this by upgrading Python 3 via brew
brew upgrade python@3
Use itertools.combinations(mylist, 2)
mylist = range(5)
for x,y in itertools.combinations(mylist, 2):
print x,y
0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4
If you just want to set the same color to every separator and it is opaque you can use:
self.tableView.separatorColor = UIColor.redColor()
If you want to use different colors for the separators or clear the separator color or use a color with alpha.
BE CAREFUL: You have to know that there is a backgroundView in the separator that has a default color.
To change it you can use this functions:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if(view.isKindOfClass(UITableViewHeaderFooterView)){
var headerView = view as! UITableViewHeaderFooterView;
headerView.backgroundView?.backgroundColor = myColor
//Other colors you can change here
// headerView.backgroundColor = myColor
// headerView.contentView.backgroundColor = myColor
}
}
func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
if(view.isKindOfClass(UITableViewHeaderFooterView)){
var footerView = view as! UITableViewHeaderFooterView;
footerView.backgroundView?.backgroundColor = myColor
//Other colors you can change here
//footerView.backgroundColor = myColor
//footerView.contentView.backgroundColor = myColor
}
}
Hope it helps!
If you're using PHPMyAdmin you have to be logged in as root to be able to change root password. in user put root than leave password blank than change your password.
In perl
perl -ane '{ if(m/[[:^ascii:]]/) { print } }' fileName > newFile
Since the fields are empty they are not valid, so the ng-invalid
and ng-invalid-required
classes are added properly.
You can use the class ng-pristine
to check out whether the fields have already been used or not.
Use this,
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[ '"]/gi;
}else if(elem == "search" || elem == "comment"){
rx = /[^a-z 0-9.,?]/gi;
}else{
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx , "" );
}
On the backend, for java , Try using StringUtils class or a custom script.
public static String HTMLEncode(String aTagFragment) {
final StringBuffer result = new StringBuffer();
final StringCharacterIterator iterator = new
StringCharacterIterator(aTagFragment);
char character = iterator.current();
while (character != StringCharacterIterator.DONE )
{
if (character == '<')
result.append("<");
else if (character == '>')
result.append(">");
else if (character == '\"')
result.append(""");
else if (character == '\'')
result.append("'");
else if (character == '\\')
result.append("\");
else if (character == '&')
result.append("&");
else {
//the char is not a special one
//add it to the result as is
result.append(character);
}
character = iterator.next();
}
return result.toString();
}
I think the only cookie you need is JSESSIONID=xxx..
Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.
Somewhere, you need to tell Apache that people are allowed to see contents of this directory.
<Directory "F:/bar/public">
Order Allow,Deny
Allow from All
# Any other directory-specific stuff
</Directory>
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
Well, the most likely difference is that you still have to do an actual lookup of localhost
somewhere.
If you use 127.0.0.1
, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of gethostbyname
will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.
Otherwise, the name has to be resolved. And there's no guarantee that your hosts
file will actually be used for that resolution (first, or at all) so localhost
may become a totally different IP address.
By that I mean that, on some systems, a local hosts
file can be bypassed. The host.conf
file controls this on Linux (and many other Unices).
I think if I understand correctly this is what you are doing.
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
switch(getDrawableId(imageView)) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
break;
}
});
Right? So that function getDrawableId()
doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
// See here
Integer integer = (Integer) imageView.getTag();
integer = integer == null ? 0 : integer;
switch(integer) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
imageView.setTag(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
imageView.setTag(R.drawable.foo);
break;
}
});
by VB function:
Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue
If Not m_RowNr(1) = strQName Then
m_RowNr(0) = 1
m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
m_RowNr(0) = m_RowNr(0) + 1
End If
m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)
End Function
Usage(without sorting option):
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id
if sorting required or multiple tables join then create intermediate table:
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
INTO table_with_Nr
From table A
Order By A.id
You're setting the Content-Type
to be multipart/form-data
, but then using JSON.stringify
on the body data, which returns application/json
. You have a content type mismatch.
You will need to encode your data as multipart/form-data
instead of json
. Usually multipart/form-data
is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded
(which is the default for HTML forms).
The specification for multipart/form-data
can be found in RFC 1867.
For a guide on how to submit that kind of data via javascript, see here.
The basic idea is to use the FormData object (not supported in IE < 10):
async function sendData(url, data) {
const formData = new FormData();
for(const name in data) {
formData.append(name, data[name]);
}
const response = await fetch(url, {
method: 'POST',
body: formData
});
// ...
}
Per this article make sure not to set the Content-Type
header. The browser will set it for you, including the boundary
parameter.
The reason for the using
statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource();
myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes
will be disposed.
DateTime.Date
cannot be converted to SQL. Use EntityFunctions.TruncateTime method to get date part.
var eventsCustom = eventCustomRepository
.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);
UPDATE: As @shankbond mentioned in comments, in Entity Framework 6 EntityFunctions
is obsolete, and you should use DbFunctions
class, which is shipped with Entity Framework.
The easiest way to do it using only Angular 2/4 template with no coding:
<nav class="navbar navbar-default" aria-expanded="false">
<div class="container-wrapper">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse no-transition" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
<ul class="nav navbar-nav" (click)="isCollapsed = !isCollapsed">
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}"><a routerLink="/">Home</a></li>
<li [routerLinkActive]="['active']"><a routerLink="/about">About</a></li>
<li [routerLinkActive]="['active']"><a routerLink="/portfolio">Portfolio</a></li>
<li [routerLinkActive]="['active']"><a routerLink="/contacts">Contacts</a></li>
</ul>
</div>
</div>
</nav>
To Import Data through URL in pandas just apply the simple below code it works actually better.
import pandas as pd
train = pd.read_table("https://urlandfile.com/dataset.csv")
train.head()
If you are having issues with a raw data then just put 'r' before URL
import pandas as pd
train = pd.read_table(r"https://urlandfile.com/dataset.csv")
train.head()
I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.
Here is how:
class TestedClass extends AARRGGHH {
public LoginContext login(String user, String password) {
LoginContext lc = new LoginContext("login", callbackHandler);
lc.doThis();
lc.doThat();
return lc;
}
}
Now, PowerMockRunner
failed to initialize TestedClass
because it extends AARRGGHH
, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.
I found a nice hack with minimal refactoring of TestedClass
: I created a small method
LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
new lc = new LoginContext(login, callbackHandler);
}
The scope of this method is necessarily package
.
Then your test stub will look like:
LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
.when(testClass)
.initLoginContext("login", callbackHandler)
and the trick is done...
You start by writing a class that derives from Attribute:
public class MyCustomAttribute: Attribute
{
public string SomeProperty { get; set; }
}
Then you could decorate anything (class, method, property, ...) with this attribute:
[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{
}
and finally you would use reflection to fetch it:
var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
var myAttribute = customAttributes[0];
string value = myAttribute.SomeProperty;
// TODO: Do something with the value
}
You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:
/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute
Important things to know about attributes:
Found the best way to do it for a server which does not support pkill
kill -9 $(ps ax | grep My_pattern| fgrep -v grep | awk '{ print $1 }')
You do not have to loop.
To export all documents from ElasticSearch into JSON, you can use the esbackupexporter tool. It works with index snapshots. It takes the container with snapshots (S3, Azure blob or file directory) as the input and outputs one or several zipped JSON files per index per day. It is quite handy when exporting your historical snapshots. To export your hot index data, you may need to make the snapshot first (see the answers above).
function isset(key){
ret = false;
array_example.forEach(function(entry) {
if( entry == key ){
ret = true;
}
});
return ret;
}
alert( isset("key_search") );
ngAfterViewInit()
of AppComponent
is a lifecycle callback Angular calls after the root component and it's children have been rendered and it should fit for your purpose.
even shorter:
echo $select->__toString()."\n";
and more shorter:
echo $select .""; die;
How I can get rid of it so it doesnt display it?
People here are trying to tell you that it's unprofessional (and it is), but in your case you should simply add following to the start of your application:
error_reporting(E_ERROR|E_WARNING);
This will disable E_NOTICE reporting. E_NOTICES are not errors, but notices, as the name says. You'd better check this stuff out and proof that undefined variables don't lead to errors. But the common case is that they are just informal, and perfectly normal for handling form input with PHP.
Also, next time Google the error message first.
If not using C++14, then I find below the simplest solution.
#define METHOD(NAME, ...) auto NAME __VA_ARGS__ -> decltype(m_T.r##NAME) { return m_T.r##NAME; }
template<typename T>
struct Reverse
{
T& m_T;
METHOD(begin());
METHOD(end());
METHOD(begin(), const);
METHOD(end(), const);
};
#undef METHOD
template<typename T>
Reverse<T> MakeReverse (T& t) { return Reverse<T>{t}; }
Demo.
It doesn't work for the containers/data-types (like array), which doesn't have begin/rbegin, end/rend
functions.
After trying most of the solutions here, the easiest thing I found was the obvious - using a temp file. I'm not sure what you want to do with your multiple line output, but you can then deal with it line by line using read. About the only thing you can't really do is easily stick it all in the same variable, but for most practical purposes this is way easier to deal with.
./myscript.sh > /tmp/foo
while read line ; do
echo 'whatever you want to do with $line'
done < /tmp/foo
Quick hack to make it do the requested action:
result=""
./myscript.sh > /tmp/foo
while read line ; do
result="$result$line\n"
done < /tmp/foo
echo -e $result
Note this adds an extra line. If you work on it you can code around it, I'm just too lazy.
EDIT: While this case works perfectly well, people reading this should be aware that you can easily squash your stdin inside the while loop, thus giving you a script that will run one line, clear stdin, and exit. Like ssh will do that I think? I just saw it recently, other code examples here: https://unix.stackexchange.com/questions/24260/reading-lines-from-a-file-with-bash-for-vs-while
One more time! This time with a different filehandle (stdin, stdout, stderr are 0-2, so we can use &3 or higher in bash).
result=""
./test>/tmp/foo
while read line <&3; do
result="$result$line\n"
done 3</tmp/foo
echo -e $result
you can also use mktemp, but this is just a quick code example. Usage for mktemp looks like:
filenamevar=`mktemp /tmp/tempXXXXXX`
./test > $filenamevar
Then use $filenamevar like you would the actual name of a file. Probably doesn't need to be explained here but someone complained in the comments.
When multiple threads need to check and change the boolean. For example:
if (!initialized) {
initialize();
initialized = true;
}
This is not thread-safe. You can fix it by using AtomicBoolean
:
if (atomicInitialized.compareAndSet(false, true)) {
initialize();
}
use double quotation marks around the values.
insert into Person (First, Last) Values("Joe","O'Brien")
When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.
If you have Java 1.8 then
You need this xml part in pom.xml and update project.
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Doesn't log4j just use the application root directory if you don't specify a root directory in your FileAppender's path property? So you should just be able to use:
log4j.appender.file.File=logs/MyLog.log
It's been awhile since I've done Java web development, but this seems to be the most intuitive, and also doesn't collide with other unfortunately named logs writing to the ${catalina.home}/logs directory.
You must update the Windows PowerShell to minimum of version 4.0 for the script below to work.
[array]$SiteLinks = "http://mypage.global/Chemical/test.html"
"http://maypage2:9080/portal/site/hotpot/test.json"
foreach($url in $SiteLinks) {
try {
Write-host "Verifying $url" -ForegroundColor Yellow
$checkConnection = Invoke-WebRequest -Uri $url
if ($checkConnection.StatusCode -eq 200) {
Write-Host "Connection Verified!" -ForegroundColor Green
}
}
catch [System.Net.WebException] {
$exceptionMessage = $Error[0].Exception
if ($exceptionMessage -match "503") {
Write-Host "Server Unavaiable" -ForegroundColor Red
}
elseif ($exceptionMessage -match "404") {
Write-Host "Page Not found" -ForegroundColor Red
}
}
}
Here is another way to do it, if you have dynamic data to be included.
#!/bin/bash
version=$1
text=$2
branch=$(git rev-parse --abbrev-ref HEAD)
repo_full_name=$(git config --get remote.origin.url | sed 's/.*:\/\/github.com\///;s/.git$//')
token=$(git config --global github.token)
generate_post_data()
{
cat <<EOF
{
"tag_name": "$version",
"target_commitish": "$branch",
"name": "$version",
"body": "$text",
"draft": false,
"prerelease": false
}
EOF
}
echo "Create release $version for repo: $repo_full_name branch: $branch"
curl --data "$(generate_post_data)" "https://api.github.com/repos/$repo_full_name/releases?access_token=$token"
If you are working using Knockout, use the key functionality of observable functionality knockout.
Use ko.computed()
method and do and trigger ajax call within that function.
One of the fastest solutions:
public static long getBinary(int n)
{
long res=0;
int t=0;
while(n>1)
{
t= (int) (Math.log(n)/Math.log(2));
res = res+(long)(Math.pow(10, t));
n-=Math.pow(2, t);
}
return res;
}
Read line by line, not the whole file:
for line in open(file_name, 'rb'):
# process line here
Even better use with
for automatically closing the file:
with open(file_name, 'rb') as f:
for line in f:
# process line here
The above will read the file object using an iterator, one line at a time.
Thought I'd update this with a dplyr
solution
library(dplyr)
filter(studentdata, Drink == "water")
I would like to suggest additional solution to fix this issue. So, I recommend to reinstall/install the latest Windows SDK
. In my case it has helped me to fix the issue when using Qt
with MSVC
compiler to debug a program.
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.
You can also use number formatter JS available at
https://code.google.com/p/javascript-number-formatter/
http://jsfiddle.net/chauhangs/hUE3h/
format("##,###.", 98700)
format("#,###.", 8211)
try with this code
String ids[] = {"182","160","183"};
StringBuilder builder = new StringBuilder();
for( int i = 0 ; i < ids.length; i++ ) {
builder.append("?,");
}
String sql = "delete from emp where id in ("+builder.deleteCharAt( builder.length() -1 ).toString()+")";
PreparedStatement pstmt = connection.prepareStatement(sql);
for (int i = 1; i <= ids.length; i++) {
pstmt.setInt(i, Integer.parseInt(ids[i-1]));
}
int count = pstmt.executeUpdate();
According to HTTP terms, The PUT
request is just-like a database update statement.
PUT
- is used for modifying existing resource (Previously POSTED). On the other hand the PATCH
request is used to update some portion of existing resource.
For Example:
Customer Details:
// This is just a example.
firstName = "James";
lastName = "Anderson";
email = "[email protected]";
phoneNumber = "+92 1234567890";
//..
When we want to update to entire record ? we have to use Http
PUT
verb
for that.
such as:
// Customer Details Updated.
firstName = "James++++";
lastName = "Anderson++++";
email = "[email protected]";
phoneNumber = "+92 0987654321";
//..
On the other hand if we want to update only the portion of the record not the entire record then go for Http
PATCH
verb
.
such as:
// Only Customer firstName and lastName is Updated.
firstName = "Updated FirstName";
lastName = "Updated LastName";
//..
PUT VS POST:
When using PUT
request we have to send all parameter such as firstName, lastName, email, phoneNumber Where as In patch
request only send the parameters which one we want to update and it won't effecting or changing other data.
For more details please visit : https://fullstack-developer.academy/restful-api-design-post-vs-put-vs-patch/
you can also use vmware-mount from VMwares VDDK (Virtual Disk Development Kit): http://communities.vmware.com/community/vmtn/developer/forums/vddk
this allows you to mount VMDK files as disk drives in windows or linux
var parts = 'http://mywebsite/folder/file'.split('/');_x000D_
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash_x000D_
_x000D_
console.log(lastSegment);
_x000D_
A good rule of thumb: use the built-in help system in Python. Example below...
jdoe@server:~$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)
------------------------------------------
NAME
memcache - client module for memcached (memory cache daemon)
FILE
/usr/lib/python2.7/dist-packages/memcache.py
MODULE DOCS
http://docs.python.org/library/memcache
DESCRIPTION
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
...
------------------------------------------
I've had best and most consistent results across all browsers by setting Pragma: no-cache
echo array_search("car",array_keys($a));
I guess you could open a popup window and call that a dialog box. I'm unsure of the details, but I'm pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?
Originally we used no-cache many years ago and did run into some problems with stale content with certain browsers... Don't remember the specifics unfortunately.
We had since settled on JUST the use of no-store. Have never looked back or had a single issue with stale content by any browser or intermediaries since.
This space is certainly dominated by reality of implementations vs what happens to have been written in various RFCs. Many proxies in particular tend to think they do a better job of "improving performance" by replacing the policy they are supposed to be following with their own.
When calling the function, follow it by return false
example:
<input type="submit" value="Add" onclick="addNewPayment();return false;">
c.Request["AP"]
will read posted values. Also you need to use a submit button to post the form:
<input type="submit" value="Submit" />
instead of
<input type=button value="Submit" />
A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.
If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.
This is the right answer http://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring/15211030#15211030. and will work for most of the folks. But if your web.xml does is not aware of all applicationContext.xml files, quartz job will not be able to invoke those beans. I had to do an extra layer to inject additional applicationContext files
public class MYSpringBeanJobFactory extends SpringBeanJobFactory
implements ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
@Override
public void setApplicationContext(final ApplicationContext context) {
try {
PathMatchingResourcePatternResolver pmrl = new PathMatchingResourcePatternResolver(context.getClassLoader());
Resource[] resources = new Resource[0];
GenericApplicationContext createdContext = null ;
resources = pmrl.getResources(
"classpath*:my-abc-integration-applicationContext.xml"
);
for (Resource r : resources) {
createdContext = new GenericApplicationContext(context);
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(createdContext);
int i = reader.loadBeanDefinitions(r);
}
createdContext.refresh();//important else you will get exceptions.
beanFactory = createdContext.getAutowireCapableBeanFactory();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle)
throws Exception {
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job);
return job;
}
}
You can add any number of context files you want your quartz to be aware of.
globals()
, locals()
, vars()
, and dir()
may all help you in what you want.
As others have said you're subtracting from the numeric values returned from methods like date.getDate()
, you need to reset those values on your date variable. I've created a method below that will do this for you. It creates a date using new Date()
which will initialize with the current date, then sets the date, month, and year according to the values passed in. For example, if you want to go back 6 days then pass in -6 like so var newdate = createDate(-6,0,0)
. If you don't want to set a value pass in a zero (or you could set default values). The method will return the new date for you (tested in Chrome and Firefox).
function createDate(days, months, years) {
var date = new Date();
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
}
Have you configured the jupyter_notebook_config.py file to allow external connections?
By default, Jupyter Notebook only accepts connections from localhost (eg, from the same computer that its running on). By modifying the NotebookApp.allow_origin option from the default ' ' to '*', you allow Jupyter to be accessed externally.
c.NotebookApp.allow_origin = '*' #allow all origins
You'll also need to change the IPs that the notebook will listen on:
c.NotebookApp.ip = '0.0.0.0' # listen on all IPs
Also see the details in a subsequent answer in this thread.
You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
For Python 3, replace import Tkinter as tk
with import tkinter as tk
.
In your receiving intent you need to do:
Intent i = getIntent();
stock_list = i.getStringArrayListExtra("stock_list");
The way you have it you've just created a new empty intent without any extras.
If you only have a single extra you can condense this down to:
stock_list = getIntent().getStringArrayListExtra("stock_list");
If you have Iterable convert to stream and find last element
Iterator<String> sourceIterator = Arrays.asList("one", "two", "three").iterator();
Iterable<String> iterable = () -> sourceIterator;
String last = StreamSupport.stream(iterable.spliterator(), false).reduce((first, second) -> second).orElse(null);
The only way I've seen it done is if you do this:
for /f "delims=" %a in ('ver') do @set foobar=%a
ver
is the version command for Windows and on my system it produces:
Microsoft Windows [Version 6.0.6001]
MySQL has a short description of their more or less strict rules:
https://dev.mysql.com/doc/internals/en/coding-style.html
Most common codingstyle for MySQL by Simon Holywell:
See also this question: Are there any published coding style guidelines for SQL?
This version
controls backtracking
/(["'])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/
Can't you put the variables in a higher scope?
(function () {
var privateVariable = true;
var MyClass = function () {
if (privateVariable) console.log('readable from private scope!');
};
MyClass.prototype.publicMethod = function () {
if (privateVariable) console.log('readable from public scope!');
};
}))();
@Carlo I really like your implementation of this, but I wanted to share my version and how to use it in my ViewModel
First implement ICommand
public class Command : ICommand
{
public delegate void ICommandOnExecute();
public delegate bool ICommandOnCanExecute();
private ICommandOnExecute _execute;
private ICommandOnCanExecute _canExecute;
public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null)
{
_execute = onExecuteMethod;
_canExecute = onCanExecuteMethod;
}
#region ICommand Members
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute?.Invoke() ?? true;
}
public void Execute(object parameter)
{
_execute?.Invoke();
}
#endregion
}
Notice I have removed the parameter from ICommandOnExecute and ICommandOnCanExecute and added a null to the constructor
Then to use in the ViewModel
public Command CommandToRun_WithCheck
{
get
{
return new Command(() =>
{
// Code to run
}, () =>
{
// Code to check to see if we can run
// Return true or false
});
}
}
public Command CommandToRun_NoCheck
{
get
{
return new Command(() =>
{
// Code to run
});
}
}
I just find this way cleaner as I don't need to assign variables and then instantiate, it all done in one go.
This question is very similar to Item 29 in Effective Java - "Consider typesafe heterogeneous containers." Laz's answer is the closest to Bloch's solution. However, both put and get should use the Class literal for safety. The signatures would become:
public <T extends Animal> void addFriend(String name, Class<T> type, T animal);
public <T extends Animal> T callFriend(String name, Class<T> type);
Inside both methods you should check that the parameters are sane. See Effective Java and the Class javadoc for more info.
For some time now, you can also only rely on the data.table
package and its IDate
class plus associated functions. (Check ?as.IDate()
). So, no need to additionally install lubridate
.
require(data.table)
some_date <- c("01/02/1979", "03/04/1980")
month(as.IDate(some_date, '%d/%m/%Y')) # all data.table functions
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.
Default @INC
Perl interpreter is compiled with a specific @INC
default value. To find out this value, run env -i perl -V
command (env -i
ignores the PERL5LIB
environmental variable - see #2) and in the output you will see something like this:
$ env -i perl -V ... @INC: /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
Note .
at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T
(taint checks enabled).
To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs
:
Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3
Environmental variable PERL5LIB
(or PERLLIB
)
Perl pre-pends @INC
with a list of directories (colon-separated) contained in PERL5LIB
(if it is not defined, PERLLIB
is used) environment variable of your shell. To see the contents of @INC
after PERL5LIB
and PERLLIB
environment variables have taken effect, run perl -V
.
$ perl -V ... %ENV: PERL5LIB="/home/myuser/test" @INC: /home/myuser/test /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
-I
command-line option
Perl pre-pends @INC
with a list of directories (colon-separated) passed as value of the -I
command-line option. This can be done in three ways, as usual with Perl options:
Pass it on command line:
perl -I /my/moduledir your_script.pl
Pass it via the first line (shebang) of your Perl script:
#!/usr/local/bin/perl -w -I /my/moduledir
Pass it as part of PERL5OPT
(or PERLOPT
) environment variable (see chapter 19.02 in Programming Perl)
Pass it via the lib
pragma
Perl pre-pends @INC
with a list of directories passed in to it via use lib
.
In a program:
use lib ("/dir1", "/dir2");
On the command line:
perl -Mlib=/dir1,/dir2
You can also remove the directories from @INC
via no lib
.
You can directly manipulate @INC
as a regular Perl array.
Note: Since @INC
is used during the compilation phase, this must be done inside of a BEGIN {}
block, which precedes the use MyModule
statement.
Add directories to the beginning via unshift @INC, $dir
.
Add directories to the end via push @INC, $dir
.
Do anything else you can do with a Perl array.
Note: The directories are unshifted onto @INC
in the order listed in this answer, e.g. default @INC
is last in the list, preceded by PERL5LIB
, preceded by -I
, preceded by use lib
and direct @INC
manipulation, the latter two mixed in whichever order they are in Perl code.
@INC
?There does not seem to be a comprehensive @INC
FAQ-type post on Stack Overflow, so this question is intended as one.
If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC
compiled into the Perl binary.
If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC
in previous use case), set the users' PERL5LIB
, usually during user login.
Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su
.
If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB
manually, or pass the -I
option to perl.
If the modules need to be used only for specific scripts, by all users using them, use use lib
/no lib
pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).
If the directories in @INC
need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib
/no lib
pragmas, then use direct @INC
manipulation inside BEGIN {}
block or inside a special purpose library designated for @INC
manipulation, which must be used by your script(s) before any other modules are used.
An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.
An additional use case for directly manipulating @INC
is to be able to add subroutine references or object references (yes, Virginia, @INC
can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).
You can check out my answer to this similar question
Basically, I've included there a bash script named "runEvery.sh" which you can run with cron every 1 minute and pass as arguments the real command you wish to run and the frequency in seconds in which you want to run it.
something like this
* * * * * ~/bin/runEvery.sh 5 myScript.sh
Try this
IFS=', '; array=(Paris, France, Europe)
for item in ${array[@]}; do echo $item; done
It's simple. If you want, you can also add a declare (and also remove the commas):
IFS=' ';declare -a array=(Paris France Europe)
The IFS is added to undo the above but it works without it in a fresh bash instance
I think you can pass it BindingFlags.NonPublic
where it is the GetMethod
method.
Well, I am still stumped. So here is more code.
Before I leave my map, I call SaveLocation(myMapView,myMapController);
This is what ends up calling my geocoding information.
But since getFromLocation
can throw an IOException
, I had to do the following to call SaveLocation
try
{
SaveLocation(myMapView,myMapController);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Then I have to change SaveLocation by saying it throws IOExceptions :
public void SaveLocation(MapView mv, MapController mc) throws IOException{
//I do this :
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List myList = myLocation.getFromLocation(latPoint, lngPoint, 1);
//...
}
And it crashes every time.
You should try HttpAutoindexModule.
Set autoindex option to on
. It is off by default.
Your example configuration should be ok
location /{
root /home/yozloy/html/;
index index.html;
autoindex on;
}
Without autoindex option you should be getting Error 403 for requests that end with /
on directories that do not have an index.html
file. With this option you should be getting a simple listing:
<html>
<head><title>Index of /</title></head>
<body bgcolor="white">
<h1>Index of /test/</h1><hr><pre><a href="../">../</a>
<a href="test.txt">test.txt</a> 19-May-2012 10:43 0
</pre><hr></body>
</html>
Edit: Updated the listing to delete any references to test
I think I found solution - proper binary parser must be selected so Eclipse can recognize the executable:
Select the project, then right-click. Project->Properties->C/C++ Build->Settings->Binary Parsers, PE Windows Parser.
I.e. if Cygwin compiler is used then Cygwin parser should be used.
That worked for me at least for Cross-compiler (both on Windows 7 and Ubuntu 12.04). On Linux, I use Elf parser.
If anyone has the better solution, please advise.
In case you don't wish to set the toolbar as the action bar, you can use this:
val toggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
toggle.isDrawerSlideAnimationEnabled = false
toggle.isDrawerIndicatorEnabled = false
toggle.setHomeAsUpIndicator(AppCompatResources.getDrawable(this, ...))
drawer!!.addDrawerListener(toggle)
toggle.setToolbarNavigationClickListener {
setDrawerOpened(!isDrawerOpened())
}
toggle.syncState()
fun setDrawerOpened(open: Boolean) {
if (open == drawerLayout.isDrawerOpen(GravityCompat.START))
return
if (open)
drawerLayout.openDrawer(GravityCompat.START)
else drawerLayout.closeDrawer(GravityCompat.START)
}
The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.
If you are supposed to get a JSON Object you can just put:
JSONObject myObject = new JSONObject(result);
Here is a solution using the plyr
package.
The following line of code essentially tells ddply
to first group your data by Group, and then within each group returns a subset where the Score equals the maximum score in that group.
library(plyr)
ddply(data, .(Group), function(x)x[x$Score==max(x$Score), ])
Group Score Info
1 1 3 c
2 2 4 d
And, as @SachaEpskamp points out, this can be further simplified to:
ddply(df, .(Group), function(x)x[which.max(x$Score), ])
(which also has the advantage that which.max
will return multiple max lines, if there are any).
There are quite a few discussions around this topic
Although we see it often, using POSITION_NONE
does not seem to be the way to go as it is very inefficient memory-wise.
Here in this question, we should consider using Alvaro's approach:
... is to
setTag()
method ininstantiateItem()
when instantiating a new view. Then instead of usingnotifyDataSetChanged()
, you can usefindViewWithTag()
to find the view you want to update.
Here is a SO answer with code based on this idea
This is a simpler way using iloc to select which columns to sum:
df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)
Produces:
a b c d e f g h
0 1 2 dd 5 8 3 3 6
1 2 3 ee 9 14 5 5 11
2 3 4 ff 1 8 7 7 4
I can't find a way to combine a range and specific columns that works e.g. something like:
df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)
numpy.full((2,2), True, dtype=bool)
I converted @DougW's Utility
into C# (used in Xamarin). The following works fine for fixed-height items in the list, and is going to be mostly fine, or at least a good start, if only some of the items are a bit bigger than the standard item.
// You will need to put this Utility class into a code file including various
// libraries, I found that I needed at least System, Linq, Android.Views and
// Android.Widget.
using System;
using System.Linq;
using Android.Views;
using Android.Widget;
namespace UtilityNamespace // whatever you like, obviously!
{
public class Utility
{
public static void setListViewHeightBasedOnChildren (ListView listView)
{
if (listView.Adapter == null) {
// pre-condition
return;
}
int totalHeight = listView.PaddingTop + listView.PaddingBottom;
for (int i = 0; i < listView.Count; i++) {
View listItem = listView.Adapter.GetView (i, null, listView);
if (listItem.GetType () == typeof(ViewGroup)) {
listItem.LayoutParameters = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
}
listItem.Measure (0, 0);
totalHeight += listItem.MeasuredHeight;
}
listView.LayoutParameters.Height = totalHeight + (listView.DividerHeight * (listView.Count - 1));
}
}
}
Thanks @DougW, this got me out of a tight spot when I had to work with OtherPeople'sCode. :-)
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
psxls gave a great answer but I think my Notepad++ version is slightly different so the $ (dollar sign) capturing did not work.
I have Notepad++ v.5.9.3 and here's how you can accomplish your task:
Search for the pattern: value=\"([0-9]*)\" And replace with: \1 (whatever you want to do around that capturing group)
Ex. Surround with square brackets
[\1] --> will produce value="[4]"
Try below code:
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
return resources.getDimensionPixelSize(resourceId);
}
return 0;
var img = new Image(1,1); // width, height values are optional params
img.src = 'http://www.testtrackinglink.com';
Disclaimer : I've created fast-xml-parser
I have created fast-xml-parser to parse a XML string into JS/JSON object or intermediate traversal object. It is expected to be compatible in all the browsers (however tested on Chrome, Firefox, and IE only).
Usage
var options = { //default
attrPrefix : "@_",
attrNodeName: false,
textNodeName : "#text",
ignoreNonTextNodeAttr : true,
ignoreTextNodeAttr : true,
ignoreNameSpace : true,
ignoreRootElement : false,
textNodeConversion : true,
textAttrConversion : false,
arrayMode : false
};
if(parser.validate(xmlData)){//optional
var jsonObj = parser.parse(xmlData, options);
}
//Intermediate obj
var tObj = parser.getTraversalObj(xmlData,options);
:
var jsonObj = parser.convertToJson(tObj);
Note: It doesn't use DOM parser but parse the string using RE and convert it into JS/JSON object.
Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :
drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;
select * from results_dummy;
-- THE update of multiple rows with/by different values
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;
select * from results_dummy;
-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;
You are getting this message because getBean returns an Object reference and you are casting it to the correct type. Java 1.5 gives you a warning. That's the nature of using Java 1.5 or better with code that works like this. Spring has the typesafe version
someMap=getApplicationContext().getBean<HashMap<String, String>>("someMap");
on its todo list.
Script for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below
Your HttpServletRequest
object has a getParameter(String paramName)
method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)
You should be using pip
to install packages, since it gives you uninstall capabilities.
Also, look into virtualenv
. It works well with pip
and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.
Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).
The 'trick' here is to use the node priority to as the vote count...
The data is:
vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote
,"vote": {
".read" : true
,".write" : true
,"$issue" : {
"user" : {
"$user" : {
".validate" : "!data.exists() &&
newData.val()==data.parent().parent().child('count').getPriority()+1 &&
newData.val()==newData.GetPriority()"
user can only vote once && count must be one higher than current count && data value must be same as priority.
}
}
,"count" : {
".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
newData.getPriority()==data.getPriority()+1 "
}
count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.
}
}
Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.
<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
window.fb = new Firebase('https:...vote/iss1/');
window.fb.child('count').once('value', function (dss) {
votes = dss.getPriority();
for (var i=1;i<10;i++) vote(dss,i+votes);
} );
function vote(dss,count)
{
var user='user/zz' + count; // replace with auth.id or whatever
window.fb.child(user).setWithPriority(count,count);
window.fb.child('count').setWithPriority(user,count);
}
</script>
The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)
The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).
select age(timestamp_A, timestamp_B)
Answering to Igor's comment:
select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
age
-------------------------------
1 year 1 mon 28 days 00:01:28
It is from an external js file and it is the only file linked to the page.
OK.
When I double click this file I get the following error
Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:
Windows Script Host Error: 'window' is not defined Code: 800A1391
... not an error you'll see in a browser. And of course, the browser is what supplies the window
object.
ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload
definition is simply being hit after the browser fires the window.onload
event.
Each column has like()
method, which can be used in query.filter()
. Given a search string, add a %
character on either side to search as a substring in both directions.
tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()
Another way to find all View:
SELECT DISTINCT table_name FROM information_schema.TABLES WHERE table_type = 'VIEW'
You have to use CSS.
In my opinion when you have a table often it is good with a separate line each side of the line.
Try this code:
HTML:
<table>
<tr class="row"><td>row 1</td></tr>
<tr class="row"><td>row 2</td></tr>
</table>
CSS:
.row {
border:1px solid black;
}
Bye
Andrea
That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123
to an int.
UPDATE
Based on your comments I would remove any spaces that are in the values you are trying to convert.
readLine()
returns pointer to local variable, which causes undefined behaviour.
To get around you can:
readLine()
line
using malloc()
- in this case line
will be persistentYou should try doing it with css3 animation. Check the code bellow:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
position: relative;
-webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
-webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
animation: myfirst 5s infinite;
animation-direction: alternate;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
0% {background: red; left: 0px; top: 0px;}
25% {background: yellow; left: 200px; top: 0px;}
50% {background: blue; left: 200px; top: 200px;}
75% {background: green; left: 0px; top: 200px;}
100% {background: red; left: 0px; top: 0px;}
}
@keyframes myfirst {
0% {background: red; left: 0px; top: 0px;}
25% {background: yellow; left: 200px; top: 0px;}
50% {background: blue; left: 200px; top: 200px;}
75% {background: green; left: 0px; top: 200px;}
100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>
<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>
</body>
</html>
Where 'div' is your animated object.
I hope you find this useful.
Thanks.
If you want to group the results based on a column and take the count based on the same, you can run the query as,
$sql = "SELECT COLUMNNAME,
COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'New',
COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'ACCPTED',
from TABLENAME
GROUP BY COLUMNANME";
The issue is with the Version of JSCH jar you are using.
Update it to latest jar.
I was also getting the same error and this solution worked.
You can download latest jar from
sys.stdin.read(1)
will basically read 1 byte from STDIN.
If you must use the method which does not wait for the \n
you can use this code as suggested in previous answer:
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
(taken from http://code.activestate.com/recipes/134892/)
You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.
UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.
constructor(props){
super(props);
}
getInitialState(){
return {"showHideSidenav":"hidden"};
}
render() {
return (
<div className="header">
<i className="border hide-on-small-and-down"></i>
<div className="container">
<a ref="btn" onClick={this.toggleSidenav.bind(this)} href="#" className="btn-menu show-on-small"><i></i></a>
<Menu className="menu hide-on-small-and-down"/>
<Sidenav className={this.props.showHideSidenav}/>
</div>
</div>
)
}
toggleSidenav() {
var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";
this.setState({"showHideSidenav":css});
}
Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.
.hidden {
display:none;
}
.show{
display:block;
}
I was having same issue. After some digging I realized that many post/pre-install scripts would try to install various dependencies and some times specific repositories are used. A better way is to disable certificate check for https module for nodejs that worked for me.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
I had a similar issue to this and clearing Temporary ASP.NET Files fixed it. Hope this helps someone.
I would suggest a more "abstract" classification. Add a new class "img-center" which can be used in combination with .img-responsive class:
// Center responsive images
.img-responsive.img-center {
margin: 0 auto;
}
I use this:
logging.conf:
[loggers]
keys=root,applog
[handlers]
keys=rotateFileHandler,rotateConsoleHandler
[formatters]
keys=applog_format,console_format
[formatter_applog_format]
format=%(asctime)s-[%(levelname)-8s]:%(message)s
[formatter_console_format]
format=%(asctime)s-%(filename)s%(lineno)d[%(levelname)s]:%(message)s
[logger_root]
level=DEBUG
handlers=rotateFileHandler,rotateConsoleHandler
[logger_applog]
level=DEBUG
handlers=rotateFileHandler
qualname=simple_example
[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=applog_format
args=('applog.log', 'a', 10000, 9)
[handler_rotateConsoleHandler]
class=StreamHandler
level=DEBUG
formatter=console_format
args=(sys.stdout,)
testapp.py:
import logging
import logging.config
def main():
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('applog')
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
#logging.shutdown()
if __name__ == '__main__':
main()
The following one-liner fast-forwards all branches that have an upstream branch if possible, and prints an error otherwise:
git branch \
--format "%(if)%(upstream:short)%(then)git push . %(upstream:short):%(refname:short)%(end)" |
sh
It uses a custom format with the git branch
command. For each branch that has an upstream branch, it prints a line with the following pattern:
git push . <remote-ref>:<branch>
This can be piped directly into sh
(assuming that the branch names are well-formed). Omit the | sh
to see what it's doing.
The one-liner will not contact your remotes. Issue a git fetch
or git fetch --all
before running it.
The currently checked-out branch will not be updated with a message like
! [remote rejected] origin/master -> master (branch is currently checked out)
For this, you can resort to regular git pull --ff-only
.
Add the following to your .gitconfig
so that git fft
performs this command:
[alias]
fft = !sh -c 'git branch --format \"%(if)%(upstream:short)%(then)git push . %(upstream:short):%(refname:short)%(end)\" | sh' -
See also my .gitconfig
. The alias is a shorthand to "fast-forward tracking (branches)".
This way you can insert arrays:
function array_insert(&$array, $value, $index)
{
return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $array);
}
Have you tried the GNU make documentation? It has a whole section about conditionals with examples.
If you want to show time on textview then better use Chronometer or TextClock
Using Chronometer:This was added in API 1. It has lot of option to customize it.
Your xml
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
Your activity
Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.
Your xml
<TextClock
android:id="@+id/textClock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:format12Hour="hh:mm:ss a"
android:gravity="center_horizontal"
android:textColor="#d41709"
android:textSize="44sp"
android:textStyle="bold" />
Thats it, you are done.
You can use any of these two widgets. This will make your life easy.
There are a couple ways you can do this. The simplest way to do so is to use the dockerfile ADD
command like so:
ADD . /path/inside/docker/container
However, any changes made to this directory on the host after building the dockerfile will not show up in the container. This is because when building a container, docker compresses the directory into a .tar
and uploads that context into the container permanently.
The second way to do this is the way you attempted, which is to mount a volume. Due to trying to be as portable as possible you cannot map a host directory to a docker container directory within a dockerfile, because the host directory can change depending on which machine you are running on. To map a host directory to a docker container directory you need to use the -v
flag when using docker run
, e.g.,:
# Run a container using the `alpine` image, mount the `/tmp`
# directory from your host into the `/container/directory`
# directory in your container, and run the `ls` command to
# show the contents of that directory.
docker run \
-v /tmp:/container/directory \
alpine \
ls /container/directory
If using Windows/MFC, and need the string for more than immediate output try:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);
You can set your hash directly to URL too.
window.location.hash = "YourHash";
The result : http://url#YourHash
Try this:
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
If you want to inform your frontend about a validation error, try to return json:
dataType: 'json',
success: function(data, textStatus, jqXHR) {
console.log(data.error);
}
Your asp script schould return:
{"error": true}
I use my ruleOut
function for filtering objects based on specific unwanted property values. I understand that in your example you would like to use conditions instead of values, but my answer is valid for the question title, so I'd like to leave my method here.
function ruleOut(arr, filterObj, applyAllFilters=true) {
return arr.filter( row => {
for (var field in filterObj) {
var val = row[field];
if (val) {
if (applyAllFilters && filterObj[field].indexOf(val) > -1) return false;
else if (!applyAllFilters) {
return filterObj[field].filter(function(filterValue){
return (val.indexOf(filterValue)>-1);
}).length == 0;
}
}
}
return true;
});
}
Say you have a list of actors like this:
let actors = [
{userName:"Mary", job:"star", language:"Turkish"},
{userName:"John", job:"actor", language:"Turkish"},
{userName:"Takis", job:"star", language:"Greek"},
{userName:"Joe", job:"star", language:"Turkish"},
{userName:"Bill", job:"star", language:"Turkish"}
];
and you would like to find all actors that are rated as Holywood stars, their nationality should not be one of 'English', 'Italian', 'Spanish', 'Greek', plus their name would not be one of 'Mary', 'Joe'. Bizzar example, I know! Anyway, with that set of conditions you would create the following object:
let unwantedFieldsFilter= {
userName: ['Mary', 'Joe'],
job: ['actor'],
language: ['English', 'Italian', 'Spanish', 'Greek']
};
OK, now if you ruleOut(actors, unwantedFieldsFilter)
you would only get
[{userName: "Bill", job: "star", language: "Turkish"}]
And Bill is your man, since his name is not one of 'Mary', 'Joe', his nationality is not included in ['English', 'Italian', 'Spanish', 'Greek'] plus he is a Star!
There is one option in my method, that is applyAllFilters
and is true by default.
If you would try to ruleOut with this param set as false, that would work as an 'OR' filtering instead of 'AND'.
Example: ruleOut(actors, {job:["actor"], language:["Italian"]}, false)
would get you everyone that is not an actor or Italian:
[{userName: "Mary", job: "star", language: "Turkish"},
{userName: "Takis", job: "star", language: "Greek"},
{userName: "Joe", job: "star", language: "Turkish"},
{userName: "Bill", job: "star", language: "Turkish"}]
NOTE: If your target server endpoint is using secure socket layer (SSL) certificate
Change your .config setting from basicHttpBinding
to basicHttpsBinding
I am sure, It will resolve your problem.
In addition, you can use the "&" sign to run many processes through one (1) ssh connections in order to to keep minimum number of terminals. For example, I have one process that listens for messages in order to extract files, the second process listens for messages in order to upload files: Using the "&" I can run both services in one terminal, through single ssh connection to my server.
*****I just realized that these processes running through the "&" will also "stay alive" after ssh session is closed! pretty neat and useful if your connection to the server is interrupted**
SqlBulkCopy class is best for SQL server,
Doing Bulk Upload/Insert of DataTable to a Table in SQL server in C#
In case if you want to remove all objects with "foo/" prefix using Java AWS SDK 2.0
import java.util.ArrayList;
import java.util.Iterator;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
//...
ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder()
.bucket(bucketName)
.prefix("foo/")
.build()
;
ListObjectsResponse objectsResponse = s3Client.listObjects(listObjectsRequest);
while (true) {
ArrayList<ObjectIdentifier> objects = new ArrayList<>();
for (Iterator<?> iterator = objectsResponse.contents().iterator(); iterator.hasNext(); ) {
S3Object s3Object = (S3Object)iterator.next();
objects.add(
ObjectIdentifier.builder()
.key(s3Object.key())
.build()
);
}
s3Client.deleteObjects(
DeleteObjectsRequest.builder()
.bucket(bucketName)
.delete(
Delete.builder()
.objects(objects)
.build()
)
.build()
);
if (objectsResponse.isTruncated()) {
objectsResponse = s3Client.listObjects(listObjectsRequest);
continue;
}
break;
};
You can also use events to trigger the Popdown.
Here's a fiddle based on satchmorun's solution. It dispenses with the PopdownAPI, and the top-level controller instead $broadcast
s 'success' and 'error' events down the scope chain:
$scope.success = function(msg) { $scope.$broadcast('success', msg); };
$scope.error = function(msg) { $scope.$broadcast('error', msg); };
The Popdown module then registers handler functions for these events, e.g:
$scope.$on('success', function(event, msg) {
$scope.status = 'success';
$scope.message = msg;
$scope.toggleDisplay();
});
This works, at least, and seems to me to be a nicely decoupled solution. I'll let others chime in if this is considered poor practice for some reason.
I guess these days you would do:
import subprocess
subprocess.run(["pwd"], cwd="sub-dir")
Is this value intended? if (scroll <= 500) { ...
This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"
<ListView
android:clipToPadding="false"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:dividerHeight="10dp"
android:divider="@null"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
and set paddingTop
, paddingBottom
and dividerHeight
to the same value to get equal spacing between all elements and space at the top and bottom of the list.
I set clipToPadding
to false
to let the views be drawn in this padded area.
I set divider
to @null
to remove the lines between list elements.
First add the new files:
svn add fileName
Then commit all new and modified files
svn ci <files_separated_by_space> -m "Commit message|ReviewID:XXXX"
If non source files are to be committed then
svn ci <files> -m "Commit msg|ReviewID:NON-SOURCE"
Just import the correct module,
"FormsModule"
import { FormsModule } from "@angular/forms";
@NgModule({
imports: [
BrowserModule,
FormsModule //<---.
],
....
})
To call the Bootstrap-datetimepikcer supported functions, you should use the syntax:
$('#datetimepicker').data("DateTimePicker").FUNCTION()
So you can try the function:
$('#datetimepicker').data("DateTimePicker").date();
Documentation: http://eonasdan.github.io/bootstrap-datetimepicker/Functions/
from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()
# if you want to return run itself to be used later
return theclass.run
Change the end of comm system to:
if __name__ == '__main__':
a_game = Comm_system()
a_game.run()
It's those lines being always run that are causing it to be run when imported as well as when executed.
For some 'Eclipse Marketplace' plugins Uninstall may not work. (Ex: SonarLint v5)
So Try,
Help -> About Eclipse -> Installation details
search the plugin name in 'Installed Software'
Select plugin name and Uninstall it
Additional Detail
To fix plugin errors, after the uninstall revert back older version of plugin,
Help -> install new software..
Get plugin url from Google search and Add it (Example: https://eclipse-uc.sonarlint.org)
Select and install older versions of the Plugin. This will fix most of the plugin problems.
>ssh user@serverip -p portnumber
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys
Found out how to make it work!
I just moved apache2 (the Web Sharing folder) to my desktop.
go to terminal and type "mv /etc/apache2/ /Users/hseungun/Desktop"
actually it says you need authority so
type this "sudo -s" then it'll go to bash-3.2
passwd root
set your password and then "mv /etc/apache2/ /Users/hseungun/Desktop"
try turning on the web sharing, and then start xampp on mac
You probably need to do a git stash
before you git pull
, this is because it is reading your old config file. So do:
git stash
git pull
git commit -am <"say first commit">
git push
Also see git-stash(1) Manual Page.
public void foo(Class c){
try {
Object ob = c.newInstance();
} catch (InstantiationException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
How to invoke method using reflection
import java.lang.reflect.*;
public class method2 {
public int add(int a, int b)
{
return a + b;
}
public static void main(String args[])
{
try {
Class cls = Class.forName("method2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod(
"add", partypes);
method2 methobj = new method2();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj
= meth.invoke(methobj, arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
}
catch (Throwable e) {
System.err.println(e);
}
}
}
Also See
Array is a JavaScript native object, why don't you just try to use the API of it? Knowing API on its own will save you time when you will switch to pure JavaScript or another framework.
There are number of different possibilities, so, use the one which mostly targets your needs.
Creating array with values:
var array = ["value1", "value2", "value3"];
Adding values to the end
var array = [];
array.push("value1");
array.push("value2");
array.push("value3");
Adding values to the begin:
var array = [];
array.unshift("value1");
array.unshift("value2");
array.unshift("value3");
Adding values at some index:
var array = [];
array[index] = "value1";
or by using splice
array.splice(index, 0, "value1", "value2", "value3");
Choose one you need.
setLoanItem()
isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.
Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.
You probably want to pass in a media object on which to call the method:
public void loanItem(Media m) {
m.setLoanItem("Yes");
}
If we're going to mention regular expressions, we might as well mention the switch
statement.
var expr = 'Papayas';_x000D_
switch (expr) {_x000D_
case 'Oranges':_x000D_
console.log('Oranges are $0.59 a pound.');_x000D_
break;_x000D_
case 'Mangoes':_x000D_
case 'Papayas': // Mangoes or papayas_x000D_
console.log('Mangoes and papayas are $2.79 a pound.');_x000D_
// expected output: "Mangoes and papayas are $2.79 a pound."_x000D_
break;_x000D_
default:_x000D_
console.log('Sorry, we are out of ' + expr + '.');_x000D_
}
_x000D_
When you already have all the "pieces" you wish to append, there is no point in using StringBuilder
at all. Using StringBuilder
and string concatenation in the same call as per your sample code is even worse.
This would be better:
return "select id1, " + " id2 " + " from " + " table";
In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:
return "select id1, id2 from table";
Using new StringBuilder().append("select id1, ").append(" id2 ")....toString()
will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.
If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.
I have an article on String
/ StringBuffer
which I wrote a while ago - before StringBuilder
came along. The principles apply to StringBuilder
in the same way though.
You don't use the :
syntax - pull
always modifies the currently checked-out branch. Thus:
git pull origin my_remote_branch
while you have my_local_branch
checked out will do what you want.
Since you already have the tracking branch set, you don't even need to specify - you could just do...
git pull
while you have my_local_branch
checked out, and it will update from the tracked branch.
I would like to post rather a Designer approach to this, this will keep design separate from your business logic:
Step 1. Create new style in (res->values->styles.xml) : Basically it is copy of your overall scheme with different parent - parent="Theme.AppCompat.Light.NoActionBar"
<!-- custom application theme. -->
<style name="MarkitTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimary</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
</style>
Step 2: In your AndroidManifest.xml, add this theme to the activity you want in: e.g. I want my main activity without action-bar so add this like below:
<activity android:name=".MainActivity"
android:theme="@style/MarkitTheme">
This is the best solution for me after trying a lot of things.
This trick here is using the esoteric table-layout:fixed
rule
This CSS ought to work against your sample HTML:
table {table-layout:fixed}
td {overflow:hidden; white-space:nowrap}
You also ought to specify explicit column widths for the <td>
s.
The table-layout:fixed
rule says "The cell widths of this table depend on what I say, not on the actual content in the cells". This is useful normally because the browser can begin displaying the table after it has received the first <tr>
. Otherwise, the browser has to receive the entire table before it can compute the column widths.
Try this before anything else - 'clear your cache'. I had the same issue. I was instructed to clear my cache. It worked.
Just change your syntax ever so slightly:
CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
ELSE '"DECLINED"'
END
If you don't put the field expression before the CASE
statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.
For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.
select * from user where userId in (1,2,3,etc)
Use the unicode escape sequence. First you'll have to find the codepoint for the character you seek to replace (let's just say it is ABCD in hex):
str = str.replaceAll("\uABCD", "");
For completeness, in Numpy there are four maximum related functions. They fall into two different categories:
np.amax/np.max
, np.nanmax
: for single array order statisticsnp.maximum
, np.fmax
: for element-wise comparison of two arraysNaNs propagator np.amax/np.max
and its NaN ignorant counterpart np.nanmax
.
np.max
is just an alias of np.amax
, so they are considered as one function.
>>> np.max.__name__
'amax'
>>> np.max is np.amax
True
np.max
propagates NaNs while np.nanmax
ignores NaNs.
>>> np.max([np.nan, 3.14, -1])
nan
>>> np.nanmax([np.nan, 3.14, -1])
3.14
NaNs propagator np.maximum
and its NaNs ignorant counterpart np.fmax
.
Both functions require two arrays as the first two positional args to compare with.
# x1 and x2 must be the same shape or can be broadcast
np.maximum(x1, x2, /, ...);
np.fmax(x1, x2, /, ...)
np.maximum
propagates NaNs while np.fmax
ignores NaNs.
>>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([ nan, nan, 2.72])
>>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([-inf, 3.14, 2.72])
The element-wise functions are np.ufunc
(Universal Function), which means they have some special properties that normal Numpy function don't have.
>>> type(np.maximum)
<class 'numpy.ufunc'>
>>> type(np.fmax)
<class 'numpy.ufunc'>
>>> #---------------#
>>> type(np.max)
<class 'function'>
>>> type(np.nanmax)
<class 'function'>
And finally, the same rules apply to the four minimum related functions:
np.amin/np.min
, np.nanmin
; np.minimum
, np.fmin
.