I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.
The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).
New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/
(eg /opt/firefox31/
). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.
Very Easy, Had this same problem then what i did was to download and install an app that would help in displaying then fixed the error.
Download this app xming:
http://sourceforge.net/project/downloading.php?
Install, then use settings on this link:
http://www.geo.mtu.edu/geoschem/docs/putty_install.html or follow this steps:
Installing/Configuring PuTTy and Xming
Once PuTTy and Xming have been downloaded to the PC, install according to their respective instructions.
Configuring Xming
Once Xming is installed, run the application called 'XLaunch' and verify that the settings are as shown:
Configuring PuTTy
After installing PuTTy, double-click on the PuTTy icon on the desktop and configure as shown:
This shows creating a login profile then saving it.
save profile then connect remotely to server to test.
Cheers!!!
You can use Core Graphics to draw the gradient, as pointed to in Mike's response. As a more detailed example, you could create a UIView
subclass to use as a background for your UILabel
. In that UIView
subclass, override the drawRect:
method and insert code similar to the following:
- (void)drawRect:(CGRect)rect
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35, // Start color
1.0, 1.0, 1.0, 0.06 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
}
This particular example creates a white, glossy-style gradient that is drawn from the top of the UIView
to its vertical center. You can set the UIView
's backgroundColor
to whatever you like and this gloss will be drawn on top of that color. You can also draw a radial gradient using the CGContextDrawRadialGradient
function.
You just need to size this UIView
appropriately and add your UILabel
as a subview of it to get the effect you desire.
EDIT (4/23/2009): Per St3fan's suggestion, I have replaced the view's frame with its bounds in the code. This corrects for the case when the view's origin is not (0,0).
When you do this,
while((inputLine = buff_read.readLine())!= null){
System.out.println(inputLine);
}
You consume everything in instream, so instream is empty. Now when try to do this,
Document doc = builder.parse(instream);
The parsing will fail, because you have passed it an empty stream.
To get the iframe to always load fresh content, add the current Unix timestamp to the end of the GET parameters. The browser then sees it as a 'different' request and will seek new content.
In Javascript, it might look like:
frames['my_iframe'].location.href='load_iframe_content.php?group_ID=' + group_ID + '×tamp=' + timestamp;
lowercase-with-hyphens
is the style I most often see on GitHub.*
lowercase_with_underscores
is probably the second most popular style I see.
The former is my preference because it saves keystrokes.
* Anecdotal; I haven't collected any data.
You have to follow these steps:
Open the php configuration file, which is located in the following directory
C: \ xampp \ php \ php.ini
Within that file search the extension section and uncomment the following lines
extension = php_pdo_pgsql.dll
extension = php_pgsql.dll
and restart your apache
process.terminate() doesn't work when using shell=True
. This answer will help you.
You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi
Using Perl
$ cat rayne.txt
A1 123 456
B1 234 567
C1 345 678
A1 098 766
B1 987 6545
C1 876 5434
$ perl -lane ' /A1/ and $x=$F[2] ; END { print "$x" } ' rayne.txt
766
$
If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:
[
{"key": value},
{"key": value},
...
This is still valid JSON.
Then, use the node.js readline module to process them one line at a time.
var fs = require("fs");
var lineReader = require('readline').createInterface({
input: fs.createReadStream("input.txt")
});
lineReader.on('line', function (line) {
line = line.trim();
if (line.charAt(line.length-1) === ',') {
line = line.substr(0, line.length-1);
}
if (line.charAt(0) === '{') {
processRecord(JSON.parse(line));
}
});
function processRecord(record) {
// Process the records one at a time here!
}
You can run gdb with --args parameter,
gdb --args executablename arg1 arg2 arg3
If you want it to run automatically, place some commands in a file (e.g. 'run') and give it as argument: -x /tmp/cmds. Optionally you can run with -batch mode.
gdb -batch -x /tmp/cmds --args executablename arg1 arg2 arg3
Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.
If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)
I think the solutions being provided have unnecessarily added stuff and does not use semaphores to its full potential. Here's what my solution is.
package com.test.threads;
import java.util.concurrent.Semaphore;
public class EvenOddThreadTest {
public static int MAX = 100;
public static Integer number = new Integer(0);
//Unlocked state
public Semaphore semaphore = new Semaphore(1);
class PrinterThread extends Thread {
int start = 0;
String name;
PrinterThread(String name ,int start) {
this.start = start;
this.name = name;
}
@Override
public void run() {
try{
while(start < MAX){
// try to acquire the number of semaphore equal to your value
// and if you do not get it then wait for it.
semaphore.acquire(start);
System.out.println(name + " : " + start);
// prepare for the next iteration.
start+=2;
// release one less than what you need to print in the next iteration.
// This will release the other thread which is waiting to print the next number.
semaphore.release(start-1);
}
} catch(InterruptedException e){
}
}
}
public static void main(String args[]) {
EvenOddThreadTest test = new EvenOddThreadTest();
PrinterThread a = test.new PrinterThread("Even",1);
PrinterThread b = test.new PrinterThread("Odd", 2);
try {
a.start();
b.start();
} catch (Exception e) {
}
}
}
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5
if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
if viewController.isKind(of: LoginViewController.self) {
}
}
}
Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function
function Animal(){
this.abc = 1;
return 1234;
}
var x = new Animal();
var y = Animal();
console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIKE operator (but this will be slow):
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
You can access the function itself using arguments.callee
[MDN]:
if (counter>0) {
arguments.callee(counter-1);
}
This will break in strict mode, however.
Simple solution is:
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
char[] cs = str.toCharArray();
char first = cs[0];
cs[0] = cs[cs.length -1];
cs[cs.length -1] = first;
return new String(cs);
}
Using a character array (watch out for the nasty empty String or null String argument!)
Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length()-1));
sb.setCharAt(sb.length()-1, first);
return sb.toString();
}
Yet another approach (more for instruction than actual use) is this one:
public String frontBack(String str) {
if (str == null || str.length() < 2) {
return str;
}
StringBuilder sb = new StringBuilder(str);
String sub = sb.substring(1, sb.length() -1);
return sb.reverse().replace(1, sb.length() -1, sub).toString();
}
Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)
Okay, first a few terms slightly oversimplified.
In git
, a tag
(like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.
Now a branch
is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.
Your HEAD
is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD
will point to master
which in turn will point to a commit. When you then do something like git checkout experimental
, you switch the HEAD
to point to the experimental
branch which might point to a different commit.
Now the explanation.
When you do a git checkout v2.0
, you are switching to a commit that is not pointed to by a branch
. The HEAD
is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.
Usually, what you can do is to say git checkout -b v2.0-fixes v2.0
. This will create a new branch pointer at the commit pointed to by the treeish v2.0
(a tag in this case) and then shift your HEAD
to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes
branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0
code. If however, you want to make any alterations there which you want to track, you'll need a branch.
You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.
Unfortunately. Most answers here either do not preserve the order or are too long. Here is a simple, order preserving answer.
s = [1,2,3,4,5,2,5,6,7,1,3,9,3,5]
x=[]
[x.append(i) for i in s if i not in x]
print(x)
This will give you x with duplicates removed but preserving the order.
Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601 there is no need to apply DateTimeFormatter
since LocalDateTime is already prepared for it:
Convert LocalDateTime to Time Zone ISO8601 String
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneOffset.UTC); //you might use a different zone
String iso8601 = zdt.toString();
Convert from ISO8601 String back to a LocalDateTime
String iso8601 = "2016-02-14T18:32:04.150Z";
ZonedDateTime zdt = ZonedDateTime.parse(iso8601);
LocalDateTime ldt = zdt.toLocalDateTime();
if you don't like the double brackets or you don't want to write a function, you can just use a variable.
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
When you start tomcat independently and type http://localhost:8080/
, tomcat show its default page (tomcat has its default page at TOMCAT_ROOT_DIRECTORY\webapps\ROOT\index.jsp
).
When you start tomcat from eclipse, eclipse doesn't have any default page for url http://localhost:8080/
so it show error message. This doesn't mean that tomcat7 is not running.when you put your project specific url like http://localhost:8080/PROJECT_NAME_YOU_HAVE_CREATE_USING_ECLIPSE
will display the default page of your web project.
You may use Socket for this like
String host = "www.yourhost.com";
Socket socket = new Socket(host, 80);
String request = "GET / HTTP/1.0\r\n\r\n";
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();
InputStream is = socket.getInputStream();
int ch;
while( (ch=is.read())!= -1)
System.out.print((char)ch);
socket.close();
I got simular problem. After signing and publishing my app to the google PlayStore it seems the Hash has changed. I added the new Hash (as mentioned) in the Facebook messaged to the Key Hashes in my app on developers.facebook.com/app//settings. Now it works again.
UPDATE tbl_ClientNotes
SET
ordering=ISNULL@ordering,ordering),
title=isnull(@title,title),
content=isnull(@content,content)
WHERE id=@id
I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.
There are a couple of commonly quoted solutions to this problem. Unfortunately neither of these are entirely satisfactory:
But then there's reflection. Is there anything you can't do using reflection?
private static void removeCryptographyRestrictions() {
if (!isRestrictedCryptography()) {
logger.fine("Cryptography restrictions removal not needed");
return;
}
try {
/*
* Do the following, but with reflection to bypass access checks:
*
* JceSecurity.isRestricted = false;
* JceSecurity.defaultPolicy.perms.clear();
* JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
*/
final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");
final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
isRestrictedField.setAccessible(true);
final Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
isRestrictedField.set(null, false);
final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
defaultPolicyField.setAccessible(true);
final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);
final Field perms = cryptoPermissions.getDeclaredField("perms");
perms.setAccessible(true);
((Map<?, ?>) perms.get(defaultPolicy)).clear();
final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
instance.setAccessible(true);
defaultPolicy.add((Permission) instance.get(null));
logger.fine("Successfully removed cryptography restrictions");
} catch (final Exception e) {
logger.log(Level.WARNING, "Failed to remove cryptography restrictions", e);
}
}
private static boolean isRestrictedCryptography() {
// This matches Oracle Java 7 and 8, but not Java 9 or OpenJDK.
final String name = System.getProperty("java.runtime.name");
final String ver = System.getProperty("java.version");
return name != null && name.equals("Java(TM) SE Runtime Environment")
&& ver != null && (ver.startsWith("1.7") || ver.startsWith("1.8"));
}
Simply call removeCryptographyRestrictions()
from a static initializer or such before performing any cryptographic operations.
The JceSecurity.isRestricted = false
part is all that is needed to use 256-bit ciphers directly; however, without the two other operations, Cipher.getMaxAllowedKeyLength()
will still keep reporting 128, and 256-bit TLS cipher suites won't work.
This code works on Oracle Java 7 and 8, and automatically skips the process on Java 9 and OpenJDK where it's not needed. Being an ugly hack after all, it likely doesn't work on other vendors' VMs.
It also doesn't work on Oracle Java 6, because the private JCE classes are obfuscated there. The obfuscation does not change from version to version though, so it is still technically possible to support Java 6.
I have the same problem, the difference is I don't have access to the source code. I've fixed my problem by putting correct version of EntityFramework.SqlServer.dll in the bin directory of the application.
In javascript (node.js) this works for me:
describe('UI', function() {
describe('gets results from Bing', function() {
this.timeout(10000);
it('makes a search', function(done) {
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('http://bing.com');
var input = driver.findElement(webdriver.By.name('q'));
input.sendKeys('something');
input.sendKeys(webdriver.Key.ENTER);
driver.wait(function() {
driver.findElement(webdriver.By.className('sb_count')).
getText().
then(function(result) {
console.log('result: ', result);
done();
});
}, 8000);
});
});
});
For tab use webdriver.Key.TAB
Simply check it by calling post method on your layout or view
view.post( new Runnable() {
@Override
public void run() {
// your layout is now drawn completely , use it here.
}
});
install pip: https://pip.pypa.io/en/latest/installing.html
insatll boto: https://github.com/boto/boto
$ git clone git://github.com/boto/boto.git
$ cd boto
$ python setup.py install
Ahmet's answer provides on how to assign the comma separated values to String array.
To use the above configuration in different classes you might need to create getters/setters for this.. But if you would like to load this configuration once and keep using this as a bean with Autowired annotation, here is the how I accomplished:
In ConfigProvider.java
@Bean (name = "ignoreFileNames")
@ConfigurationProperties ( prefix = "ignore.filenames" )
public List<String> ignoreFileNames(){
return new ArrayList<String>();
}
In outside classes:
@Autowired
@Qualifier("ignoreFileNames")
private List<String> ignoreFileNames;
you can use the same list everywhere else by autowiring.
You want instanceof
:
if (value instanceof Integer)
This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do
if (value.getClass() == Integer.class)
or
if (Integer.class.equals(value.getClass())
My JSON file name: terrifcalculatordata.json
[
{
"id": 1,
"name": "Vigo",
"picture": "./static/images/vigo.png",
"charges": "PKR 100 per excess km"
},
{
"id": 2,
"name": "Mercedes",
"picture": "./static/images/Marcedes.jpg",
"charges": "PKR 200 per excess km"
},
{
"id": 3,
"name": "Lexus",
"picture": "./static/images/Lexus.jpg",
"charges": "PKR 150 per excess km"
}
]
First , import on top:
import calculatorData from "../static/data/terrifcalculatordata.json";
then after return:
<div>
{
calculatorData.map((calculatedata, index) => {
return (
<div key={index}>
<img
src={calculatedata.picture}
class="d-block"
height="170"
/>
<p>
{calculatedata.charges}
</p>
</div>
You can use Apache commons-lang
StringUtils.isEmpty(String str)
- Checks if a String is empty ("") or null.
or
StringUtils.isBlank(String str)
- Checks if a String is whitespace, empty ("") or null.
the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API
Try out the CImg library. The tutorial will help you get familiarized. Once you have a CImg object, the data() function will give you access to the 2D pixel buffer array.
Also check this answer from here: Cannot manually edit applicationhost.config
The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.
So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.
How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.
Ok - thanks to all of you - let me wrap this up:
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
This code helps to change the background of the title bar programmatically in Android. Change the color to any color you want.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));
}
Inside public folder create an assets folder and place image path accordingly.
<img className="img-fluid"
src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`}
alt="logo"/>
Try it this way, I just made some light changes:
MailMessage msg = new MailMessage();
msg.From = new MailAddress("[email protected]");
msg.To.Add("[email protected]");
msg.Subject = "test";
msg.Body = "Test Content";
//msg.Priority = MailPriority.High;
using (SmtpClient client = new SmtpClient())
{
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("[email protected]", "mypassword");
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
Also please show your app.config file, if you have mail settings there.
sometimes will b usable this line on any layout or components.
android:background="?attr/selectableItemBackground"
Like as.
<RelativeLayout
android:id="@+id/relative_ticket_checkin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="?attr/selectableItemBackground">
Try the following:
java -cp jar1:jar2:jar3:dir1:. HelloWorld
The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.
i wrote a simple function for this:
Function (stringVar param)
(
Local stringVar oneChar := '0';
Local numberVar strLen := Length(param);
Local numberVar index := strLen;
oneChar = param[strLen];
while index > 0 and oneChar = '0' do
(
oneChar := param[index];
index := index - 1;
);
Left(param , index + 1);
)
mongod --dbpath [path_to_data_directory]
You can use a combination of substring and lastIndexOf
Sample
var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
If you want to transpose a matrix like A = np.array([[1,2],[3,4]]), then you can simply use A.T, but for a vector like a = [1,2], a.T does not return a transpose! and you need to use a.reshape(-1, 1), as below
import numpy as np
a = np.array([1,2])
print('a.T not transposing Python!\n','a = ',a,'\n','a.T = ', a.T)
print('Transpose of vector a is: \n',a.reshape(-1, 1))
A = np.array([[1,2],[3,4]])
print('Transpose of matrix A is: \n',A.T)
I recently saw this one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
As a small note, it only started to work for me when I changed smtp to smtps in the examples above per samples from javamail (see smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip, option -S).
My resulting code is as follow:
Properties props=new Properties();
props.put("mail.smtps.starttls.enable","true");
// Use the following if you need SSL
props.put("mail.smtps.socketFactory.port", port);
props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.host", serverList.get(randNum));
Session session = Session.getDefaultInstance(props);
smtpConnectionPool = new SmtpConnectionPool(
SmtpConnectionFactories.newSmtpFactory(session));
final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
...
transport.sendMessage(message, message.getAllRecipients());
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
Use
[databaseName]
db.Drop+databaseName();
drop collection
use databaseName
db.collectionName.drop();
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=db-server;'
'Database=db;'
'Trusted_Connection=yes;')
sql = "SELECT * FROM [mytable] "
cursor.execute(sql)
for r in cursor:
print(r)
Add below line in ${kafka_home}/config/server.properties
delete.topic.enable=true
Restart the kafka server with new config:
${kafka_home}/bin/kafka-server-start.sh ~/kafka/config/server.properties
Delete the topics you wish to:
${kafka_home}/bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic daemon12
If the jdk.tools is present in the .m2 repository. Still you get the error something like this:
missing artifact: jdk.tools.....c:.../jre/..
In the buildpath->configure build path-->Libraries.Just change JRE system library from JRE to JDK.
Options>Advanced>connections
Uncheck the option :
Use port 80 and 443 as alternative....
In the context of db: Stored procedure is precompiled execution plan where as functions are not.
$data = array(
'name' => $_POST['name'] ,
'groupname' => $_POST['groupname'],
'age' => $_POST['age']
);
$this->db->where('id', $_POST['id']);
$this->db->update('tbl_user', $data);
I had the same problem on Mac OS Try to run sudo mongod and in a new terminal tab run mongo
pip install -r requirements.txt
and in the requirements.txt file you put your modules in a list, with one item per line.
Django=1.3.1
South>=0.7
django-debug-toolbar
You have a misplaced closing brace before the return
statement.
You can add in your .bashrc
file:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
and it will dynamically change when you update your packages.
The solucion that work for me is the following
$filter('filter')(data, {'id':10})
An internal table data is stored in the warehouse folder, whereas an external table data is stored at the location you mentioned in table creation.
So when you delete an internal table, it deletes the schema as well as the data under the warehouse folder, but for an external table it's only the schema that you will loose.
So when you want an external table back you again after deleting it, can create a table with the same schema again and point it to the original data location. Hope it is clear now.
5 days ago from a particular date:
$date = new DateTime('2008-12-02');
$date->sub(new DateInterval('P5D'));
echo $date->format('Y-m-d') . "\n";
For me the nicest way of displaying it (the footer) is sticking to the bottom but not covering content all the time:
#my_footer {
position: static
fixed; bottom: 0
}
One way is:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
It is deprecated, and you should try the following code instead. The first two lines of code gives you the DisplayMetrics
objecs. This objects contains the fields like heightPixels
, widthPixels
.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
Api level 30 update
final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
// Gets all excluding insets
final WindowInsets windowInsets = metrics.getWindowInsets();
Insets insets = windowInsets.getInsetsIgnoreVisibility(WindowInsets.Type.navigationBars()
| WindowInsets.Type.displayCutout());
int insetsWidth = insets.right + insets.left;
int insetsHeight = insets.top + insets.bottom;
// Legacy size that Display#getSize reports
final Rect bounds = metrics.getBounds();
final Size legacySize = new Size(bounds.width() - insetsWidth,
bounds.height() - insetsHeight);
If you can make the assumption that all children are either Element Nodes or Text Nodes, then this is one solution.
To get all child text nodes as a jquery collection:
$('selector').clone().children().remove().end().contents();
To get a copy of the original element with non-text children removed:
$('selector').clone().children().remove().end();
I checked the line 35 of xampp/apache/conf/httpd.conf and it was:
ServerRoot "/xampp/apache"
Which doesn't exist. ...
Create the directory, or change the path to the directory that contains your hypertext documents.
$time = strtotime($oldtime);
Then use date()
to put it into the correct format.
While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).
I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.
I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.
If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.
Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.
Update 2: Same solution seems to be needed on iOS 13 beta builds as well.
Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).
An example of its use:
li * {
display: initial;
}
Working with Python 2.7.6 and 2.7.13
import urllib2
req = urllib2.Request('http://icanhazip.com', data=None)
response = urllib2.urlopen(req, timeout=5)
print(response.read())
You can use the assign
function:
df = df.assign(industry='yyy')
I was looking for this myself when we changed domain on our Wordpress website. It can't be done without some programming so this is what I did.
<?php
header("Content-Type: text/plain");
$host = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";
$string_to_replace = 'old.example.com';
$new_string = 'new.example.com';
// Connect to database server
mysql_connect($host, $username, $password);
// Select database
mysql_select_db($database);
// List all tables in database
$sql = "SHOW TABLES FROM ".$database;
$tables_result = mysql_query($sql);
if (!$tables_result) {
echo "Database error, could not list tables\nMySQL error: " . mysql_error();
exit;
}
echo "In these fields '$string_to_replace' have been replaced with '$new_string'\n\n";
while ($table = mysql_fetch_row($tables_result)) {
echo "Table: {$table[0]}\n";
$fields_result = mysql_query("SHOW COLUMNS FROM ".$table[0]);
if (!$fields_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($fields_result) > 0) {
while ($field = mysql_fetch_assoc($fields_result)) {
if (stripos($field['Type'], "VARCHAR") !== false || stripos($field['Type'], "TEXT") !== false) {
echo " ".$field['Field']."\n";
$sql = "UPDATE ".$table[0]." SET ".$field['Field']." = replace(".$field['Field'].", '$string_to_replace', '$new_string')";
mysql_query($sql);
}
}
echo "\n";
}
}
mysql_free_result($tables_result);
?>
Hope it helps anyone who's stumbling into this problem in the future :)
Your branch may not be up to date, a simple solution but try git fetch
The query should be:
(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))
You missed & and ()
This is how you can do it from DB2 client.
Open the Command Editor and Run the select Query in the Commands Tab.
Open the corresponding Query Results Tab
Then from Menu --> Selected --> Export
There is also who is active?:
Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids
Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:
Gson gson = new GsonBuilder()
.registerTypeAdapter(BloodPressurePost.class, new BloodPressurePostSerializer())
In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.
public class BloodPressurePostSerializer implements JsonSerializer<BloodPressurePost> {
@Override
public JsonElement serialize(BloodPressurePost src, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject jsonObject = new JsonObject();
if (src.systolic > 0) {
jsonObject.addProperty("systolic", src.systolic);
}
if (src.diastolic > 0) {
jsonObject.addProperty("diastolic", src.diastolic);
}
jsonObject.addProperty("units", src.units);
return jsonObject;
}
}
Ammending as "optional Answer". If you don't need to programmatically solve the problem, here goes the "visual way" in VS2012.
In Visual Studio, you can set custom format directly from the properties Panel:
First Set the "Format" property to: "Custom"; Secondly, set your custom format to: "dd-MM-yyyy";
The DATEDIFF function can give you the number of days between two dates. Which is more accurate, since... how do you define a month? (28, 29, 30, or 31 days?)
Instead of the conventional read.table I feel fread is a faster function. Specifying additional attributes like select only the required columns, specifying colclasses and string as factors will reduce the time take to import the file.
data_frame <- fread("filename.csv",sep=",",header=FALSE,stringsAsFactors=FALSE,select=c(1,4,5,6,7),colClasses=c("as.numeric","as.character","as.numeric","as.Date","as.Factor"))
You need to create a comparator. I am not sure why each value needs its own map but here is what the comparator would look like:
class ListMapComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
Map<String, String> test1 = (Map<String, String>) obj1;
Map<String, String> test2 = (Map<String, String>) obj2;
return test1.get("name").compareTo(test2.get("name"));
}
}
You can see it working with your above example with this:
public class MapSort {
public List<Map<String, String>> testMap() {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> myMap1 = new HashMap<String, String>();
myMap1.put("name", "Josh");
Map<String, String> myMap2 = new HashMap<String, String>();
myMap2.put("name", "Anna");
Map<String, String> myMap3 = new HashMap<String, String>();
myMap3.put("name", "Bernie");
list.add(myMap1);
list.add(myMap2);
list.add(myMap3);
return list;
}
public static void main(String[] args) {
MapSort ms = new MapSort();
List<Map<String, String>> testMap = ms.testMap();
System.out.println("Before Sort: " + testMap);
Collections.sort(testMap, new ListMapComparator());
System.out.println("After Sort: " + testMap);
}
}
You will have some type safe warnings because I did not worry about these. Hope that helps.
The .bashrc file is in your home directory.
So from command line do:
cd
ls -a
This will show all the hidden files in your home directory. "cd" will get you home and ls -a will "list all".
In general when you see ~/ the tilda slash refers to your home directory. So ~/.bashrc is your home directory with the .bashrc file.
And the standard path to homebrew is in /usr/local/ so if you:
cd /usr/local
ls | grep -i homebrew
you should see the homebrew directory (/usr/local/homebrew). Source
Yes sometimes you may have to create this file and the typical format of a .bashrc file is:
# .bashrc
# User specific aliases and functions
. .alias
alias ducks='du -cks * | sort -rn | head -15'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
PATH=$PATH:/home/username/bin:/usr/local/homebrew
export PATH
If you create your own .bashrc file make sure that the following line is in your ~/.bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.
In the latter case Webpack is generally the best way since it supports code splitting.
For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)
I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds
The code can be found here: https://github.com/thelgevold/angular-2-samples
Angular version: 4.1.x
Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.
Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.
This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).
Use the SqlDataAdapter, this would simplify everything.
//Your code to this point
DataTable dt = new DataTable();
using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
using(var da = new SqlDataAdapter(cmd))
{
da.Fill(dt):
}
}
and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).
If you are using windows 8 or later:
Everything should work fine. I don't know if it works exactly the same for other OS, but you don't have to set the PATH manually in Windows 8 or later.
This line:
[self dismissViewControllerAnimated:YES completion:nil];
isn't sending a message to itself, it's actually sending a message to its presenting VC, asking it to do the dismissing. When you present a VC, you create a relationship between the presenting VC and the presented one. So you should not destroy the presenting VC while it is presenting (the presented VC can't send that dismiss message back…). As you're not really taking account of it you are leaving the app in a confused state. See my answer Dismissing a Presented View Controller in which I recommend this method is more clearly written:
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
In your case, you need to ensure that all of the controlling is done in mainVC
. You should use a delegate to send the correct message back to MainViewController from ViewController1, so that mainVC can dismiss VC1 and then present VC2.
In VC2 VC1 add a protocol in your .h file above the @interface:
@protocol ViewController1Protocol <NSObject>
- (void)dismissAndPresentVC2;
@end
and lower down in the same file in the @interface section declare a property to hold the delegate pointer:
@property (nonatomic,weak) id <ViewController1Protocol> delegate;
In the VC1 .m file, the dismiss button method should call the delegate method
- (IBAction)buttonPressedFromVC1:(UIButton *)sender {
[self.delegate dissmissAndPresentVC2]
}
Now in mainVC, set it as VC1's delegate when creating VC1:
- (IBAction)present1:(id)sender {
ViewController1* vc = [[ViewController1 alloc] initWithNibName:@"ViewController1" bundle:nil];
vc.delegate = self;
[self present:vc];
}
and implement the delegate method:
- (void)dismissAndPresent2 {
[self dismissViewControllerAnimated:NO completion:^{
[self present2:nil];
}];
}
present2:
can be the same method as your VC2Pressed:
button IBAction method. Note that it is called from the completion block to ensure that VC2 is not presented until VC1 is fully dismissed.
You are now moving from VC1->VCMain->VC2 so you will probably want only one of the transitions to be animated.
update
In your comments you express surprise at the complexity required to achieve a seemingly simple thing. I assure you, this delegation pattern is so central to much of Objective-C and Cocoa, and this example is about the most simple you can get, that you really should make the effort to get comfortable with it.
In Apple's View Controller Programming Guide they have this to say:
Dismissing a Presented View Controller
When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it. Although there are several techniques for notifying the presenting view controller that its presented view controller should be dismissed, the preferred technique is delegation. For more information, see “Using Delegation to Communicate with Other Controllers.”
If you really think through what you want to achieve, and how you are going about it, you will realise that messaging your MainViewController to do all of the work is the only logical way out given that you don't want to use a NavigationController. If you do use a NavController, in effect you are 'delegating', even if not explicitly, to the navController to do all of the work. There needs to be some object that keeps a central track of what's going on with your VC navigation, and you need some method of communicating with it, whatever you do.
In practice Apple's advice is a little extreme... in normal cases, you don't need to make a dedicated delegate and method, you can rely on [self presentingViewController] dismissViewControllerAnimated:
- it's when in cases like yours that you want your dismissing to have other effects on remote objects that you need to take care.
Here is something you could imagine to work without all the delegate hassle...
- (IBAction)dismiss:(id)sender {
[[self presentingViewController] dismissViewControllerAnimated:YES
completion:^{
[self.presentingViewController performSelector:@selector(presentVC2:)
withObject:nil];
}];
}
After asking the presenting controller to dismiss us, we have a completion block which calls a method in the presentingViewController to invoke VC2. No delegate needed. (A big selling point of blocks is that they reduce the need for delegates in these circumstances). However in this case there are a few things getting in the way...
present2
- you can end up with difficult-to-debug errors or crashes. Delegates help you to avoid this.So please... take the time to learn delegation!
update2
In your comment you have managed to make it work by using this in VC2's dismiss button handler:
[self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
This is certainly much simpler, but it leaves you with a number of issues.
Tight coupling
You are hard-wiring your viewController structure together. For example, if you were to insert a new viewController before mainVC, your required behaviour would break (you would navigate to the prior one). In VC1 you have also had to #import VC2. Therefore you have quite a lot of inter-dependencies, which breaks OOP/MVC objectives.
Using delegates, neither VC1 nor VC2 need to know anything about mainVC or it's antecedents so we keep everything loosely-coupled and modular.
Memory
VC1 has not gone away, you still hold two pointers to it:
presentedViewController
propertypresentingViewController
propertyYou can test this by logging, and also just by doing this from VC2
[self dismissViewControllerAnimated:YES completion:nil];
It still works, still gets you back to VC1.
That seems to me like a memory leak.
The clue to this is in the warning you are getting here:
[self presentViewController:vc2 animated:YES completion:nil];
[self dismissViewControllerAnimated:YES completion:nil];
// Attempt to dismiss from view controller <VC1: 0x715e460>
// while a presentation or dismiss is in progress!
The logic breaks down, as you are attempting to dismiss the presenting VC of which VC2 is the presented VC. The second message doesn't really get executed - well perhaps some stuff happens, but you are still left with two pointers to an object you thought you had got rid of. (edit - I've checked this and it's not so bad, both objects do go away when you get back to mainVC)
That's a rather long-winded way of saying - please, use delegates. If it helps, I made another brief description of the pattern here:
Is passing a controller in a construtor always a bad practice?
update 3
If you really want to avoid delegates, this could be the best way out:
In VC1:
[self presentViewController:VC2
animated:YES
completion:nil];
But don't dismiss anything... as we ascertained, it doesn't really happen anyway.
In VC2:
[self.presentingViewController.presentingViewController
dismissViewControllerAnimated:YES
completion:nil];
As we (know) we haven't dismissed VC1, we can reach back through VC1 to MainVC. MainVC dismisses VC1. Because VC1 has gone, it's presented VC2 goes with it, so you are back at MainVC in a clean state.
It's still highly coupled, as VC1 needs to know about VC2, and VC2 needs to know that it was arrived at via MainVC->VC1, but it's the best you're going to get without a bit of explicit delegation.
Notepad++ also handles multiple cursors now.
Go into Settings => Preferences => Editing and check "Enable" in "Multi editing settings" Then, just use Ctrl+click to use multiple cursors.
Feature demo on official website here : https://npp-user-manual.org/docs/editing/
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()
This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...
Its called Short circuit operator.
Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.
It could also be used to set a default value for function argument.`
function theSameOldFoo(name){
name = name || 'Bar' ;
console.log("My best friend's name is " + name);
}
theSameOldFoo(); // My best friend's name is Bar
theSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar`
Using the accepted answer my script kept returning exceptionally early (right after 'exec > >(tee ...)') leaving the rest of my script running in the background. As I couldn't get that solution to work my way I found another solution/work around to the problem:
# Logging setup
logfile=mylogfile
mkfifo ${logfile}.pipe
tee < ${logfile}.pipe $logfile &
exec &> ${logfile}.pipe
rm ${logfile}.pipe
# Rest of my script
This makes output from script go from the process, through the pipe into the sub background process of 'tee' that logs everything to disc and to original stdout of the script.
Note that 'exec &>' redirects both stdout and stderr, we could redirect them separately if we like, or change to 'exec >' if we just want stdout.
Even thou the pipe is removed from the file system in the beginning of the script it will continue to function until the processes finishes. We just can't reference it using the file name after the rm-line.
First, your success()
handler just returns the data, but that's not returned to the caller of getData()
since it's already in a callback. $http
is an asynchronous call that returns a $promise
, so you have to register a callback for when the data is available.
I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.
For simplicity, here's your same code re-written with a function callback provided by the calling controller:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
Now, $http
actually already returns a $promise, so this can be re-written:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
Finally, there's better ways to configure the $http
service to handle the headers for you using config()
to setup the $httpProvider
. Checkout the $http documentation for examples.
Update Java 8 usage of default
keyword:
As many others have noted The default visibility (no keyword)
the field will be accessible from inside the same package to which the class belongs.
Not to be confused with the new Java 8 feature (Default Methods) that allows an interface to provide an implementation when its labeled with the default
keyword.
See: Access modifiers
Why to use regex? PHP has some built in functionality to do that
<?php
$valid_symbols = array('-', '_');
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
echo "String 1 not acceptable acceptable";
}
?>
preg_match('/\s/',$username)
will check for blank space
!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols
Extending from the correct answer of Andrey-Egorov using .executeScript()
to conclude my own question example:
inputField = driver.findElement(webdriver.By.id('gbqfq'));
driver.executeScript("arguments[0].setAttribute('value', '" + longstring +"')", inputField);
Forget datalist element that good solution for autocomplete function, but not for combobox feature.
css:
.combobox {
display: inline-block;
position: relative;
}
.combobox select {
display: none;
position: absolute;
overflow-y: auto;
}
html:
<div class="combobox">
<input type="number" name="" value="" min="" max="" step=""/><br/>
<select size="3">
<option value="0"> 0</option>
<option value="25"> 25</option>
<option value="40"> 40</option>
</select>
</div>
js (jQuery):
$('.combobox').each(function() {
var
$input = $(this).find('input'),
$select = $(this).find('select');
function hideSelect() {
setTimeout(function() {
if (!$select.is(':focus') && !$input.is(':focus')) {
$select
.hide()
.css('z-index', 1);
}
}, 20);
}
$input
.focusin(function() {
if (!$select.is(':visible')) {
$select
.outerWidth($input.outerWidth())
.show()
.css('z-index', 100);
}
})
.focusout(hideSelect)
.on('input', function() {
$select.val('');
});
$select
.change(function() {
$input.val($select.val());
})
.focusout(hideSelect);
});
This works properly even when you use text input instead of number.
Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
You could use a more generic converter
public class EnumBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
#endregion
}
And in the XAML-Part you use:
<Grid>
<Grid.Resources>
<l:EnumBooleanConverter x:Key="enumBooleanConverter" />
</Grid.Resources>
<StackPanel >
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
</StackPanel>
</Grid>
The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.
The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.
The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.
$(document).ready(
var xhr;
var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};
var interval = setInterval(fn, 500);
);
.format is a more readable way to handle variable formatting:
'{:.{prec}f}'.format(26.034, prec=2)
BEGIN TRANSACTION
select top 1 *
from table1
with (tablock, holdlock)
-- You do lots of things here
COMMIT
This will hold the 'table lock' until the end of your current "transaction".
You can go here to download the Java JRE.
You can go here to download the Java JDK.
After that you need to set up your environmental variables in Windows:
EDIT: See screenshot for environmental variables
I think you should use mvn install:install-file
to populate your local repository with the library jars then you should change the scope from system to compile.
If you are starting with maven I suggest to use maven directly not IDE plugins as it adds an extra layer of complexity.
As for the error, do you put the required jars on your classpath? If you are using types from the library, you need to have access to it in the runtime as well. This has nothing to do with maven itself.
I don't understand why you want to put the library to source control - it is for sources code not binary jars.
If you want to use a gentle approach via a beautiful (for terminal) interactive reporting interface I would suggest using npm-check.
It's less of a hammer and gives you more consequential knowledge of, and control over, your dependency updates.
To give you a taste of what awaits here's a screenshot (scraped from the git page for npm-check):
This directive works as a [routerLink] replacement. All you have to do is to replace your [routerLink] usages with [link]. It works with ctrl+click, cmd+click, middle click.
import {Directive, HostListener, Input} from '@angular/core'
import {Router} from '@angular/router'
import _ from 'lodash'
import qs from 'qs'
@Directive({
selector: '[link]'
})
export class LinkDirective {
@Input() link: string
@HostListener('click', ['$event'])
onClick($event) {
// ctrl+click, cmd+click
if ($event.ctrlKey || $event.metaKey) {
$event.preventDefault()
$event.stopPropagation()
window.open(this.getUrl(this.link), '_blank')
} else {
this.router.navigate(this.getLink(this.link))
}
}
@HostListener('mouseup', ['$event'])
onMouseUp($event) {
// middleclick
if ($event.which == 2) {
$event.preventDefault()
$event.stopPropagation()
window.open(this.getUrl(this.link), '_blank')
}
}
constructor(private router: Router) {}
private getLink(link): any[] {
if ( ! _.isArray(link)) {
link = [link]
}
return link
}
private getUrl(link): string {
let url = ''
if (_.isArray(link)) {
url = link[0]
if (link[1]) {
url += '?' + qs.stringify(link[1])
}
} else {
url = link
}
return url
}
}
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
Ok. I found the solution here tessnet2 fails to load the Ans given by Adam
Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.
it says
Quick Tessnet2 usage
Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.
Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the same directory.
After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!
Anyway I found it. Thanks everyone.
/**
* Use this function as jQuery "load" to disable request caching in IE
* Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
**/
$.fn.loadWithoutCache = function (){
var elem = $(this);
var func = arguments[1];
$.ajax({
url: arguments[0],
cache: false,
dataType: "html",
success: function(data, textStatus, XMLHttpRequest) {
elem.html(data);
if(func != undefined){
func(data, textStatus, XMLHttpRequest);
}
}
});
return elem;
}
You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.
You could give the span a set width, then add the margin:0 auto
again. This would center-align it.
.left
{
background-color: #999999;
height: 50px;
width: 24.5%;
}
span.panelTitleTxt
{
display:block;
width:100px;
height: 100%;
margin: 0 auto;
}
Are you searching for the log file in the right path: %h/one%u.log
Here %h resolves to your home : In windows this defaults to : C:\Documents and Settings(user_name).
I have tried the sample code you have posted and it works fine after you specify the configuration file path (logging.properties either through code or java args) .
By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:
android:background="#fff"
I solved it this way:
First, I stopped all running containers:
docker-compose down
Then I executed a lsof
command to find the process using the port (for me it was port 9000)
sudo lsof -i -P -n | grep 9000
Finally, I "killed" the process (in my case, it was a VSCode extension):
kill -9 <process id>
XSLT 1.0 does not have an integer data type, only double. You can use number()
to convert a string to a number.
For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.
Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)
Which will result in 11-22-2019
(depending on the current date)
I fixed this using pycharm. At the bottom of pycharm you can see file encoding. I noticed that it is UT-8. I changed it to US-ASCII
Just a reminder: Implicit type var
in multiple declaration is not allowed. There might be the following compilation errors.
var Foo = 0, Bar = 0;
Implicitly-typed variables cannot have multiple declarators
Similarly,
var Foo, Bar;
Implicitly-typed variables must be initialized
Try with this:
var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);
On Mac install nginx with brew:
/usr/local/etc/nginx/nginx.conf
location / {
root html; # **means /usr/local/Cellar/nginx/1.8.0/html and it soft linked to /usr/local/var/www**
index index.html;
}
This may seem bizarre, but it's worked for me and I have written a C# program to automate this.
Step 1: Truncate the transaction log (Back up only the transaction log, turning on the option to remove inactive transactions)
Step 2: Run a database shrink, moving all the pages to the start of the files
Step 3: Truncate the transaction log again, as step 2 adds log entries
Step 4: Run a database shrink again.
My stripped down code, which uses the SQL DMO library, is as follows:
SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_NoTruncate);
SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_Default);
Simple! You must only acept request, on your phone.
RenderPartial()
is a void method that writes to the response stream. A void method, in C#, needs a ;
and hence must be enclosed by { }
.
Partial()
is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @
prefix to distinguish it from plain HTML you have on the page.
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
Following Felix Klings advice I tried it out in my chrome browser.
console.dir([1,2])
gives the following output:
Array[2]
0: 1
1: 2
length: 2
__proto__: Array[0]
While console.log([1,2])
gives the following output:
[1, 2]
So I believe console.dir()
should be used to get more information like prototype etc in arrays and objects.
The problem is that you're displaying time()
, which is a UNIX timestamp based on GMT/UTC. That’s why it doesn’t change. date()
on the other hand, formats the time based on that timestamp.
A timestamp is the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
The generate 204 might be dynamically loading the suggestions of search criteria. AS i can see from my load test script, this is seemingly responsible for every server call each time the user types into the text box
findById
is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.
Example:
// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );
Functionally, it's the same as calling:
UserModel.findOne({_id: id}, function (err, user) { ... });
Note that Mongoose will cast the provided id
value to the type of _id
as defined in the schema (defaulting to ObjectId).
If you want to check the python version in a particular cond environment you can also use conda list python
You can use
$window.scrollTo(x, y);
where x
is the pixel along the horizontal axis and y
is the pixel along the vertical axis.
Scroll to top
$window.scrollTo(0, 0);
Focus on element
$window.scrollTo(0, angular.element('put here your element').offsetTop);
Update:
Also you can use $anchorScroll
dex2jar with jd-gui will give all the java source files but they are not exactly the same. They are almost equivalent .class files (not 100%). So if you want to change the code for an apk file:
decompile using apktool
apktool will generate smali(Assembly version of dex) file for every java file with same name.
smali is human understandable, make changes in the relevant file,
recompile using same apktool(apktool b Nw.apk <Folder Containing Modified Files>
)
If you are using a GUI and you are still getting the same problem. Just leave the size value empty, the primary key defaults the value to 11, you should be fine with this. Worked with Bitnami phpmyadmin.
In Windows 8, you may want to remove
C:\ProgramData\Oracle\Java\javapath
directory.
from path
It solved my issue.
My view templates are generally .php files. This is what I would be using for now.
<?php // Some comment here ?>
The solution is quite similar to what @Robert suggested, works for me. Is not very clean I guess.
Just use any one of NoException (my project), jOO?'s Unchecked, throwing-lambdas, Throwable interfaces, or Faux Pas.
// NoException
stream.map(Exceptions.sneak().function(Class::forName));
// jOO?
stream.map(Unchecked.function(Class::forName));
// throwing-lambdas
stream.map(Throwing.function(Class::forName).sneakyThrow());
// Throwable interfaces
stream.map(FunctionWithThrowable.aFunctionThatUnsafelyThrowsUnchecked(Class::forName));
// Faux Pas
stream.map(FauxPas.throwingFunction(Class::forName));
Go and look at the printf()
implementation with "%f"
in some C library.
Mux (my company) has an open source android app that streams RTMP to a server, including setting up the camera and user interactions. It's built to stream to Mux's live streaming API but can easily stream to any RTMP entrypoint.
specify your marks:
List<Double> marks = new ArrayList<Double>();
This is called generics.
Changing Bundle Identifier worked for me.
If it still doesn't work, try again with these steps before:
cd /Users/my_username/Library/MobileDevice/Provisioning Profiles && rm *
(in my case)I'm not sure if it would be faster, or even accurate, but you could use John Carmack's Magical Square Root, algorithm to solve the square root faster. You could probably easily test this for all possible 32 bit integers, and validate that you actually got correct results, as it's only an appoximation. However, now that I think about it, using doubles is approximating also, so I'm not sure how that would come into play.
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
This regex work for me (was using in Angular 8) :
([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){2,30}
It will be invalid if there is:-
- Any whitespace start or end of the name
- Got symbols e.g. @
- Less than 2 or more than 30
Example invalid First Name (whitespace)
Example valid First Name :
You can retrieve the group ID the same way. It appears in the message body as message.chat.id
and it's usually a negative number, where normal chats are positive.
Group IDs and Chat IDs can only be retrieved from a received message, there are no calls available to retrieve active groups etc. You have to remember the group ID when you receive the message and store it in cache or something similar.
The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):
import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)
which will produce:
a: [[1 4 0 1]
[1 3 2 4]
[1 0 2 1]
[3 1 0 0]
[1 4 0 1]]
b: [[0 1 0 0]
[0 1 0 1]
[0 0 0 0]
[1 0 0 0]
[0 1 0 0]]
The case is like :
mysql connects will localhost when network is not up.
mysql cannot connect when network is up.
You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):
This should ideally resolve the issue you are facing.
You could also use supervisord which is a very handy daemon, which can be used to easily control services. These services are defined by simple configuration files defining what to execute with which user in which directory and so forth, there are a zillion options. supervisord has a very simple syntax, so it makes a very good alternative to writing SysV init scripts.
Here a simple supervisord configuration file for the program you are trying to run/control. (put this into /etc/supervisor/conf.d/yourapp.conf)
[program:yourapp]
command=/usr/bin/java -jar /path/to/application.jar
user=usertorun
autostart=true
autorestart=true
startsecs=10
startretries=3
stdout_logfile=/var/log/yourapp-stdout.log
stderr_logfile=/var/log/yourapp-stderr.log
To control the application you would need to execute supervisorctl, which will present you with a prompt where you could start, stop, status yourapp.
# sudo supervisorctl
yourapp RUNNING pid 123123, uptime 1 day, 15:00:00
supervisor> stop yourapp
supervisor> start yourapp
If the supervisord
daemon is already running and you've added the configuration for your serivce without restarting the daemon you can simply do a reread
and update
command in the supervisorctl
shell.
This really gives you all the flexibilites you would have using SysV Init scripts, but easy to use and control. Take a look at the documentation.
Try as following, should return "exists" or "non exists":
<?php
echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';
To compare each item with the next one in an iterator without instantiating a list:
import itertools
it = (x for x in range(10))
data1, data2 = itertools.tee(it)
data2.next()
for a, b in itertools.izip(data1, data2):
print a, b
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
You should install PDO on your server.
Edit your php.ini (look at your phpinfo()
, "Loaded Configuration File" line, to find the php.ini file path).
Find and uncomment the following line (remove the ;
character):
;extension=pdo_mysql.so
Then, restart your Apache server. For more information, please read the documentation.
SSH doesn't use the :
syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config
file and add:
Host git.host.de Port 4019
Then specify just git.host.de
without a port number.
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.
/^[a-z0-9]+$/i
I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:
protected void Button1_Click(object sender, EventArgs e)
{
var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
<input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" />
<input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" />
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
Response.Write(formPostText);
}
Use max width and max height. It will keep the aspect ratio
#container img
{
max-width: 250px;
max-height: 250px;
}
If the input is formatted like this,
1 2 3
4 5 6
7 8 9
a one liner can be used
mat = [list(map(int,input().split())) for i in range(row)]
JUnit since 5.5 allows @TestMethodOrder(OrderAnnotation.class)
on class and @Order(1)
on test-methods.
JUnit old versions allow test methods run ordering using class annotations:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@FixMethodOrder(MethodSorters.JVM)
@FixMethodOrder(MethodSorters.DEFAULT)
By default test methods are run in alphabetical order. So, to set specific methods order you can name them like:
a_TestWorkUnit_WithCertainState_ShouldDoSomething b_TestWorkUnit_WithCertainState_ShouldDoSomething c_TestWorkUnit_WithCertainState_ShouldDoSomething
Or
_1_TestWorkUnit_WithCertainState_ShouldDoSomething _2_TestWorkUnit_WithCertainState_ShouldDoSomething _3_TestWorkUnit_WithCertainState_ShouldDoSomething
You can find examples here.
This is because ASP.NET it changing the Id of your textbox, if you run your page, and do a view source, you will see the text box id is something like
ctl00_ContentColumn_txt_model_code
There are a few ways round this:
Use the actual control name:
var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;
use the ClientID property within ASP script tags
document.getElementById('<%= txt_model_code.ClientID %>').value;
Or if you are running .NET 4 you can use the new ClientIdMode property, see this link for more details.
http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx1
Your ngClick
is correct; you just need the right service. $location
is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:
$location.path( '/new-page.html' );
The $location
service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.
You could also do something more flexible with a directive if you so chose:
.directive( 'goClick', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'goClick', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path( path );
});
});
};
});
And then you could use it on anything:
<button go-click="/go/to/this">Click!</button>
There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.
This function collect all matching sequences from string. In this example it takes all email addresses from string.
static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
public List<String> getAllEmails(String message) {
List<String> result = null;
Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);
if (matcher.find()) {
result = new ArrayList<String>();
result.add(matcher.group());
while (matcher.find()) {
result.add(matcher.group());
}
}
return result;
}
For message = "[email protected], <[email protected]>>>> [email protected]"
it will create List of 3 elements.
Applying the suggestions mentioned, I've faced the issue of app getting killed whenever default icon gets changed to new icon. So have implemented the code with some tweaks. Step 1). In file AndroidManifest.xml, create for default activity with android:enabled="true" & other alias with android:enabled="false". Your will not contain but append those in with android:enabled="true".
<activity
android:name=".activities.SplashActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/SplashTheme">
</activity>
<!-- <activity-alias used to change app icon dynamically> : default icon, set enabled true -->
<activity-alias
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:name=".SplashActivityAlias1" <!--put any random name started with dot-->
android:enabled="true"
android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<!-- <activity-alias used to change app icon dynamically> : sale icon, set enabled false initially -->
<activity-alias
android:label="@string/app_name"
android:icon="@drawable/ic_store_marker"
android:roundIcon="@drawable/ic_store_marker"
android:name=".SplashActivityAlias" <!--put any random name started with dot-->
android:enabled="false"
android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
Step 2). Make a method that will be used to disable 1st activity-alias that contains default icon & enable 2nd alias that contains icon need to be changed.
/**
* method to change the app icon dynamically
*
* @param context
* @param isNewIcon : true if new icon need to be set; false to set default
* icon
*/
public static void changeAppIconDynamically(Context context, boolean isNewIcon) {
PackageManager pm = context.getApplicationContext().getPackageManager();
if (isNewIcon) {
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias1"), //com.example.dummy will be your package
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
} else {
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias1"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
Step 3). Now call this method depending on your requirement, say on button click or date specific or occasion specific conditions, simply like -
// Switch app icon to new icon
GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, true);
// Switch app icon to default icon
GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, false);
Hope this will help those who face the issue of app getting killed on icon change. Happy Coding :)
I recommend using .htaccess
. You only need to add:
DirectoryIndex home.php
or whatever page name you want to have for it.
EDIT: basic htaccess tutorial.
1) Create .htaccess
file in the directory where you want to change the index file.
.
in front, to ensure it is a "hidden" fileEnter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.
2) Set server to allow reading of .htaccess
files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)
Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default
for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:
sudo service apache2 restart
Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.
Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess
file in that sub-site's root and it will overwrite the declaration in the parent.
in devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
import requests
img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
handler.write(img_data)
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
The answer to the question specifically asked is no. But have you been looking at mocking frameworks? I use MOQ but there's millions of them out there and they allow you to implement/stub (partially or fully) interfaces in-line. Eg.
public void ThisWillWork()
{
var source = new DummySource[0];
var mock = new Mock<DummyInterface>();
mock.SetupProperty(m => m.A, source.Select(s => s.A));
mock.SetupProperty(m => m.B, source.Select(s => s.C + "_" + s.D));
DoSomethingWithDummyInterface(mock.Object);
}
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
You can Add this :
...
dlg.dialog({ autoOpen:false,
modal: true,
width: 400,
open: function(){ // There is new line
$("#txtStartDate").focus();
}
});
...
This worked for me in Firefox and Chrome and IE8...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
div.section:hover div.image, div.section:hover div.layer {
border: solid 1px red;
}
</style>
</head>
<body>
<div class="section">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</body>
</html>
... you may want to test this with IE6 as well (I'm not sure if it'll work there).
You can configure a proxy with conda by adding it to the .condarc
, like
proxy_servers:
http: http://user:[email protected]:8080
https: https://user:[email protected]:8080
or set the HTTP_PROXY
and HTTPS_PROXY
environment variables. Note that in your case you need to add the scheme to the proxy url, like https://proxy-us.bla.com:123.
See http://conda.pydata.org/docs/config.html#configure-conda-for-use-behind-a-proxy-server.
you can solve the problem much simple like First convert the the given string to the date object eg:
java.util.Date date1 = new Date("11/19/2015");
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd yyyy HH:mma");
String format = formatter.format(date);
System.out.println(format);
Basic Solution for Laravel 8 is
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com');
I had conflict between "GuzzleHTTP sending requests" and "Illuminate\Http\Request;" don't ask me why... [it's here to be searchable]
So looking for 1sec i found in Laravel 8 Doc...
https://laravel.com/docs/8.x/http-client#making-requests
as you can see
https://laravel.com/docs/8.x/http-client#introduction
Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.
It worked for me very well, have fun and if helpful point up!
This is an answer I've already given some time ago:
It depends entirely on the domain-specific application needs. A lot of times direct text file/binary files access can be extremely fast, efficient, as well as providing you all the file access capabilities of your OS's file system.
Furthermore, your programming language most likely already has a built-in module (or is easy to make one) for specific parsing.
If what you need is many appends (INSERTS?) and sequential/few access little/no concurrency, files are the way to go.
On the other hand, when your requirements for concurrency, non-sequential reading/writing, atomicity, atomic permissions, your data is relational by the nature etc., you will be better off with a relational or OO database.
There is a lot that can be accomplished with SQLite3, which is extremely light (under 300kb), ACID compliant, written in C/C++, and highly ubiquitous (if it isn't already included in your programming language -for example Python-, there is surely one available). It can be useful even on db files as big as 140 terabytes, or 128 tebibytes (Link to Database Size), possible more.
If your requirements where bigger, there wouldn't even be a discussion, go for a full-blown RDBMS.
As you say in a comment that "the system" is merely a bunch of scripts, then you should take a look at pgbash.
As it was said in other answers there is no way to make a POST request using window.location.href, to do it you can create a form and submit it immediately.
You can use this function:
function postForm(path, params, method) {
method = method || 'post';
var form = document.createElement('form');
form.setAttribute('method', method);
form.setAttribute('action', path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
postForm('mysite.com/form', {arg1: 'value1', arg2: 'value2'});
Just my two cents:
Cold deployment is the way of deploying an application when you stop it (or stop the whole server), then you install the new version, and finally restart the application (or start the whole server). It's suitable for official production deployments, but it would be horrible slow to do this during development. Forget about rapid development if you are doing this.
Auto deployment is the ability the server has to re-scan periodically for a new EAR/WAR and deploy it automagically behind the scenes for you, or for the IDE (Eclipse) to deploy automagically the whole application when you make changes to the source code. JBoss does this, but JBoss's marketing department call this misleadingly "hot deployment". An auto deployment is not as slow compared to a cold deployment, but is really slow compared to a hot deployment.
Hot deployment is the ability to deploy behind the scenes "as you type". No need to redeploy the whole application when you make changes. Hot deployment ONLY deploys the changes. You change a Java source code, and voila! it's running already. You never noticed it was deploying it. JBoss cannot do this, unless you buy for JRebel (or similar) but this is too much $$ for me (I'm cheap).
Now my "sales pitch" :D
What about using Tomcat during development? Comes with hot deployment all day long... for free. I do that all the time during development and then I deploy on WebSphere, JBoss, or Weblogic. Don't get me wrong, these three are great for production, but are really AWFUL for rapid-development on your local machine. Development productivity goes down the drain if you use these three all day long.
In my experience, I stopped using WebSphere, JBoss, and Weblogic for rapid development. I still have them installed in my local environment, though, but only for the occasional test I may need to run. I don't pay for JRebel all the while I get awesome development speed. Did I mention Tomcat is fully compatible with JBoss?
Tomcat is free and not only has auto-deployment, but also REAL hot deployment (Java code, JSP, JSF, XHTML) as you type in Eclipse (Yes, you read well). MYKong has a page (https://www.mkyong.com/eclipse/how-to-configure-hot-deploy-in-eclipse/) with details on how to set it up.
Did you like my sales pitch?
Cheers!
The update statement in all versions of SQL looks like:
update table
set col1 = expr1,
col2 = expr2,
. . .
coln = exprn
where some condition
So, the answer is that you separate the assignments using commas and don't repeat the set
statement.
Call AddWithoutValidation
instead of Add
(see this MSDN link).
Alternatively, I'm guessing the API you are using really only requires this for POST or PUT requests (not ordinary GET requests). In that case, when you call HttpClient.PostAsync
and pass in an HttpContent
, set this on the Headers
property of that HttpContent
object.
Missed property runat="server"
or in code use Request.Params["TextArea1"]
You have to use the AppendText
method of the textbox directly. If you try to use the Text
property, the textbox will not scroll down as new line are appended.
textBox1.AppendText("Hello" + Environment.NewLine);
Using Numpy's fancy indexing:
>>> test
array([ 1, 23, 4, 6, 7, 8])
>>> test[::-1] # test, reversed
array([ 8, 7, 6, 4, 23, 1])
>>> numpy.vstack([test, test[::-1]]) # stack test and its reverse
array([[ 1, 23, 4, 6, 7, 8],
[ 8, 7, 6, 4, 23, 1]])
>>> # transpose, then take the first half;
>>> # +1 to cater to odd-length arrays
>>> numpy.vstack([test, test[::-1]]).T[:(len(test) + 1) // 2]
array([[ 1, 8],
[23, 7],
[ 4, 6]])
vstack
copies the array, but all the other operations are constant-time pointer tricks (including reversal) and hence are very fast.
Log in as root, then run the following MySQL commands:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;
This can be done in many ways. a. Using nested inside a tag.
<a href="link1.html">
<div> Something in the div </div>
</a>
b. Using the Inline JavaScript Method
<div onclick="javascript:window.location.href='link1.html' ">
Some Text
</div>
c. Using jQuery inside tag
HTML:
<div class="demo" > Some text here </div>
jQuery:
$(".demo").click( function() {
window.location.href="link1.html";
});
I don't want to include the Support library just for getColor, so I'm using something like
public static int getColorWrapper(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return context.getColor(id);
} else {
//noinspection deprecation
return context.getResources().getColor(id);
}
}
I guess the code should work just fine, and the deprecated getColor
cannot disappear from API < 23.
And this is what I'm using in Kotlin:
/**
* Returns a color associated with a particular resource ID.
*
* Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
*/
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);
For debian, from the 10gen repo, between 2.4.x and 2.6.x, they renamed the init script /etc/init.d/mongodb to /etc/init.d/mongod, and the default config file from /etc/mongodb.conf to /etc/mongod.conf, and the PID and lock files from "mongodb" to "mongod" too. This made upgrading a pain, and I don't see it mentioned in their docs anywhere. Anyway, the solution is to remove the old "mongodb" versions:
update-rc.d -f mongodb remove
rm /etc/init.d/mongodb
rm /var/run/mongodb.pid
diff -ur /etc/mongodb.conf /etc/mongod.conf
Now, look and see what config changes you need to keep, and put them in mongod.conf.
Then:
rm /etc/mongodb.conf
Now you can:
service mongod restart
Do install latest version instead of the recommended stable version. It will give you freedom to use latest ES6 Features on node.
Can be Found here Node JS.
sudo npm i -g npm@latest
All your projects will work fine.
Update: 2020 another good option is to use nvm
for node which can then support multiple versions.
use nvm install --lts
to always be able to update to latest node version use nvm ls-remote
command to to check new versions of node.
Other option for mac :: brew update && brew install node && npm -g npm
Contrary to .NET where all types derive from an "object", in TypeScript, all types derive from "any". I just wanted to add this comparison as I think it will be a common one made as more .NET developers give TypeScript a try.
Any one can try this command to truncate any file in linux system
This will surely work in any format :
truncate -s 0 file.txt
You can create 2 wrapper methods for saving and retrieving object from session storage.
function saveSession(obj) {
sessionStorage.setItem("myObj", JSON.stringify(obj));
return true;
}
function getSession() {
var obj = {};
if (typeof sessionStorage.myObj !== "undefined") {
obj = JSON.parse(sessionStorage.myObj);
}
return obj;
}
Use it like this:- Get object, modify some data, and save back.
var obj = getSession();
obj.newProperty = "Prod"
saveSession(obj);
So its the indentation that matters. As other users here have pointed out to you, when the indentation level is at the same point as the def function declaration your function has ended. Keep in mind that you cannot mix tabs and spaces in Python. Most editors provide support for this.
Would that work for you?
public class Main {
public static void main(String[] args) {
Random r = new Random(System.currentTimeMillis());
System.out.println(r.nextInt(100000) * 0.000001);
}
}
result e.g. 0.019007