To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).
file://///server/path/to/file.txt
Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:
For security purposes, Mozilla applications block links to local files (and directories) from remote files.
And less directly, from Google:
Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.
The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.
If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type
git status -- it will show the files with changes
then if you want to know what changes are to be made it can be checked in ways ,
git diff -- will show all the changes in all files
it is good only when only one file is modified
and if you want to check particular file then use
git diff
I fixed the same problem on Google Chrome with the following:
Choose Customize and control Google Chrome (the button in the top right corner).
Choose Settings.
Go to Extensions.
Unmark all the extensions there. (They should show as Enable instead of Enabled.)
jQuery plugin for decorating image maps (highlights, select areas, tooltips):
http://www.outsharked.com/imagemapster/
Disclosure: I wrote it.
Use the isSelected method.
You can also use an ItemListener so you'll be notified when it's checked or unchecked.
Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.
IMHO this is the best way to write your line :
private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
new HashMap<Class<? extends Persistent>, PersistentHelper>();
This way the increased indentation without any braces can help you to see that the code was just splited because the line was too long. And instead of 4 spaces, 8 will make it clearer.
select
count(1) "NO. Of DB Users",
to_char(sysdate,'DD-MON-YYYY:HH24:MI:SS') sys_time
from
v$session
where
username is NOT NULL;
A more recent version of the accepted answer.
Brief version:
$('#form').on('submit', function(e, options) {
options = options || {};
if ( !options.lots_of_stuff_done ) {
e.preventDefault();
$.ajax({
/* do lots of stuff */
}).then(function() {
// retrigger the submit event with lots_of_stuff_done set to true
$(e.currentTarget).trigger('submit', { 'lots_of_stuff_done': true });
});
} else {
/* allow default behavior to happen */
}
});
A good use case for something like this is where you may have some legacy form code that works, but you've been asked to enhance the form by adding something like email address validation before submitting the form. Instead of digging through the back-end form post code, you could write an API and then update your front-end code to hit that API first before allowing the form to do it's traditional POST.
To do that, you can implement code similar to what I've written here:
$('#signup_form').on('submit', function(e, options) {
options = options || {};
if ( !options.email_check_complete ) {
e.preventDefault(); // Prevent form from submitting.
$.ajax({
url: '/api/check_email'
type: 'get',
contentType: 'application/json',
data: {
'email_address': $('email').val()
}
})
.then(function() {
// e.type === 'submit', if you want this to be more dynamic
$(e.currentTarget).trigger(e.type, { 'email_check_complete': true });
})
.fail(function() {
alert('Email address is not valid. Please fix and try again.');
})
} else {
/**
Do traditional <form> post.
This code will be hit on the second pass through this handler because
the 'email_check_complete' option was passed in with the event.
*/
$('#notifications').html('Saving your personal settings...').fadeIn();
}
});
If your last field is a single character, you could do this:
a="1:2:3:4:5"
echo ${a: -1}
echo ${a:(-1)}
Check string manipulation in bash.
Specifying the column type as serial for PostgreSQL to generate the id.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }
https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL
You have to overwrite the file. In C++:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
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.
I ran into a similar problem and just passed the end of the array to the ArrayList.add()
index param like so:
public class Stack {
private ArrayList<String> stringList = new ArrayList<String>();
RandomStringGenerator rsg = new RandomStringGenerator();
private void push(){
String random = rsg.randomStringGenerator();
stringList.add(stringList.size(), random);
}
}
Copying Grid to datatable
if (GridView.Rows.Count != 0)
{
//Forloop for header
for (int i = 0; i < GridView.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(GridView.HeaderRow.Cells[i].Text);
}
//foreach for datarow
foreach (GridViewRow row in GridView.Rows)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < row.Cells.Count; j++)
{
dr[GridView.HeaderRow.Cells[j].Text] = row.Cells[j].Text;
}
dt.Rows.Add(dr);
}
//Loop for footer
if (GridView.FooterRow.Cells.Count != 0)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < GridView.FooterRow.Cells.Count; i++)
{
//You have to re-do the work if you did anything in databound for footer.
}
dt.Rows.Add(dr);
}
dt.TableName = "tb";
}
Uninstall node-sass
npm uninstall node-sass
use sass by:
npm install -g sass
npm install --save-dev sass
I solved this by doing the following:
<body class="container-fluid">
<div class="row">
<div class="span6" style="float: none; margin: 0 auto;">
....
</div>
</div>
</body>
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
They both represent floating point numbers. A FLOAT
is for single-precision, while a DOUBLE
is for double-precision numbers.
MySQL uses four bytes for single-precision values and eight bytes for double-precision values.
There is a big difference from floating point numbers and decimal (numeric) numbers, which you can use with the DECIMAL
data type. This is used to store exact numeric data values, unlike floating point numbers, where it is important to preserve exact precision, for example with monetary data.
you can use call back function, like this
$this->form_validation->set_rules('userfile', 'Document', 'callback_file_selected_test');
if ($this->form_validation->run() == FALSE) {
//error
}
else{
// success
}
function file_selected_test(){
$this->form_validation->set_message('file_selected_test', 'Please select file.');
if (empty($_FILES['userfile']['name'])) {
return false;
}else{
return true;
}
}
exec sp_execsql @Sql
The DB change only lasts for the time to complete @sql
http://blog.sqlauthority.com/2007/07/02/sql-server-2005-comparison-sp_executesql-vs-executeexec/
Keep both lists x and y in sorted order.
If x = y, do your action, if x < y, advance x, if y < x, advance y until either list is empty.
The run time of this intersection is proportional to min (size (x), size (y))
Don't run a .Contains () loop, this is proportional to x * y which is much worse.
Unplug your phone from the your computer, then choose PC Software as PC Connection Type. Then go into Developer Options and select USB Debugging
here is a quick review and with a simple and quick understanding
from teacher Beau Carnes from freecodecamp
lines2 = lines.split.join("\n")
To find all the pom.xml
files in your current directory and print them, you can use:
find . -name 'pom.xml' -print
On a recent project, some huge data structures were set up with data that was read in from a database (and hence not String constants/literals) but with a huge amount of duplication. It was a banking application, and things like the names of a modest set (maybe 100 or 200) corporations appeared all over the place. The data structures were already large, and if all those corp names had been unique objects they would have overflowed memory. Instead, all the data structures had references to the same 100 or 200 String objects, thus saving lots of space.
Another small advantage of interned Strings is that ==
can be used (successfully!) to compare Strings if all involved strings are guaranteed to be interned. Apart from the leaner syntax, this is also a performance enhancement. But as others have pointed out, doing this harbors a great risk of introducing programming errors, so this should be done only as a desparate measure of last resort.
The downside is that interning a String takes more time than simply throwing it on the heap, and that the space for interned Strings may be limited, depending on the Java implementation. It's best done when you're dealing with a known reasonable number of Strings with many duplications.
If you're using membership you can do: Membership.GetUser()
Your code is returning the Windows account which is assigned with ASP.NET.
Additional Info Edit: You will want to include System.Web.Security
using System.Web.Security
Use OnItemClickListener
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
When you click on a row a listener is fired. So you setOnClickListener
on the listview and use the annonymous inner class OnItemClickListener
.
You also override onItemClick
. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).
Using the position you get the item .
Edit : From your comments i assume you need to set the adapter o listview
So assuming your activity extends ListActivtiy
setListAdapter(adapter);
Or if your activity class extends Activity
ListView lv = (ListView) findViewById(R.id.listview1);
//initialize adapter
lv.setAdapter(adapter);
I used the properties plugin to solve this.
Properties are defined in the pom, and written out to a my.properties file, where they can then be accessed from your Java code.
In my case it is test code that needs to access this properties file, so in the pom the properties file is written to maven's testOutputDirectory:
<configuration>
<outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>
Use outputDirectory if you want properties to be accessible by your app code:
<configuration>
<outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>
For those looking for a fuller example (it took me a bit of fiddling to get this working as I didn't understand how naming of properties tags affects ability to retrieve them elsewhere in the pom file), my pom looks as follows:
<dependencies>
<dependency>
...
</dependency>
</dependencies>
<properties>
<app.env>${app.env}</app.env>
<app.port>${app.port}</app.port>
<app.domain>${app.domain}</app.domain>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
And on the command line:
mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901
So these properties can be accessed from the Java code:
java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
java.util.Properties properties = new Properties();
properties.load(inputStream);
appPort = properties.getProperty("app.port");
appDomain = properties.getProperty("app.domain");
You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
You need to follow these steps:
[1,3].inject([1,1,1,2,2,3]) do |memo,element|
memo.tap do |memo|
i = memo.find_index(e)
memo.delete_at(i) if i
end
end
You could do this:
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;
Reference:
That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.
I have a similar problem, I tested adding code and found some interesting results. With this code I add, I can deduce that depending on the "provider" to use, the firm can be different? (because the data included in the encryption is not always equal in all providers).
Conclusion.- Signature Decipher= ???(trash) + DigestInfo (if we know the value of "trash", the digital signatures will be equal)
Input data: This is the message being signed
Digest: 62b0a9ef15461c82766fb5bdaae9edbe4ac2e067
DigestInfo: 3021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
Signature Decipher: 1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff003021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
public class prueba {
/**
* @param args
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws NoSuchPaddingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*///
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
KeyPair keyPair = KeyPairGenerator.getInstance("RSA","BC").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey puKey = keyPair.getPublic();
String plaintext = "This is the message being signed";
// Hacer la firma
Signature instance = Signature.getInstance("SHA1withRSA","BC");
instance.initSign(privateKey);
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
// En dos partes primero hago un Hash
MessageDigest digest = MessageDigest.getInstance("SHA1", "BC");
byte[] hash = digest.digest((plaintext).getBytes());
// El digest es identico a openssl dgst -sha1 texto.txt
//MessageDigest sha1 = MessageDigest.getInstance("SHA1","BC");
//byte[] digest = sha1.digest((plaintext).getBytes());
AlgorithmIdentifier digestAlgorithm = new AlgorithmIdentifier(new
DERObjectIdentifier("1.3.14.3.2.26"), null);
// create the digest info
DigestInfo di = new DigestInfo(digestAlgorithm, hash);
byte[] digestInfo = di.getDEREncoded();
//Luego cifro el hash
Cipher cipher = Cipher.getInstance("RSA","BC");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digestInfo);
//byte[] cipherText = cipher.doFinal(digest2);
Cipher cipher2 = Cipher.getInstance("RSA","BC");
cipher2.init(Cipher.DECRYPT_MODE, puKey);
byte[] cipherText2 = cipher2.doFinal(signature);
System.out.println("Input data: " + plaintext);
System.out.println("Digest: " + bytes2String(hash));
System.out.println("Signature: " + bytes2String(signature));
System.out.println("Signature2: " + bytes2String(cipherText));
System.out.println("DigestInfo: " + bytes2String(digestInfo));
System.out.println("Signature Decipher: " + bytes2String(cipherText2));
}
Use String.substring(beginIndex, endIndex)
str.substring(0, str.length() - 2);
The substring begins at the specified beginIndex and extends to the character at index (endIndex - 1)
Centering content has so many avenues that it can't really be explored in a single answer. If you would like to explore them, CSS Zen Garden is an enjoyable-if-old resource exploring the many, many ways to layout content in a way even old browsers will tolerate.
The correct way, if you don't have any mitigating requirements, is to just apply margin: auto
to the sides, and a width
. If your page has no content that needs to go outside those margins, just apply it to the body:
body {
padding: 0;
margin: 15px auto;
width: 500px;
}
https://jsfiddle.net/b9chris/62wgq8nk/
So here we've got a 500px wide set of content centered at all* sizes. The padding 0 is to deal with some browsers that like to apply some default padding and throw us off a bit. In the example I do wrap the content in an article
tag to be nice to Screen Readers, Pocket, etc so for example the blind can jump past the nav you likely have (which should be in nav
) and straight to the content.
I say all* because below 500px this will mess up - we're not being Responsive. To get Responsive, you could just use Bootstrap etc, but building it yourself you use a Media Query like:
body {
padding: 0;
margin: 15px;
@media (min-width: 500px) {
margin: 15px auto;
width: 500px;
}
}
Note that this is SCSS/SASS syntax - if you're using plain CSS, it's inverted:
body {
padding: 0;
margin: 15px;
}
@media (min-width: 500px) {
body {
margin: 15px auto;
width: 500px;
}
}
https://jsfiddle.net/b9chris/62wgq8nk/6/
It's common however to want to center just one chunk of a page, so let's apply this to only the article tag in a final example.
body {
padding: 0;
margin: 0;
}
nav {
width: 100%;
box-sizing: border-box;
padding: 15px;
}
article {
margin: 15px;
@media (min-width: 500px) {
margin: 15px auto;
width: 500px;
}
}
https://jsfiddle.net/b9chris/62wgq8nk/17/
Note that this final example also uses CSS Flexbox in the nav, which is also one of the newer ways you could center things. So, that's fun.
But, there are special circumstances where you need to use other approaches to center content, and each of those is probably worth its own question (many of them already asked and answered here on this site).
//function to find vowel
const vowel = (str)=>{
//these are vowels we want to check for
const check = ['a','e','i','o','u'];
//keep track of vowels
var count = 0;
for(let char of str.toLowerCase())
{
//check if each character in string is in vowel array
if(check.includes(char)) count++;
}
return count;
}
console.log(vowel("hello there"));
How about this
for (int i = 0; i < str.length(); i++) {
System.out.println(str.substring(i, i + 1));
}
As matt burns says in his answer, you may need to enable CORS on the server where the problem images are hosted.
If the server is Apache, this can be done by adding the following snippet (from here) to either your VirtualHost config or an .htaccess
file:
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
...if adding it to a VirtualHost, you'll probably need to reload Apache's config too (eg. sudo service apache2 reload
if Apache's running on a Linux server)
Use sessions
On your search.jsp
Put your scard
in sessions using session.setAttribute("scard","scard")
//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.
And in your next page you retrieve it using session.getAttribute("scard")
UPDATE
<input type="text" value="<%=session.getAttribute("scard")%>"/>
There are three ways
1) This runs the GUI editor for the user environment variables. It does exactly what the OP wanted to do and does not prompt for administrative credentials.
rundll32.exe sysdm.cpl,EditEnvironmentVariables
(bonus: This works on Windows Vista to Windows 10 for desktops and Windows Server 2008 through Server 2016. It does not work on Windows NT, 2000, XP, and 2003. However, on the older systems you can use sysdm.cpl without the ",EditEnvironmentVariables" parameter and then navigate to the Advanced tab and then Environment Variables button.)
2) Use the SETX command from the command prompt. This is like the set command but updates the environment that's stored in the registry. Unfortunately, SETX is not as easy to use as the built in SET command. There's no way to list the variables for example. Thus it's impossible to do something such as appending a folder to the user's PATH variable. While SET will display the variables you don't know which ones are user vs. system variables and the PATH that's shown is a combination of both.
3) Use regedit and navigate to HKEY_CURRENT_USER\Environment
Keep in mind that changes to the user's environment does not immediately propagate to all processes currently running for that user. You can see this in a command prompt where your changes will not be visible if you use SET. For example
rem Add a user environment variable named stackoverflow that's set to "test"
setx stackoverflow test
set st
This should show all variables whose names start with the letters "st". If there are none then it displays "Environment variable st not defined
".
Exit the command prompt and start another. Try set st
again
and you'll see
stackoverflow=test
To delete the stackoverflow variable use
setx stackoverflow ""
It will respond with "SUCCESS: Specified value was saved.
" which looks strange given you want to delete the variable. However, if you start a new command prompt then set st
will show that there are no variables starting with the letters "st"
(correction - I discovered that setx stackoverflow ""
did not delete the variable. It's in the registry as an empty string. The SET
command though interprets it as though there is no variable. if not defined stackoverflow echo Not defined
says it's not defined.)
which git &> /dev/null || { echo >&2 "I require git but it's not installed. Aborting."; exit 1; }
echo "Git is installed."
That will echo "Git is installed" if it is, otherwise, it'll echo an error message. You can use this for scripts that use git
It's also customizable, so you can change "which git" to "which java" or something, and change the error message.
In order to use mod_rewrite you can type the following command in the terminal:
$ su
$ passwd **********
# a2enmod rewrite
Restart apache2 after
# service apache2 restart
# /etc/init.d/apache2 restart
or
# service apache2 restart
A pointer to a pointer is also called a handle. One usage for it is often when an object can be moved in memory or removed. One is often responsible to lock and unlock the usage of the object so it will not be moved when accessing it.
It's often used in memory restricted environment, ie the Palm OS.
Use f
string for getting this solved.
year=None
year_val= 'null' if year is None else str(year)
print(f'{year_val}')
null
function CurFocus()
{
$('.txtEmail').focus();
}
function pageLoad()
{
setTimeout(CurFocus(),3000);
}
window.onload = pageLoad;
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
Ubuntu 18.04 * Usage: /etc/init.d/cron {start|stop|status|restart|reload|force-reload}
This should suffice:
Environment.GetCommandLineArgs()[0];
You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging
Public Sub test(mdate As String)
Dim toDay As String
mdate = Round(CDbl(CDate(mdate)), 0)
toDay = Round(CDbl(Now()), 0)
Dim Aging as String
Aging = toDay - mdate
MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub
NB: Used CDate
for convert Date String to Valid Date
I am using this in Office 2007 :)
$('#some_select_box option:selected').remove();
In Python the definition of package is very simple. Like Java the hierarchical structure and the directory structure are the same. But you have to have __init__.py
in a package. I will explain the __init__.py
file with the example below:
package_x/
|-- __init__.py
|-- subPackage_a/
|------ __init__.py
|------ module_m1.py
|-- subPackage_b/
|------ __init__.py
|------ module_n1.py
|------ module_n2.py
|------ module_n3.py
__init__.py
can be empty, as long as it exists. It indicates that the directory should be regarded as a package. Of course, __init__.py
can also set the appropriate content.
If we add a function in module_n1:
def function_X():
print "function_X in module_n1"
return
After running:
>>>from package_x.subPackage_b.module_n1 import function_X
>>>function_X()
function_X in module_n1
Then we followed the hierarchy package and called module_n1 the function. We can use __init__.py
in subPackage_b like this:
__all__ = ['module_n2', 'module_n3']
After running:
>>>from package_x.subPackage_b import *
>>>module_n1.function_X()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named module_n1
Hence using * importing, module package is subject to __init__.py
content.
Just add a div around the container
so it looks like:
<div style="background: red;">
<div class="container marketing">
<h2 style="padding-top: 60px;"></h2>
</div>
</div>
I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:
$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
// just to use this `hasNext()` method to see
// if this is the last element
echo $each;
}
}
Its simple.. add this dependency in your project and create a button with 1. Any shape 2. Any color 3. Any border 4. With material effects
https://github.com/manojbhadane/QButton
<com.manojbhadane.QButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="OK"
app:qb_backgroundColor="@color/green"
app:qb_radius="100"
app:qb_strokeColor="@color/darkGreen"
app:qb_strokeWidth="5" />
for n in range(6,0,-1):
print n
# prints [6, 5, 4, 3, 2, 1]
I find out that, inside of your .css >if you set the display property of a div element to inline-block it fixes the problem. and margin will work as is expected.
gets()
is dangerous because it is possible for the user to crash the program by typing too much into the prompt. It can't detect the end of available memory, so if you allocate an amount of memory too small for the purpose, it can cause a seg fault and crash. Sometimes it seems very unlikely that a user will type 1000 letters into a prompt meant for a person's name, but as programmers, we need to make our programs bulletproof. (it may also be a security risk if a user can crash a system program by sending too much data).
fgets()
allows you to specify how many characters are taken out of the standard input buffer, so they don't overrun the variable.
Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);
If you use an absolute path such as ("/index.jsp"
), there is no difference.
If you use relative path, you must use HttpServletRequest.getRequestDispatcher()
. ServletContext.getRequestDispatcher()
doesn't allow it.
For example, if you receive your request on http://example.com/myapp/subdir
,
RequestDispatcher dispatcher =
request.getRequestDispatcher("index.jsp");
dispatcher.forward( request, response );
Will forward the request to the page http://example.com/myapp/subdir/index.jsp
.
In any case, you can't forward request to a resource outside of the context.
Awesomium makes it easy to use HTML UI in your C++ or .NET app
My previous answer is now outdated. These days you would be crazy not to look into using Electron for this. Many popular desktop apps have been developed on top of it.
This capitalizes this first letter and every letter following a space and lower cases any other letter.
public string CapitalizeFirstLetterAfterSpace(string input)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(input);
bool capitalizeNextLetter = true;
for(int pos = 0; pos < sb.Length; pos++)
{
if(capitalizeNextLetter)
{
sb[pos]=System.Char.ToUpper(sb[pos]);
capitalizeNextLetter = false;
}
else
{
sb[pos]=System.Char.ToLower(sb[pos]);
}
if(sb[pos]=' ')
{
capitalizeNextLetter=true;
}
}
}
For a method that works with both C and C++, you might want to consider using the standard library function strtol().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
The only thing which helps me on Windows 7 (x64): https://stackoverflow.com/a/29714359/2670121
Reinstall node and python with x32 versions.
I spent a lot of time with this error:
Failed to load c++ bson extension
and finally, when I installed module node-gyp
(for building native addons) and even installed windows SDK with visual studio - nodejs didn't recognize assembled module bson.node
as a module. After reinstalling the problem is gone.
Again, What does this error mean?
Actually, it's even not error. You still can use mongoose. But in this case, instead of fast native realization of bson
module, you got js-realization
, which is slower.
I saw many tips like: "edit path deep inside node_modules..." - which is totally useless, because it does not solve the problem, but just turned off the error messages.
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
Go to IIS -> Application Pool -> Advance Settings -> Enable 32-bit Applications
All the answers above, for some reason or another, did not work for me on SQL Server 2012. My situation was I accidently deleted all rows instead of just one row. After our DBA restored the table to dbo.foo_bak
, I used the below to restore. NOTE: This only works if the backup table (represented by dbo.foo_bak
) and the table that you are writing to (dbo.foo
) have the exact same column names.
This is what worked for me using a hybrid of a bunch of different answers:
USE [database_name];
GO
SET IDENTITY_INSERT dbo.foo ON;
GO
INSERT INTO [dbo].[foo]
([rown0]
,[row1]
,[row2]
,[row3]
,...
,[rown])
SELECT * FROM [dbo].[foo_bak];
GO
SET IDENTITY_INSERT dbo.foo OFF;
GO
This version of my answer is helpful if you have primary and foreign keys.
Sure you can:
https://<organization>.slack.com/messages/<channel>/
for example: https://tikal.slack.com/messages/general/ (of course that for accessing it, you must be part of the team)
I think that it's absolutely absurd to put ALL of your function definitions into the header file. Why? Because the header file is used as the PUBLIC interface to your class. It's the outside of the "black box".
When you need to look at a class to reference how to use it, you should look at the header file. The header file should give a list of what it can do (commented to describe the details of how to use each function), and it should include a list of the member variables. It SHOULD NOT include HOW each individual function is implemented, because that's a boat load of unnecessary information and only clutters the header file.
An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).
To print it as a date/time, you first need to decide which timezone to use. For example:
System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));
This will print the date/time in iso format: 2015-06-02T10:15:02.325
If you want a different format you can use a formatter:
LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);
I had the same issue and here is how I manage to pass through:
In your case you have addToCount()
which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"
in your function implementation you can receive the params like:
addToCount(paramContactID){
// the paramContactID contains the value you passed into the function when you called it
// you can do what you want to do with the paramContactID in here!
}
You'll need to loop through your array elements, create a new DOM node for each and append it to your object.
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}?
I'm developing an UWP application which connects to a MQTT broker in the LAN. I go a similar error.
MQTTnet.Exceptions.MqttCommunicationException: 'An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883'
ExtendedSocketException: An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883
Turned out that I forgot to give the app the correct capabilites ...
Well your onclick function works absolutely fine its your this line
window.external.values(a.value, b.value, c.value, d.value, e.value);
window.external is object and has no method name values
<html>
<head>
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
// window.external.values(a.value, b.value, c.value, d.value, e.value);
//use alert to check its working
alert("HELLO");
}
</script>
</head>
<body>
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
</body>
</html>
put .gitignore in your main catalog
git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push
If we are using apache commons logging wrapper on top of log4j, then we need to have both the jars available in classpath. Also, commons-logging.properties
and log4j.properties/xml
should be available in classpath.
We can also pass implementation class and log4j.properties
name as JAVA_OPTS
either using -Dorg.apache.commons.logging.Log=<logging implementation class name> -Dlog4j.configuration=<file:location of log4j.properties/xml file>
. Same can be done via setting JAVA_OPTS
in case of app/web server.
It will help to externalize properties which can be changed in deployment.
If you use android studio, this might be useful for you.
I had a similar problem and i solved it by changing the skd path from the default C:\Program Files (x86)\Android\android-studio\sdk to C:\Program Files (x86)\Android\android-sdk .
It seems the problem came from the compiler version (gradle sets it automatically to the highest one available in the sdk folder) which doesn't support this theme, and since android studio had only the api 7 in its sdk folder, it gave me this error.
For more information on how to change Android sdk path in Android Studio: Android Studio - How to Change Android SDK Path
IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.
What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML
I have found a way to use <base>
and anchor based links. You can use JavaScript to keep links like #contact
working as they have to. I used it in some parallax pages and it works for me.
<base href="http://www.mywebsite.com/templates/"><!--[if lte IE 6]></base><![endif]-->
...content...
<script>
var link='',pathname = window.location.href;
$('a').each(function(){
link = $(this).attr('href');
if(link[0]=="#"){
$(this).attr('href', pathname + link);
}
});
</script>
You should use at the end of the page
Many of us know that the Popular Method of Escaping Single Quotes is by Doubling them up easily like below.
PRINT 'It''s me, Arul.';
we are going to look on some other alternate ways of escaping the single quotes.
1.UNICODE Characters
39 is the UNICODE character of Single Quote. So we can use it like below.
PRINT 'Hi,it'+CHAR(39)+'s Arul.';
PRINT 'Helo,it'+NCHAR(39)+'s Arul.';
2.QUOTED_IDENTIFIER
Another simple and best alternate solution is to use QUOTED_IDENTIFIER. When QUOTED_IDENTIFIER is set to OFF, the strings can be enclosed in double quotes. In this scenario, we don’t need to escape single quotes. So,this way would be very helpful while using lot of string values with single quotes. It will be very much helpful while using so many lines of INSERT/UPDATE scripts where column values having single quotes.
SET QUOTED_IDENTIFIER OFF;
PRINT "It's Arul."
SET QUOTED_IDENTIFIER ON;
CONCLUSION
The above mentioned methods are applicable to both AZURE and On Premises .
In you keyup/down handler you just need to set the scrollTop
property of the div you want to scroll to make it scroll down (or up).
For example:
JSX:
<div ref="foo">{content}</div>
keyup/down handler:
this.refs.foo.getDOMNode().scrollTop += 10
If you do something similar to above, your div will scroll down 10 pixels (assuming the div is set to overflow auto
or scroll
in css, and your content is overflowing of course).
You will need to expand on this to find the offset of the element inside your scrolling div that you want to scroll the div down to, and then modify the scrollTop
to scroll far enough to show the element based on it's height.
Have a look at MDN's definitions of scrollTop, and offsetTop here:
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop
To define Optional
Protocol
in swift you should use @objc
keyword before Protocol
declaration and attribute
/method
declaration inside that protocol.
Below is a sample of Optional Property of a protocol.
@objc protocol Protocol {
@objc optional var name:String?
}
class MyClass: Protocol {
// No error
}
This works for PL/SQL:
select count(*), id,address from table group by id,address having count(*)<2
I think you are directly trying to access API link, this won't work because API is secured using IAM role and you must provide AWS authentication i.e Access key and Secret key.
Use the Postman Chrome extension to test your API: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html
Check out this link to migrate from Angular 5.2 to 6. https://update.angular.io/
That's not a jQuery function - it's the regular Array.join function.
It converts an array to a string, putting the argument between each element.
In case of .css method in jQuery for !important rule will not apply.
In this case we should use .attr function.
For Example:
If you want to add style as below:
<div id='voltaic_holder' style='position:absolute;top:-75px !important'>
You should use:
$("#voltaic_holder").attr("style", "position:absolute;top:-75px !important");
Hope it helps some one.
In short, no, there is no way to override a class variable.
You do not override class variables in Java you hide them. Overriding is for instance methods. Hiding is different from overriding.
In the example you've given, by declaring the class variable with the name 'me' in class Son you hide the class variable it would have inherited from its superclass Dad with the same name 'me'. Hiding a variable in this way does not affect the value of the class variable 'me' in the superclass Dad.
For the second part of your question, of how to make it print "son", I'd set the value via the constructor. Although the code below departs from your original question quite a lot, I would write it something like this;
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
The JLS gives a lot more detail on hiding in section 8.3 - Field Declarations
Can't you use JOIN like this one?
SELECT
a.x , b.y, b.z
FROM a
LEFT OUTER JOIN b ON b.v = a.v
(I don't know Oracle Syntax. So I wrote SQL syntax)
knowTypeList parameter let serialize with DataContractSerializer several known types:
private static void WriteObject(
string fileName, IEnumerable<Vehichle> reflectedInstances, List<Type> knownTypeList)
{
using (FileStream writer = new FileStream(fileName, FileMode.Append))
{
foreach (var item in reflectedInstances)
{
var serializer = new DataContractSerializer(typeof(Vehichle), knownTypeList);
serializer.WriteObject(writer, item);
}
}
}
Short answer: no (easy?) way, but you can do something that serves your purpose.
I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:
spawn('bash', ['-i'], {
cwd: new_cwd,
env: new_env,
stdio: 'inherit'
});
After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:
However, for me, that differences are desirable.
You can also use this syntax: (in column D to concatenate A, B, and C)
=A2 & " """ & B2 & """ " & C2
Samuel Liew is right. sometimes jquery conflict with the other jqueries. to solve this problem you need to put them in such a order that they may not conflict with each other. do one thing: open your application in google chrome and inspect bottom right corner with red marked errors. which kind of error that is?
With async actions (timers, ajax) you can override the property isDefaultPrevented
like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
Now the class is this
<img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
SHOW CREATE TABLE bar;
you will get a create statement for that table, edit the table name, or anything else you like, and then execute it.
This will allow you to copy the indexes and also manually tweak the table creation.
You can also run the query within a program.
cat file2 >> file1
The >>
operator appends the output to the named file or creates the named file if it does not exist.
cat file1 file2 > file3
This concatenates two or more files to one. You can have as many source files as you need. For example,
cat *.txt >> newfile.txt
Update 20130902
In the comments eumiro suggests "don't try cat file1 file2 > file1
." The reason this might not result in the expected outcome is that the file receiving the redirect is prepared before the command to the left of the >
is executed. In this case, first file1
is truncated to zero length and opened for output, then the cat
command attempts to concatenate the now zero-length file plus the contents of file2
into file1
. The result is that the original contents of file1
are lost and in its place is a copy of file2
which probably isn't what was expected.
Update 20160919
In the comments tpartee suggests linking to backing information/sources. For an authoritative reference, I direct the kind reader to the sh man page at linuxcommand.org which states:
Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell.
While that does tell the reader what they need to know it is easy to miss if you aren't looking for it and parsing the statement word by word. The most important word here being 'before'. The redirection is completed (or fails) before the command is executed.
In the example case of cat file1 file2 > file1
the shell performs the redirection first so that the I/O handles are in place in the environment in which the command will be executed before it is executed.
A friendlier version in which the redirection precedence is covered at length can be found at Ian Allen's web site in the form of Linux courseware. His I/O Redirection Notes page has much to say on the topic, including the observation that redirection works even without a command. Passing this to the shell:
$ >out
...creates an empty file named out. The shell first sets up the I/O redirection, then looks for a command, finds none, and completes the operation.
When you use the exec format for a command (e.g. CMD ["grunt"]
, a JSON array with double quotes) it will be executed without a shell. This means that most environment variables will not be present.
If you specify your command as a regular string (e.g. CMD grunt
) then the string after CMD
will be executed with /bin/sh -c
.
More info on this is available in the CMD section of the Dockerfile reference.
Bash script for adding cron job without the interactive editor. Below code helps to add a cronjob using linux files.
#!/bin/bash
cron_path=/var/spool/cron/crontabs/root
#cron job to run every 10 min.
echo "*/10 * * * * command to be executed" >> $cron_path
#cron job to run every 1 hour.
echo "0 */1 * * * command to be executed" >> $cron_path
You could apply both background-color and border to make it look like 2 colors.
div.A { width: 50px; background-color: #9c9e9f; border-right: 50px solid #f6f6f6; }
The border should have the same size as the width.
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.
To explain the differences as relevant to your posted example:
a. When you use RegisterStartupScript
, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.
Here is the rendered source of the page when you invoke the RegisterStartupScript
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<div> <span id="lblDisplayDate">Label</span>
<br />
<input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
<br />
<input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
</div>
<!-- Note this part -->
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
lbl.style.color = 'red';
</script>
</form>
<!-- Note this part -->
</body>
</html>
b. When you use RegisterClientScriptBlock
, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.
Here is the rendered source of the page when you invoke the RegisterClientScriptBlock
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
// Error is thrown in the next line because lbl is null.
lbl.style.color = 'green';
Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).
Edit after comments:
For instance, the following function would work:
protected void btnPostBack2_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function ChangeColor() {");
sb.Append("var lbl = document.getElementById('lblDisplayDate');");
sb.Append("lbl.style.color='green';");
sb.Append("}</script>");
//Render the function definition.
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
//Render the function invocation.
string funcCall = "<script language='javascript'>ChangeColor();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
In order to check the maximum allowed connections, you can run the following query:
SHOW VARIABLES LIKE "max_connections";
To check the number of active connections, you can run the following query:
SHOW VARIABLES LIKE "max_used_connections";
Hope it helps.
JackDB, a database client in your web browser, makes this really easy. Especially if you're on Heroku.
It lets you connect to remote databases and run SQL queries on them.
Source
(source: jackdb.com)
Once your DB is connected, you can run a query and export to CSV or TXT (see bottom right).
Note: I'm in no way affiliated with JackDB. I currently use their free services and think it's a great product.
You say "Java" but "not Java EE". Do you mean you are using JSP and/or servlets but not a full Java EE stack? If that's the case, then you should still have request.getParameter() available to you.
If you mean you are writing Java but you are not writing JSPs nor servlets, or that you're just using Java as your reference point but you're on some other platform that doesn't have built-in parameter parsing ... Wow, that just sounds like an unlikely question, but if so, the principle would be:
xparm=0
word=""
loop
get next char
if no char
exit loop
if char=='='
param_name[xparm]=word
word=""
else if char=='&'
param_value[xparm]=word
word=""
xparm=xparm+1
else if char=='%'
read next two chars
word=word+interpret the chars as hex digits to make a byte
else
word=word+char
(I could write Java code but that would be pointless, because if you have Java available, you can just use request.getParameters.)
Top can be compiled from sources or downloaded from sunfreeware.com. As previously posted, vmstat is available (I believe it's in the core install?).
If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.
Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
You can use position:absolute;
to absolutely position an element within a parent div.
When using position:absolute;
the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.
To make the content div positioned, all position
values that aren't static will work, but relative
is the easiest since it doesn't change the divs positioning by itself.
So add position:relative;
to the content div, remove the float from the button and add the following css to the button:
position: absolute;
right: 0;
bottom: 0;
i'd suggest shorter and faster approach:
printf("%.2f", ((signed long)(fVal * 100) * 0.01f));
this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.
I have a three column table with just over 6 Billion rows in SQL Server 2008 R2.
We query it every day to create minute-by-minute system analysis charts for our customers. I have not noticed any database performance hits (though the fact that it grows ~1 GB every day does make managing backups a bit more involved than I would like).
Update July 2016
We made it to ~24.5 billion rows before backups became large enough for us to decide to truncate records older than two years (~700 GB stored in multiple backups, including on expensive tapes). It's worth noting that performance was not a significant motivator in this decision (i.e., it was still working great).
For anyone who finds themselves trying to delete 20 billion rows from SQL Server, I highly recommend this article. Relevant code in case the link dies (read the article for a full explanation):
ALTER DATABASE DeleteRecord SET RECOVERY SIMPLE;
GO
BEGIN TRY
BEGIN TRANSACTION
-- Bulk logged
SELECT *
INTO dbo.bigtable_intermediate
FROM dbo.bigtable
WHERE Id % 2 = 0;
-- minimal logged because DDL-Operation
TRUNCATE TABLE dbo.bigtable;
-- Bulk logged because target table is exclusivly locked!
SET IDENTITY_INSERT dbo.bigTable ON;
INSERT INTO dbo.bigtable WITH (TABLOCK) (Id, c1, c2, c3)
SELECT Id, c1, c2, c3 FROM dbo.bigtable_intermediate ORDER BY Id;
SET IDENTITY_INSERT dbo.bigtable OFF;
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
ALTER DATABASE DeleteRecord SET RECOVERY FULL;
GO
Update November 2016
If you plan on storing this much data in a single table: don't. I highly recommend you consider table partitioning (either manually or with the built-in features if you're running Enterprise edition). This makes dropping old data as easy as truncating a table once a (week/month/etc.). If you don't have Enterprise (which we don't), you can simply write a script which runs once a month, drops tables older than 2 years, creates next month's table, and regenerates a dynamic view that joins all of the partition tables together for easy querying. Obviously "once a month" and "older than 2 years" should be defined by you based on what makes sense for your use-case. Deleting directly from a table with tens of billions of rows of data will a) take a HUGE amount of time and b) fill up the transaction log hundreds or thousands of times over.
It's not easily supported. Here's an article with instructions on how to pass EventArgs as command parameters.
You might want to look into using MVVMLight - it supports EventArgs in command directly; your situation would look something like this:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Navigated">
<cmd:EventToCommand Command="{Binding NavigatedEvent}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
If a computer can run it, a suitably motivated human can reverse-engineer it.
X.each_with_index do |item, index|
puts "current_index: #{index}"
end
There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):
Run man tcpdump | less -Ip examples
to see some examples
Here’s a tcpdump filter for HTTP GET (GET
= 0x47
, 0x45
, 0x54
, 0x20
):
sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
Here’s a tcpdump filter for HTTP POST (POST
= 0x50
, 0x4f
, 0x53
, 0x54
):
sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
Monitor HTTP traffic including request and response headers and message body (source):
tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).
Just give the AlertDialog this theme
<style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="android:windowMinWidthMajor">90%</item>
<item name="android:windowMinWidthMinor">90%</item>
</style>
Some of it is native, the rest is available through libraries.
For example Datejs is a good international date library.
For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).
You likely have other files (such as the default
configuration) located in /etc/nginx/sites-enabled
that needs to be removed.
This issue is caused by a repeat of the default_server
parameter supplied to one or more listen
directives in your files. You'll likely find this conflicting directive reads something similar to:
listen 80 default_server;
As the nginx core module documentation for listen
states:
The
default_server
parameter, if present, will cause the server to become the default server for the specifiedaddress:port
pair. If none of the directives have thedefault_server
parameter then the first server with theaddress:port
pair will be the default server for this pair.
This means that there must be another file or server
block defined in your configuration with default_server
set for port 80. nginx is encountering that first before your mysite.com
file so try removing or adjusting that other configuration.
If you are struggling to find where these directives and parameters are set, try a search like so:
grep -R default_server /etc/nginx
A faster way to do this is by right clicking the refresh icon beside the address bar and choosing Empty Cache and Hard reload
Just make sure Chrome's dev tools is open. (Press F12) By the way... This trick only works on Chrome for Windows, Ubuntu, and Mac OS
Finally, i solved the problem by using following way, in which the position of the spinner can be get by its string
private int getPostiton(String locationid,Cursor cursor)
{
int i;
cursor.moveToFirst();
for(i=0;i< cursor.getCount()-1;i++)
{
String locationVal = cursor.getString(cursor.getColumnIndex(RoadMoveDataBase.LT_LOCATION));
if(locationVal.equals(locationid))
{
position = i+1;
break;
}
else
{
position = 0;
}
cursor.moveToNext();
}
Calling the method
Spinner location2 = (Spinner)findViewById(R.id.spinner1);
int location2id = getPostiton(cursor.getString(3),cursor);
location2.setSelection(location2id);
I hope it will help for some one..
Seems like views have own mechanics for tint management, so better will be put tint list:
ViewCompat.setBackgroundTintList(
editText,
ColorStateList.valueOf(errorColor));
I havent tried this scenario yet - I was scared off by the (unanswered) comments below the GA announcement blog post:
I'll be staying on VS15 for a while ...
Thank @Ironman for his complete answer, however I should add my solution according to what I've experienced facing this issue.
In build.gradle (Module: app):
compile 'com.android.support:multidex:1.0.1'
...
dexOptions {
javaMaxHeapSize "4g"
}
...
defaultConfig {
multiDexEnabled true
}
Also, put the following in gradle.properties file:
org.gradle.jvmargs=-Xmx4096m -XX\:MaxPermSize\=512m -XX\:+HeapDumpOnOutOfMemoryError -Dfile.encoding\=UTF-8
I should mention, these numbers are for my laptop config (MacBook Pro with 16 GB RAM) therefore please edit them as your config.
This is how i changed placeholder arrow color, the 2 classes are for dropdown open and dropdown closed, you need to change the #fff to the color you want:
.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
border-color: transparent transparent #fff transparent !important;
}
.select2-container--default .select2-selection--single .select2-selection__arrow b {
border-color: #fff transparent transparent transparent !important;
}
i've searched google a lot and find the best suited project is the swipmenulistview https://github.com/baoyongzhang/SwipeMenuListView on github.
You have to use the SSH version, not HTTPS. When you clone from a repository, copy the link with the SSH version, because SSH is easy to use and solves all problems with access. You can set the access for every SSH you input into your account (like push, pull, clone, etc...)
Here is a link, which says why we need SSH and how to use it: step by step
I found a way to automate running the clean before you debug your code. (Warning, this runs everytime you hit the button, even for hot restart)
First, find the Run > Edit Configurations Menu
Click the External tool '+' icon under Before launch: External tool, Activate tool window.
This function will print variable name with its value:
import inspect
def print_this(var):
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
print(str([k for k, v in callers_local_vars if v is var][0])+': '+str(var))
***Input & Function call:*** my_var = 10 print_this(my_var) ***Output**:* my_var: 10
Here's an example on how to achieve this:
<Grid DockPanel.Dock="Right"
HorizontalAlignment="Right">
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Right"
VerticalAlignment="Center">
<Button x:Name="MinimizeButton"
KeyboardNavigation.IsTabStop="False"
Click="MinimizeWindow"
Style="{StaticResource MinimizeButton}"
Template="{StaticResource MinimizeButtonControlTemplate}" />
<Button x:Name="MaximizeButton"
KeyboardNavigation.IsTabStop="False"
Click="MaximizeClick"
Style="{DynamicResource MaximizeButton}"
Template="{DynamicResource MaximizeButtonControlTemplate}" />
<Button x:Name="CloseButton"
KeyboardNavigation.IsTabStop="False"
Command="{Binding ApplicationCommands.Close}"
Style="{DynamicResource CloseButton}"
Template="{DynamicResource CloseButtonControlTemplate}"/>
</StackPanel>
</Grid>
</DockPanel>
Handle Click Events in the code-behind.
For MouseDown -
App.Current.MainWindow.DragMove();
For Minimize Button -
App.Current.MainWindow.WindowState = WindowState.Minimized;
For DoubleClick and MaximizeClick
if (App.Current.MainWindow.WindowState == WindowState.Maximized)
{
App.Current.MainWindow.WindowState = WindowState.Normal;
}
else if (App.Current.MainWindow.WindowState == WindowState.Normal)
{
App.Current.MainWindow.WindowState = WindowState.Maximized;
}
As it was mentioned by Davos you can use the IDLEX
It happens that I'm using Linux version and from all extensions I needed only LineNumbers. So I've downloaded IDLEX archive, took LineNumbers.py from it, copied it to Python's lib folder ( in my case its /usr/lib/python3.5/idlelib ) and added following lines to configuration file in my home folder which is ~/.idlerc/config-extensions.cfg:
[LineNumbers]
enable = 1
enable_shell = 0
visible = True
[LineNumbers_cfgBindings]
linenumbers-show =
In my case it helped.
main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.livewallpaper.profileview.loginact.Main2Activity">
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:text="Title"
android:gravity="center"
android:layout_height="0dp" />
<LinearLayout
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
<EditText
android:hint="enter here"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:layout_weight="1"
android:text="signup for App"
android:gravity="bottom|center_horizontal"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
Use this in manifest
file
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize"/>
Now the most important part!
Use theme like this in either Activity
or Application
tag.
android:theme="@style/AppTheme"
And the theme tooks like this
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="windowActionModeOverlay">true</item>
</style>
So I was missing the theme. Which made me frustrated all day.
Scenario:
Your domain: mydomain.com
Domain you wish to send to: theirdomain.com
1. Determine the mail server you're sending to. Open a CMD prompt Type
NSLOOKUP
set q=mx
theirdomain.com
Response:
Non-authoritative answer:
theirdomain.com MX preference = 50, mail exchanger = mail.theirdomain.com
Nslookup_big
EDIT Be sure to type exit to terminate NSLOOKUP.
2. Connect to their mail server
SMTP communicates over port 25. We will now try to use TELNET to connect to their mail server "mail.theirdomain.com"
Open a CMD prompt
TELNET MAIL.THEIRDOMAIN.COM 25
You should see something like this as a response:
220 mx.google.com ESMTP 6si6253627yxg.6
Be aware that different servers will come up with different greetings but you should get SOMETHING. If nothing comes up at this point there are 2 possible problems. Port 25 is being blocked at your firewall, or their server is not responding. Try a different domain, if that works then it's not you.
3. Send an Email
Now, use simple SMTP commands to send a test email. This is very important, you CANNOT use the backspace key, it will work onscreen but not be interpreted correctly. You have to type these commands perfectly.
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
So, what does that all mean? EHLO - introduce yourself to the mail server HELO can also be used but EHLO tells the server to use the extended command set (not that we're using that).
MAIL FROM - who's sending the email. Make sure to place this is the greater than/less than brackets as many email servers will require this (Postini).
RCPT TO - who you're sending it to. Again you need to use the brackets. See Step #4 on how to test relaying mail!
DATA - tells the SMTP server that what follows is the body of your email. Make sure to hit "Enter" at the end.
. - the period alone on the line tells the SMTP server you're all done with the data portion and it's clear to send the email.
quit - exits the TELNET session.
4. Test SMTP relay Testing SMTP relay is very easy, and simply requires a small change to the above commands. See below:
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
See the difference? On the RCPT TO line, we're sending to a domain that is not controlled by the SMTP server we're sending to. You will get an immediate error is SMTP relay is turned off. If you're able to continue and send an email, then relay is allowed by that server.
Align the text area box to the label, not the label to the text area,
label {
width: 180px;
display: inline-block;
}
textarea{
vertical-align: middle;
}
<label for="myfield">Label text</label><textarea id="myfield" rows="5" cols="30"></textarea>
The best option (for my of course) is do it yourserfl. It means you can modify programattly all parts of the SOAP message
Binding binding = prov.getBinding();
List<Handler> handlerChain = binding.getHandlerChain();
handlerChain.add( new ModifyMessageHandler() );
binding.setHandlerChain( handlerChain );
And the ModifyMessageHandler source could be
@Override
public boolean handleMessage( SOAPMessageContext context )
{
SOAPMessage msg = context.getMessage();
try
{
SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
SOAPHeader header = envelope.addHeader();
SOAPElement ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
ele.addTextNode( "value_of_header" );
ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
ele.addTextNode( "value_of_header" );
ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
ele.addTextNode( "value_of_header" );
...
I hope this helps you
Conceptual Schema - covers entities and relationships. Should be created first. Contrary to some of the other answers; tables are not defined here. For example a 'many to many' table is not included in a conceptual data model but is defined as a 'many to many' relationship between entities.
Logical Schema - Covers tables, attributes, keys, mandatory role constraints, and referential integrity with no regards to the physical implementation. Things like indexes are not defined, attribute types should be kept logical, e.g. text instead of varchar2. Should be created based on the conceptual schema.
36, and the GUID will only use 0-9A-F (hexidecimal!).
12345678-1234-1234-1234-123456789012
That's 36 characters in any GUID--they are of constant length. You can read a bit more about the intricacies of GUIDs here.
You will need two more in length if you want to store the braces.
Note: 36 is the string length with the dashes in between. They are actually 16-byte numbers.
To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.
To learn more about the grid and the columns / gutter widths, please also read:
In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px.
When setting @grid-columns:3;
and setting @grid-gutter-width:15px;
in variables.less you will get:
15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px
when you see this problem always put your autocomplete function in keyup function and ensure you have added the libraries
$( "#searcharea" ).keyup(function(){
$( "#searcharea" ).autocomplete({
source: "suggestions.php"
});
});
I think you need to use MaterialApp
widget and use theme
and set primarySwatch
with color that you want. look like below code,
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
if (System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
{
// Use a try block to catch IOExceptions, to
// handle the case of the file already being
// opened by another process.
try
{
System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
python 3 https://docs.python.org/3.5/howto/sorting.html#the-old-way-using-the-cmp-parameter
from functools import cmp_to_key
def custom_compare(x, y):
# custom comparsion of x[0], x[1] with y[0], y[1]
return 0
sorted(entries, key=lambda e: (cmp_to_key(custom_compare)(e[0]), e[1]))
1.
function setColor(e) {
var target = e.target,
count = +target.dataset.count;
target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
target.dataset.count = count === 1 ? 0 : 1;
/*
() : ? - this is conditional (ternary) operator - equals
if (count === 1) {
target.style.backgroundColor = "#7FFF00";
target.dataset.count = 0;
} else {
target.style.backgroundColor = "#FFFFFF";
target.dataset.count = 1;
}
target.dataset - return all "data attributes" for current element,
in the form of object,
and you don't need use global variable in order to save the state 0 or 1
*/
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)";
data-count="1"
/>
2.
function setColor(e) {
var target = e.target,
status = e.target.classList.contains('active');
e.target.classList.add(status ? 'inactive' : 'active');
e.target.classList.remove(status ? 'active' : 'inactive');
}
.active {
background-color: #7FFF00;
}
.inactive {
background-color: #FFFFFF;
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)"
/>
I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...
There is a line of code to uncommment in order to have it return JSON.
With Flexbox you can easily horizontally (and vertically) center floated children inside a div.
So if you have simple markup like so:
<div class="wpr">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
with CSS:
.wpr
{
width: 400px;
height: 100px;
background: pink;
padding: 10px 30px;
}
.wpr span
{
width: 50px;
height: 50px;
background: green;
float: left; /* **children floated left** */
margin: 0 5px;
}
(This is the (expected - and undesirable) RESULT)
Now add the following rules to the wrapper:
display: flex;
justify-content: center; /* align horizontal */
and the floated children get aligned center (DEMO)
Just for fun, to get vertical alignment as well just add:
align-items: center; /* align vertical */
Insert a 3rd column and in Cell C2
paste this formula
=IF(SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2))>1,0,1)
and copy it down. Now create your pivot based on 1st and 3rd column. See snapshot
I'd like to add another reason that "catalina.sh" won't be able to connect to port 8005, apart from a firewall or a change in "server.xml": It takes Tomcat time to start listening on port 8005.
It's easy to reproduce this scenario If you start Tomcat and try to stop it immediately. Wait a few minutes and you'll see that the problem disappears because the port has opened.
One way is to add it by yourself! How? By merging kwargs
with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:
import sys
def myfunc(**kwargs):
args = {'country':'England','town':'London',
'currency':'Pound', 'language':'English'}
diff = set(kwargs.keys()) - set(args.keys())
if diff:
print("Invalid args:",tuple(diff),file=sys.stderr)
return
args.update(kwargs)
print(args)
The defaults are set in the dictionary args
, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args
with kwargs
which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args
as our argument dictionary and have no further need of kwargs
.
This works in MariaDB:
SELECT Req_ID, (R1+R2+R3+R4+R5)/5 AS Average
FROM Request
GROUP BY Req_ID;
I was able to fix this by doing two things, though you may not have to do step 1.
copy from cygwin ssh.exe and all cyg*.dll into Git's bin directory (this may not be necessary but it is a step I took but this alone did not fix things)
follow the steps from: http://zylstra.wordpress.com/2008/08/29/overcome-herokus-permission-denied-publickey-problem/
I added some details to my ~/.ssh/config file:
Host heroku.com
Hostname heroku.com
Port 22
IdentitiesOnly yes
IdentityFile ~/.ssh/id_heroku
TCPKeepAlive yes
User brandon
I had to use User as my email address for heroku.com Note: this means you need to create a key, I followed this to create the key and when it prompts for the name of the key, be sure to specify id_heroku http://help.github.com/win-set-up-git/
If you have access to the script console (Manage Jenkins -> Script Console), then you can do this following:
Jenkins.instance.getItemByFullName("YourJobName").updateNextBuildNumber(45)
To answer your question directly: no. There is no more simple way to get a consistent look and feel across all modern browsers, without repeating the class on the column. (Although, see below re: nth-child.)
The following is the most efficient way to do this.
HTML:
<table class="products">
<tr>
<td>...</td>
<td>...</td>
<td class="price">10.00</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td class="price">11.45</td>
<td>...</td>
<td>...</td>
</tr>
</table>
CSS:
table.products td.price {
text-align: right;
}
nth-child
is now supported by 96% of the browsers, what is below is now 11 years old!
Why you shouldn't use nth-child:
The CSS3 pseudo-selector, nth-child, would be perfect for this -- and much more efficient -- but it is impractical for use on the actual web as it exists today. It is not supported by several major modern browsers, including all IE's from 6-8. Unfortunately, this means that nth-child is unsupported in a significant share (at least 40%) of browsers today.
So, nth-child is awesome, but if you want a consistent look and feel, it's just not feasible to use.
So to fix this properly, I did what others here did and used css to get hide the horizontal toolbar:
.name {
max-width: 100%;
overflow-x: hidden;
}
Then in js, I created an event listener to look for scrolling, and counteracted the users attempted horizontal scroll.
var scrollEventHandler = function()
{
window.scroll(0, window.pageYOffset)
}
window.addEventListener("scroll", scrollEventHandler, false);
I saw somebody do something similar, but apparently that didn't work. This however is working perfectly fine for me.
I find the answer. 1/First put in the presets, i have this example "Output format MPEG2 DVD HQ"
-vcodec mpeg2video -vstats_file MFRfile.txt -r 29.97 -s 352x480 -aspect 4:3 -b 4000k -mbd rd -trellis -mv0 -cmp 2 -subcmp 2 -acodec mp2 -ab 192k -ar 48000 -ac 2
If you want a report includes the commands -vstats_file MFRfile.txt into the presets like the example. this can make a report which it's ubicadet in the folder source of your file Source. you can put any name if you want , i solved my problem "i write many times in this forum" reading a complete .docx about mpeg properties. finally i can do my progress bar reading this txt file generated.
Regards.
This will replace consecutive spaces with one space (but not tab).
tr -s '[:blank:]'
This will replace consecutive spaces with a tab.
tr -s '[:blank:]' '\t'
It's even easier than everything suggested above. Data attributes in MVC which include dashes (-) are catered for with the use of underscore (_).
<%= Html.ActionLink("« Previous", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new { @class = "prev", data_details = "Some Details" })%>
I see JohnnyO already mentioned this.
DisplayName
sets the DisplayName
in the model metadata. For example:
[DisplayName("foo")]
public string MyProperty { get; set; }
and if you use in your view the following:
@Html.LabelFor(x => x.MyProperty)
it would generate:
<label for="MyProperty">foo</label>
Display
does the same, but also allows you to set other metadata properties such as Name, Description, ...
Brad Wilson has a nice blog post covering those attributes.
For any one having this issue with Flurry framework. This is what fixed my issue. For me the issue was that i had imported the following files but never used them. "libFlurryTVOS_9.2.3" "libFlurryWatch_9.2.3"
So all I had to do was go to project target settings and remove these 2 files from the "Linked framework and libraries" section and the problem was solved.
Here is my swift solution as a UIView extension. It could be considered as a simulation of a UIActivityIndicator behaviour on any UIImageView.
import UIKit
extension UIView
{
/**
Starts rotating the view around Z axis.
@param duration Duration of one full 360 degrees rotation. One second is default.
@param repeatCount How many times the spin should be done. If not provided, the view will spin forever.
@param clockwise Direction of the rotation. Default is clockwise (true).
*/
func startZRotation(duration duration: CFTimeInterval = 1, repeatCount: Float = Float.infinity, clockwise: Bool = true)
{
if self.layer.animationForKey("transform.rotation.z") != nil {
return
}
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
let direction = clockwise ? 1.0 : -1.0
animation.toValue = NSNumber(double: M_PI * 2 * direction)
animation.duration = duration
animation.cumulative = true
animation.repeatCount = repeatCount
self.layer.addAnimation(animation, forKey:"transform.rotation.z")
}
/// Stop rotating the view around Z axis.
func stopZRotation()
{
self.layer.removeAnimationForKey("transform.rotation.z")
}
}
you can also highlight the spaces (replacing the spaces with a block):
:%s/ /¦/g
(before writing undo it)
you can use directly (blur) event in input tag.
<div>
<input [value] = "" (blur) = "result = $event.target.value" placeholder="Type Something">
{{result}}
</div>
and you will get output in "result"
If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8"
encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))
If the only characters to consider are letters then you can do:
select X from myTable where upper(X) = lower(X)
But of course that won't filter out other characters, just letters.
Just adding an example that worked fine for me:
$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg
In case of :
<?xml version="1.0" encoding="iso-8859-1"?>
<info xmlns="http://namespaces.default" xmlns:ns2="http://namespaces.ns2" >
<id> 954 </id>
<idboss> 954 </idboss>
<name> Fausto </name>
<sorname> Anonimo </sorname>
<phone> 040000000 </phone>
<fax> 040000001 </fax>
</info>
Query :
Select *
from xmltable(xmlnamespaces(default 'http://namespaces.default'
'http://namespaces.ns2' as "ns",
),
'/info'
passing xmltype.createxml(xml)
columns id varchar2(10) path '/id',
idboss varchar2(500) path '/idboss',
etc....
) nice_xml_table
While you unfortunately cannot convert an existing member function pointer to a plain function pointer, you can create an adapter function template in a fairly straightforward way that wraps a member function pointer known at compile-time in a normal function like this:
template <class Type>
struct member_function;
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...)>
{
template <Ret(Type::*Func)(Args...)>
static Ret adapter(Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
template <class Type, class Ret, class... Args>
struct member_function<Ret(Type::*)(Args...) const>
{
template <Ret(Type::*Func)(Args...) const>
static Ret adapter(const Type &obj, Args&&... args)
{
return (obj.*Func)(std::forward<Args>(args)...);
}
};
int (*func)(A&) = &member_function<decltype(&A::f)>::adapter<&A::f>;
Note that in order to call the member function, an instance of A
must be provided.
Make it a block first, then float left to stop pushing the next block in to a new line.
#report-upload-form label {
padding-left:26px;
width:125px;
text-transform: uppercase;
display:block;
float:left
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("Enter Key Pressed");
}
}
This allows you to choose the specific Key you want, without finding the char value of the key.
About the server can deliver to the clients the root cert or not, extracted from the RFC-5246 'The Transport Layer Security (TLS) Protocol Version 1.2' doc it says:
certificate_list
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it. Because certificate validation requires that root keys be distributed independently, the self-signed certificate that specifies the root certificate authority MAY be omitted from the chain, under the
assumption that the remote end must already possess it in order to validate it in any case.
About the term 'MAY', extracted from the RFC-2119 "Best Current Practice" says:
5.MAY
This word, or the adjective "OPTIONAL", mean that an item is truly optional. One vendor may choose to include the item because a
particular marketplace requires it or because the vendor feels that
it enhances the product while another vendor may omit the same item.
An implementation which does not include a particular option MUST be
prepared to interoperate with another implementation which does
include the option, though perhaps with reduced functionality. In the same vein an implementation which does include a particular option
MUST be prepared to interoperate with another implementation which
does not include the option (except, of course, for the feature the
option provides.)
In conclusion, the root may be at the certification path delivered by the server in the handshake.
A practical use.
Think about, not in navigator user terms, but on a transfer tool at a server in a militarized zone with limited internet access.
The server, playing the client role at the transfer, receives all the certs path from the server.
All the certs in the chain should be checked to be trusted, root included.
The only way to check this is the root be included at the certs path in transfer time, being matched against a previously declared as 'trusted' local copy of them.
You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app - say 20000-21000, and CATCH EXCEPTIONS. That is how you will know if a port is unusable (used by another process, in other words) on your computer.
However, in your case, you shouldn't have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails.
Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers - only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data.
I presume you will be using UDP for this?
I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using BigDecimal
class .Here we can avoid extra steps which are required to get the final value if we use DecimalFormat("0.00")
or using Math.round(a * 100) / 100
.
import java.math.BigDecimal;
public class RoundingNumbers {
public static void main(String args[]){
double number = 123.13698;
int decimalsToConsider = 2;
BigDecimal bigDecimal = new BigDecimal(number);
BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with setting scale = "+roundedWithScale);
bigDecimal = new BigDecimal(number);
BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);
}
}
This program would give us below output
Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14
It doesn't. Somewhere in your print stylesheet, you must have this section of code:
a[href]::after {
content: " (" attr(href) ")"
}
The only other possibility is you have an extension doing it for you.
What does $rootScope.$broadcast do?
It broadcasts the message to respective listeners all over the angular app, a very powerful means to transfer messages to scopes at different hierarchical level(be it parent , child or siblings)
Similarly, we have $rootScope.$emit, the only difference is the former is also caught by $scope.$on while the latter is caught by only $rootScope.$on .
refer for examples :- http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
Look for Windows Installer XML (WiX)
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
I wanted to keep a database on my machine, but also have a data on my external hard drive, and switch between using the two.
If you are on a Mac, and installed MySQL using Homebrew, this should work for you. Otherwise, you will just need to substitute the appropriate locations for the MySQL datadir
on your machine.
#cd to my data dir location
cd /usr/local/var/
#copy contents of local data directory to the new location
cp -r mysql/ /Volumes/myhd/mydatadir/
#temporarily move the old datadir
mv mysql mysql.local
#symlink to the new location
ln -s /Volumes/myhd/mydatadir mysql
Then to when you want to switch back simply do:
mv mysql mysql.remote
mv mysql.local mysql
and you are using your local database again. Hope that helps.
onDestroyed()
is wrong name for
onDestroy()
Did you make a mistake only in this question or in your code too?
The solution you are looking for is in Angular's official tutorial. In this tutorial Phones are loaded from a JSON file using Angulars $http service . In the code below we use $http.get to load a phones.json file saved in the phones directory:
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
We then iterate over the phones:
<table>
<tbody ng-repeat="i in phones">
<tr><td>{{i.name}}</td><td>{{$index}}</td></tr>
<tr ng-repeat="e in i.details">
<td>{{$index}}</td>
<td>{{e.foo}}</td>
<td>{{e.bar}}</td></tr>
</tbody>
</table>
It appears that it is possible to track a smart phone without using GPS.
Sources:
Primary: "PinMe: Tracking a Smartphone User around the World"
Secondary: "How to Track a Cellphone Without GPS—or Consent"
I have not yet found a link to the team's final code. When I do I will post, if another has not done so.
It seems to me like people dislike a goto
statement a lot, so I felt the need to straighten this out a bit.
I believe the 'emotions' people have about goto
eventually boil down to understanding of code and (misconceptions) about possible performance implications. Before answering the question, I will therefore first go into some of the details on how it's compiled.
As we all know, C# is compiled to IL, which is then compiled to assembler using an SSA compiler. I'll give a bit of insights into how this all works, and then try to answer the question itself.
From C# to IL
First we need a piece of C# code. Let's start simple:
foreach (var item in array)
{
// ...
break;
// ...
}
I'll do this step by step to give you a good idea of what happens under the hood.
First translation: from foreach
to the equivalent for
loop (Note: I'm using an array here, because I don't want to get into details of IDisposable -- in which case I'd also have to use an IEnumerable):
for (int i=0; i<array.Length; ++i)
{
var item = array[i];
// ...
break;
// ...
}
Second translation: the for
and break
is translated into an easier equivalent:
int i=0;
while (i < array.Length)
{
var item = array[i];
// ...
break;
// ...
++i;
}
And third translation (this is the equivalent of the IL code): we change break
and while
into a branch:
int i=0; // for initialization
startLoop:
if (i >= array.Length) // for condition
{
goto exitLoop;
}
var item = array[i];
// ...
goto exitLoop; // break
// ...
++i; // for post-expression
goto startLoop;
While the compiler does these things in a single step, it gives you insight into the process. The IL code that evolves from the C# program is the literal translation of the last C# code. You can see for yourself here: https://dotnetfiddle.net/QaiLRz (click 'view IL')
Now, one thing you have observed here is that during the process, the code becomes more complex. The easiest way to observe this is by the fact that we needed more and more code to ackomplish the same thing. You might also argue that foreach
, for
, while
and break
are actually short-hands for goto
, which is partly true.
From IL to Assembler
The .NET JIT compiler is an SSA compiler. I won't go into all the details of SSA form here and how to create an optimizing compiler, it's just too much, but can give a basic understanding about what will happen. For a deeper understanding, it's best to start reading up on optimizing compilers (I do like this book for a brief introduction: http://ssabook.gforge.inria.fr/latest/book.pdf ) and LLVM (llvm.org).
Every optimizing compiler relies on the fact that code is easy and follows predictable patterns. In the case of FOR loops, we use graph theory to analyze branches, and then optimize things like cycli in our branches (e.g. branches backwards).
However, we now have forward branches to implement our loops. As you might have guessed, this is actually one of the first steps the JIT is going to fix, like this:
int i=0; // for initialization
if (i >= array.Length) // for condition
{
goto endOfLoop;
}
startLoop:
var item = array[i];
// ...
goto endOfLoop; // break
// ...
++i; // for post-expression
if (i >= array.Length) // for condition
{
goto startLoop;
}
endOfLoop:
// ...
As you can see, we now have a backward branch, which is our little loop. The only thing that's still nasty here is the branch that we ended up with due to our break
statement. In some cases, we can move this in the same way, but in others it's there to stay.
So why does the compiler do this? Well, if we can unroll the loop, we might be able to vectorize it. We might even be able to proof that there's just constants being added, which means our whole loop could vanish into thin air. To summarize: by making the patterns predictable (by making the branches predictable), we can proof that certain conditions hold in our loop, which means we can do magic during the JIT optimization.
However, branches tend to break those nice predictable patterns, which is something optimizers therefore kind-a dislike. Break, continue, goto - they all intend to break these predictable patterns- and are therefore not really 'nice'.
You should also realize at this point that a simple foreach
is more predictable then a bunch of goto
statements that go all over the place. In terms of (1) readability and (2) from an optimizer perspective, it's both the better solution.
Another thing worth mentioning is that it's very relevant for optimizing compilers to assign registers to variables (a process called register allocation). As you might know, there's only a finite number of registers in your CPU and they are by far the fastest pieces of memory in your hardware. Variables used in code that's in the inner-most loop, are more likely to get a register assigned, while variables outside of your loop are less important (because this code is probably hit less).
Help, too much complexity... what should I do?
The bottom line is that you should always use the language constructs you have at your disposal, which will usually (implictly) build predictable patterns for your compiler. Try to avoid strange branches if possible (specifically: break
, continue
, goto
or a return
in the middle of nothing).
The good news here is that these predictable patterns are both easy to read (for humans) and easy to spot (for compilers).
One of those patterns is called SESE, which stands for Single Entry Single Exit.
And now we get to the real question.
Imagine that you have something like this:
// a is a variable.
for (int i=0; i<100; ++i)
{
for (int j=0; j<100; ++j)
{
// ...
if (i*j > a)
{
// break everything
}
}
}
The easiest way to make this a predictable pattern is to simply eliminate the if
completely:
int i, j;
for (i=0; i<100 && i*j <= a; ++i)
{
for (j=0; j<100 && i*j <= a; ++j)
{
// ...
}
}
In other cases you can also split the method into 2 methods:
// Outer loop in method 1:
for (i=0; i<100 && processInner(i); ++i)
{
}
private bool processInner(int i)
{
int j;
for (j=0; j<100 && i*j <= a; ++j)
{
// ...
}
return i*j<=a;
}
Temporary variables? Good, bad or ugly?
You might even decide to return a boolean from within the loop (but I personally prefer the SESE form because that's how the compiler will see it and I think it's cleaner to read).
Some people think it's cleaner to use a temporary variable, and propose a solution like this:
bool more = true;
for (int i=0; i<100; ++i)
{
for (int j=0; j<100; ++j)
{
// ...
if (i*j > a) { more = false; break; } // yuck.
// ...
}
if (!more) { break; } // yuck.
// ...
}
// ...
I personally am opposed to this approach. Look again on how the code is compiled. Now think about what this will do with these nice, predictable patterns. Get the picture?
Right, let me spell it out. What will happen is that:
more
variable that only happens to be used in control flow. more
will be eliminated from the program, and only branches remain. These branches will be optimized, so you will get only a single branch out of the inner loop.more
is definitely used in the inner-most loop, so if the compiler won't optimize it away, it has a high chance to be allocated to a register (which eats up valuable register memory).So, to summarize: the optimizer in your compiler will go into a hell of a lot of trouble to figure out that more
is only used for the control flow, and in the best case scenario will translate it to a single branch outside of the outer for loop.
In other words, the best case scenario is that it will end up with the equivalent of this:
for (int i=0; i<100; ++i)
{
for (int j=0; j<100; ++j)
{
// ...
if (i*j > a) { goto exitLoop; } // perhaps add a comment
// ...
}
// ...
}
exitLoop:
// ...
My personal opinion on this is quite simple: if this is what we intended all along, let's make the world easier for both the compiler and readability, and write that right away.
tl;dr:
Bottom line:
goto
or bool more
, prefer the former.It's old, but this may help someone else.
Below TouchImageView class supports both zooming in/out on either pinch or double tap
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class TouchImageView extends ImageView implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
Matrix matrix;
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF last = new PointF();
PointF start = new PointF();
float minScale = 1f;
float maxScale = 3f;
float[] m;
int viewWidth, viewHeight;
static final int CLICK = 3;
float saveScale = 1f;
protected float origWidth, origHeight;
int oldMeasuredWidth, oldMeasuredHeight;
ScaleGestureDetector mScaleDetector;
Context context;
public TouchImageView(Context context) {
super(context);
sharedConstructing(context);
}
public TouchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
sharedConstructing(context);
}
GestureDetector mGestureDetector;
private void sharedConstructing(Context context) {
super.setClickable(true);
this.context = context;
mGestureDetector = new GestureDetector(context, this);
mGestureDetector.setOnDoubleTapListener(this);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
matrix = new Matrix();
m = new float[9];
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
last.set(curr);
start.set(last);
mode = DRAG;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
float deltaX = curr.x - last.x;
float deltaY = curr.y - last.y;
float fixTransX = getFixDragTrans(deltaX, viewWidth,
origWidth * saveScale);
float fixTransY = getFixDragTrans(deltaY, viewHeight,
origHeight * saveScale);
matrix.postTranslate(fixTransX, fixTransY);
fixTrans();
last.set(curr.x, curr.y);
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
int xDiff = (int) Math.abs(curr.x - start.x);
int yDiff = (int) Math.abs(curr.y - start.y);
if (xDiff < CLICK && yDiff < CLICK)
performClick();
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
setImageMatrix(matrix);
invalidate();
return true; // indicate event was handled
}
});
}
public void setMaxZoom(float x) {
maxScale = x;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
// Double tap is detected
Log.i("MAIN_TAG", "Double tap detected");
float origScale = saveScale;
float mScaleFactor;
if (saveScale == maxScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
} else {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
}
matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
viewHeight / 2);
fixTrans();
return false;
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float mScaleFactor = detector.getScaleFactor();
float origScale = saveScale;
saveScale *= mScaleFactor;
if (saveScale > maxScale) {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
} else if (saveScale < minScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
}
if (origWidth * saveScale <= viewWidth
|| origHeight * saveScale <= viewHeight)
matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
viewHeight / 2);
else
matrix.postScale(mScaleFactor, mScaleFactor,
detector.getFocusX(), detector.getFocusY());
fixTrans();
return true;
}
}
void fixTrans() {
matrix.getValues(m);
float transX = m[Matrix.MTRANS_X];
float transY = m[Matrix.MTRANS_Y];
float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
float fixTransY = getFixTrans(transY, viewHeight, origHeight
* saveScale);
if (fixTransX != 0 || fixTransY != 0)
matrix.postTranslate(fixTransX, fixTransY);
}
float getFixTrans(float trans, float viewSize, float contentSize) {
float minTrans, maxTrans;
if (contentSize <= viewSize) {
minTrans = 0;
maxTrans = viewSize - contentSize;
} else {
minTrans = viewSize - contentSize;
maxTrans = 0;
}
if (trans < minTrans)
return -trans + minTrans;
if (trans > maxTrans)
return -trans + maxTrans;
return 0;
}
float getFixDragTrans(float delta, float viewSize, float contentSize) {
if (contentSize <= viewSize) {
return 0;
}
return delta;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
viewWidth = MeasureSpec.getSize(widthMeasureSpec);
viewHeight = MeasureSpec.getSize(heightMeasureSpec);
//
// Rescales image on rotation
//
if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
|| viewWidth == 0 || viewHeight == 0)
return;
oldMeasuredHeight = viewHeight;
oldMeasuredWidth = viewWidth;
if (saveScale == 1) {
// Fit to screen.
float scale;
Drawable drawable = getDrawable();
if (drawable == null || drawable.getIntrinsicWidth() == 0
|| drawable.getIntrinsicHeight() == 0)
return;
int bmWidth = drawable.getIntrinsicWidth();
int bmHeight = drawable.getIntrinsicHeight();
Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);
float scaleX = (float) viewWidth / (float) bmWidth;
float scaleY = (float) viewHeight / (float) bmHeight;
scale = Math.min(scaleX, scaleY);
matrix.setScale(scale, scale);
// Center the image
float redundantYSpace = (float) viewHeight
- (scale * (float) bmHeight);
float redundantXSpace = (float) viewWidth
- (scale * (float) bmWidth);
redundantYSpace /= (float) 2;
redundantXSpace /= (float) 2;
matrix.postTranslate(redundantXSpace, redundantYSpace);
origWidth = viewWidth - 2 * redundantXSpace;
origHeight = viewHeight - 2 * redundantYSpace;
setImageMatrix(matrix);
}
fixTrans();
}
}
Usage:
You can replace your ImageView
with TouchImageView in both XML & java
1. For XML
<?xml version="1.0" encoding="utf-8"?>
<com.example.android.myapp.TouchImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imViewedImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true" />
2. For Java
TouchImageView imViewedImage = findViewById(R.id.imViewedImage);
To be safe you don't break stuff (for example when these strings are changed in your code or further up), or crash you program (in case the returned string was literal for example like "hello I'm a literal string"
and you start to edit it), make a copy of the returned string.
You could use strdup()
for this, but read the small print. Or you can of course create your own version if it's not there on your platform.
A global JS variable (object) can be used to pass data between components. Example: Passing data from Ammlogin.vue to Options.vue. In Ammlogin.vue rspData is set to the response from the server. In Options.vue the response from the server is made available via rspData.
index.html:
<script>
var rspData; // global - transfer data between components
</script>
Ammlogin.vue:
....
export default {
data: function() {return vueData},
methods: {
login: function(event){
event.preventDefault(); // otherwise the page is submitted...
vueData.errortxt = "";
axios.post('http://vueamm...../actions.php', { action: this.$data.action, user: this.$data.user, password: this.$data.password})
.then(function (response) {
vueData.user = '';
vueData.password = '';
// activate v-link via JS click...
// JSON.parse is not needed because it is already an object
if (response.data.result === "ok") {
rspData = response.data; // set global rspData
document.getElementById("loginid").click();
} else {
vueData.errortxt = "Felaktig avändare eller lösenord!"
}
})
.catch(function (error) {
// Wu oh! Something went wrong
vueData.errortxt = error.message;
});
},
....
Options.vue:
<template>
<main-layout>
<p>Alternativ</p>
<p>Resultat: {{rspData.result}}</p>
<p>Meddelande: {{rspData.data}}</p>
<v-link href='/'>Logga ut</v-link>
</main-layout>
</template>
<script>
import MainLayout from '../layouts/Main.vue'
import VLink from '../components/VLink.vue'
var optData = { rspData: rspData}; // rspData is global
export default {
data: function() {return optData},
components: {
MainLayout,
VLink
}
}
</script>
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$@"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
This particular commands worked for me.
sudo apt-get remove --purge nginx nginx-full nginx-common
and
sudo apt-get install nginx
credit to this answer on stackexchnage
As, i am installing through anaconda Prompt .In my case, it didn't even work with python -m pip install
Then, i add this
python -m pip install <package_name> --user
It works for me.
Like: python -m pip install mitmproxy --user
Another you should try that run the Command Prompt as Run as Administrator and then try pip install. It should work either.
<%: Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = true } )%>
or
@checked = checked
if you like
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.
Some other things you can check would be to run the following query while the CPU load is high:
SHOW PROCESSLIST;
This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).
You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.
You'll also probably want to give the following a read over as they contain some good information.
It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
use:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.
CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);
Perform a select and use this select query and save to the parameter @IDNUMBER
(SELECT IFNULL
(CONCAT('LHPL',LPAD(
(SUBSTRING_INDEX
(MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)
And then Insert query will be :
INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES
(@IDNUMBER, 'EMPLOYEE NAME');
The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.
If you are using grep
or sed
the syntax will be a little different. Notice that the sequential [^a][^b]
method does not work here:
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n'
jd8a
8$fb
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a]$"
8$fb
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^b]$"
jd8a
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^c]$"
jd8a
8$fb
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a][^b]$"
jd8a
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a][^c]$"
jd8a
8$fb
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a^b]$"
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a^c]$"
8$fb
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^b^c]$"
jd8a
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^b^c^a]$"
FWIW, I'm finding the same results in Regex101, which I think is JavaScript syntax.
Bad: https://regex101.com/r/MJGAmX/2
Good: https://regex101.com/r/LzrIBu/2
\bdbo\..*fn
I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform
(although I only knew car
and Platform
at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.
Here's the regex I used to find it:
\bcar\..*Platform
Create object for the class and call, if you want to call it from other pages.
$obj = new Functions();
$var = $obj->filter($_GET['params']);
Or inside the same class instances [ methods ], try this.
$var = $this->filter($_GET['params']);
Probably there's something wrong with the input values for X and/or T. The function from the question works ok:
import numpy as np
from math import e
def sigmoid(X, T):
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])
print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))
Result:
[[15 16]
[ 5 10]]
[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]
[[ 0.99999969 0.99999989]
[ 0.99330715 0.9999546 ]]
Probably it's the dtype of your input arrays. Changing X to:
X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)
Gives:
Traceback (most recent call last):
File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
print sigmoid(X, T)
File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp
You should have to use Date.ParseExact
or Date.TryParseExact
with correct format string.
Dim edate = "10/12/2009"
Dim expenddt As Date = Date.ParseExact(edate, "dd/MM/yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo)
OR
Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
Dim expenddt As Date = Date.ParseExact(edate, format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None)
OR
Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
Dim expenddt As Date
Date.TryParseExact(edate, format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None, expenddt)
Another possibility:
There are two ways the MySQL client can connect to the server: over TCP/IP, or using sockets. It's possible you have your MySQL server configured to support socket connections, but not network connections.