You could try https://hacss.io:
<a href="http://www.google.com" class=":hover{text-decoration:none;}">Google</a>
Use the DATEDIFF()
function.
Example from documentation:
SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
-> 1
Data for last month-
select count(distinct switch_id)
from [email protected]
where dealer_name = 'XXXX'
and to_char(CREATION_DATE,'MMYYYY') = to_char(add_months(trunc(sysdate),-1),'MMYYYY');
This is an interesting task and and here is my contribution. It's very simple and fast. If interested please bear with me and read on.
If you would like to this job fast, you definitely have to get yourself into dynamical programming. Which means you should forget about recursive approaches. That's for sure...
OK le_m's code which uses the Heap's method seems to be the fastest so far. Well i haven't got a name for my algorithm, i don't know if it's already been implemented or not but it's very simple and fast. As with all dynamical programming approaches we will start with the simplest problem and go for the final result.
Assuming that we have an array of a = [1,2,3]
we will start with
r = [[1]]; // result
t = []; // interim result
Then follow these three steps;
r
(result) array we will add the next item of the input array.t
. (well except for the first one not to waste time with 0 rotation)r
the interim array t
should hold the next level of results so we make r = t; t = [];
and carry on up until the length of the input array a
.So the following are our steps;
r array | push next item to | get length many rotations
| each sub array | of each subarray
-----------------------------------------------------------
[[1]] | [[1,2]] | [[1,2],[2,1]]
----------|-------------------|----------------------------
[[1,2], | [[1,2,3], | [[1,2,3],[2,3,1],[3,1,2],
[2,1]] | [2,1,3]] | [2,1,3],[1,3,2],[3,2,1]]
----------|-------------------|----------------------------
previous t| |
-----------------------------------------------------------
So here is the code
function perm(a){_x000D_
var r = [[a[0]]],_x000D_
t = [],_x000D_
s = [];_x000D_
if (a.length <= 1) return a;_x000D_
for (var i = 1, la = a.length; i < la; i++){_x000D_
for (var j = 0, lr = r.length; j < lr; j++){_x000D_
r[j].push(a[i]);_x000D_
t.push(r[j]);_x000D_
for(var k = 1, lrj = r[j].length; k < lrj; k++){_x000D_
for (var l = 0; l < lrj; l++) s[l] = r[j][(k+l)%lrj];_x000D_
t[t.length] = s;_x000D_
s = [];_x000D_
}_x000D_
}_x000D_
r = t;_x000D_
t = [];_x000D_
}_x000D_
return r;_x000D_
}_x000D_
_x000D_
var arr = [0,1,2,4,5];_x000D_
console.log("The length of the permutation is:",perm(arr).length);_x000D_
console.time("Permutation test");_x000D_
for (var z = 0; z < 2000; z++) perm(arr);_x000D_
console.timeEnd("Permutation test");
_x000D_
In multiple test i have seen it resolving the 120 permutations of [0,1,2,3,4] for 2000 times in 25~35ms.
The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid
type (for instance sns.lmplot()
), use the size
and aspect
parameter.
Size
changes both the height and width, maintaining the aspect ratio.
Aspect
only changes the width, keeping the height constant.
You can always get your desired size by playing with these two parameters.
To get a negative version of a number in JavaScript you can always use the ~
bitwise operator.
For example, if you have a = 1000
and you need to convert it to a negative, you could do the following:
a = ~a + 1;
Which would result in a
being -1000
.
To change Switch style without using style.xml or Java code, you can customize switch into layout XML :
<Switch
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:thumbTint="@color/blue"
android:trackTint="@color/white"
android:checked="true"
android:layout_height="wrap_content" />
It's attribute android:thumbTint and android:trackTint that allowed you to customize color
This is the visual result for this XML :
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
Check in Deployment Assembly,
I have the same error, when i generate the war file with the "maven clean install" way and deploy manualy, it works fine, but when i use the runtime enviroment (eclipse) the problems come.
The solution for me (for eclipse IDE) go to: "proyect properties" --> "Deployment Assembly" --> "Add" --> "the jar you need", in my case java "build path entries". Maybe can help a litle!
Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
$('#selector').is(':visible');
Cast the operands to floats:
float ans = (float)a / (float)b;
Its undefined
because, console.log(response)
runs before doCall(urlToCall);
is finished. You have to pass in a callback function aswell, that runs when your request is done.
First, your function. Pass it a callback:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}
Now:
var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})
@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.
Why perform the summation forwards when you can do it backwards? Given:
std::vector<int> v; // vector to be summed
int sum_of_elements(0); // result of the summation
We can use subscripting, counting backwards:
for (int i(v.size()); i > 0; --i)
sum_of_elements += v[i-1];
We can use range-checked "subscripting," counting backwards (just in case):
for (int i(v.size()); i > 0; --i)
sum_of_elements += v.at(i-1);
We can use reverse iterators in a for loop:
for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
sum_of_elements += *i;
We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):
for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
sum_of_elements += *(i - 1);
We can use accumulate
with reverse iterators:
sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);
We can use for_each
with a lambda expression using reverse iterators:
std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });
So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.
This is the better solution:
verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));
attr_accessor
is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname
and you can use this field in your View, or model, if you wanted, but mostly in your View.
Let's consider the following example
class Address
attr_reader :street
attr_writer :street
def initialize
@street = ""
end
end
Here we have used attr_reader
(readable attribute) and attr_writer
(writable attribute) for accessing purpose. But we can achieve the same functionality using attr_accessor
. In short, attr_accessor provides access to both getter and setter methods.
So modified code is as below
class Address
attr_accessor :street
def initialize
@street = ""
end
end
attr_accessible
allows you to list all the columns you want to allow Mass Assignment. The opposite of this is attr_protected
which means this field I do NOT want anyone to be allowed to Mass Assign to. More than likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.
CSS has a text-align: center
property, and since this is purely a visual thing, not semantic, it should be relegated to CSS, not HTML.
case : <Back as <
override func viewWillAppear(animated: Bool) {
navigationController!.navigationBar.topItem!.title = ""
}
hash[:new_key] = hash.delete :old_key
doctormad's solution is not correct. try this:
$var = '1a';
if ((int) $var == $var) {
var_dump("$var is an integer, really?");
}
this prints
1a is an integer, really?"
use filter_var() with FILTER_VALIDATE_INT argument
$data = Array('0', '1', '1a', '1.1', '1e', '0x24', PHP_INT_MAX+1);
array_walk($data, function ($num){
$is_int = filter_var($num, FILTER_VALIDATE_INT);
if ($is_int === false)
var_dump("$num is not int");
});
this prints
1a is not int
1.1 is not int
1e is not int
0x24 is not int
9.2233720368548E+18 is not int
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
On NetBeans : open your project explorer->Dependencies->[file.jar] rightclick->Download Javadoc
If you try joining C on a field from B before joining B, i.e.:
SELECT A.x,
A.y,
A.z
FROM A
INNER JOIN C
on B.x = C.x
INNER JOIN B
on A.x = B.x
your query will fail, so in this case the order matters.
If you're using Swift 2, now you can only use print() to write something to the output.
Apple has combined both println() and print() functions into one.
Updated to iOS 9
By default, the function terminates the line it prints by adding a line break.
print("Hello Swift")
Terminator
To print a value without a line break after it, pass an empty string as the terminator
print("Hello Swift", terminator: "")
Separator
You now can use separator to concatenate multiple items
print("Hello", "Swift", 2, separator:" ")
Both
Or you could combine using in this way
print("Hello", "Swift", 2, separator:" ", terminator:".")
just wanted to leave my .scss
example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.
Im looking forward for your feedback!
// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;
// Prepare your "function"
@mixin in-between {
@media (min-width:$widthSmall) and (max-width:$widthMedium) {
@content;
}
}
// Apply your "function"
main {
@include in-between {
//Do something between two media queries
padding-bottom: 20px;
}
}
From R..'s answer:
However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.
Users who don't see that it's an array will most likely write something like this (which fails):
#include <stdio.h>
typedef int twoInts[2];
void print(twoInts *twoIntsPtr);
void intermediate (twoInts twoIntsAppearsByValue);
int main () {
twoInts a;
a[0] = 0;
a[1] = 1;
print(&a);
intermediate(a);
return 0;
}
void intermediate(twoInts b) {
print(&b);
}
void print(twoInts *c){
printf("%d\n%d\n", (*c)[0], (*c)[1]);
}
It will compile with the following warnings:
In function ‘intermediate’:
warning: passing argument 1 of ‘print’ from incompatible pointer type [enabled by default]
print(&b);
^
note: expected ‘int (*)[2]’ but argument is of type ‘int **’
void print(twoInts *twoIntsPtr);
^
And produces the following output:
0
1
-453308976
32767
Here's my proposition:
for i in range(len(rserver.keys())):
salt = uuid.uuid4().hex
print(salt)
mdp_hash = rserver.get(rserver.keys()[i])
rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
rsalt.set(rserver.keys()[i], salt)
'a' in x
and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries
If you want to make it center then use android:layout_centerVertical="true"
in the TextView.
You can use np.concatenate()
specifying which axis
to append, using np.newaxis
:
import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)
If you are reading from many files:
import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)
These are the best and most commonly used methods for writing to and reading from files:
using System.IO;
File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it.
File.ReadAllText(sFilePathAndName);
The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.
Append text to an existing file:
private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
string sTextToAppend = txtMainUserInput.Text;
//first, check to make sure that the user entered something in the text box.
if (sTextToAppend == "" || sTextToAppend == null)
{MessageBox.Show("You did not enter any text. Please try again");}
else
{
string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
if (sFilePathAndName == "" || sFilePathAndName == null)
{
//MessageBox.Show("You cancalled"); //DO NOTHING
}
else
{
sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
File.AppendAllText(sFilePathAndName, sTextToAppend);
string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
}//end nested if/else
}//end if/else
}//end method AppendTextToExistingFile_Click
Get file name from the user via file explorer/open file dialog (you will need this to select existing files).
private string getFileNameFromUser()//returns file path\name
{
string sFileNameAndPath = "";
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "Select file";
fd.Filter = "TXT files|*.txt";
fd.InitialDirectory = Environment.CurrentDirectory;
if (fd.ShowDialog() == DialogResult.OK)
{
sFileNameAndPath = (fd.FileName.ToString());
}
return sFileNameAndPath;
}//end method getFileNameFromUser
Get text from an existing file:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
This is what I finally came up with, which works great!
{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}
Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.
There are 2 solutions for this, but it return all columns separately:
import functools
dfs = [df1, df2, df3]
df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
date a_x b_x a_y b_y c_x a b c_y
0 May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
0_a 0_b 1_a 1_b 1_c 2_a 2_b 2_c
date
May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
Little bit cleared @A.Morel's answer. You might beware of keyboard language layout. Some keyboard layouts changed default numeric keys to symbols.
let key = parseInt(e.key)
if (isNaN(key)) {
console.log("is not numeric")
}
else {
console.log("is numeric")
}
Both old and accepted, however, I'll just leave this here:
function dump(){
echo (php_sapi_name() !== 'cli') ? '<pre>' : '';
foreach(func_get_args() as $arg){
echo preg_replace('#\n{2,}#', "\n", print_r($arg, true));
}
echo (php_sapi_name() !== 'cli') ? '</pre>' : '';
}
Takes an arbitrary number of arguments, and wraps each in <pre>
for CGI requests. In CLI requests it skips the <pre>
tag generation for clean output.
dump(array('foo'), array('bar', 'zip'));
/*
CGI request CLI request
<pre> Array
Array (
( [0] => foo
[0] => foo )
) Array
</pre> (
<pre> [0] => bar
Array [1] => zip
( )
[0] => bar
[0] => zip
)
</pre>
C++11 override
keyword when used with the function declaration inside the derived class, it forces the compiler to check that the declared function is actually overriding some base class function. Otherwise, the compiler will throw an error.
Hence you can use override
specifier to ensure dynamic polymorphism (function overriding).
class derived: public base{
public:
virtual void func_name(int var_name) override {
// statement
}
};
thePlayers[i] = new Player(i);
I just deleted the i
inside Player(i)
; and it worked.
so the code line should be:
thePlayers[i] = new Player9();
I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.
I solved it by using os.walk()
, recursively calling my function and using shutil.move()
on files which I wanted to overwrite and folders which did not exist.
It works like shutil.move()
, but with the benefit that existing files are only overwritten, but not deleted.
import os
import shutil
def moverecursively(source_folder, destination_folder):
basename = os.path.basename(source_folder)
dest_dir = os.path.join(destination_folder, basename)
if not os.path.exists(dest_dir):
shutil.move(source_folder, destination_folder)
else:
dst_path = os.path.join(destination_folder, basename)
for root, dirs, files in os.walk(source_folder):
for item in files:
src_path = os.path.join(root, item)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.move(src_path, dst_path)
for item in dirs:
src_path = os.path.join(root, item)
moverecursively(src_path, dst_path)
None of the answers here mention the fact that a URL image can be compressed (gzip), and none of them work in this case.
There are two solutions that can get you around this:
The first is to use the cURL method and set the curl_setopt CURLOPT_ENCODING, ''
:
// ... image validation ...
// Handle compression & redirection automatically
$ch = curl_init($image_url);
$fp = fopen($dest_path, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
// Exclude header data
curl_setopt($ch, CURLOPT_HEADER, 0);
// Follow redirected location
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Auto detect decoding of the response | identity, deflate, & gzip
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_exec($ch);
curl_close($ch);
fclose($fp);
It works, but from hundreds of tests of different images (png, jpg, ico, gif, svg), it is not the most reliable way.
What worked out best is to detect whether an image url has content encoding (e.g. gzip):
// ... image validation ...
// Fetch all headers from URL
$data = get_headers($image_url, true);
// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;
// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;
if ($gzip_decode)
{
// Get contents and use gzdecode to "unzip" data
file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
// Use copy method
copy($image_url, $dest_path);
}
For more information regarding gzdecode see this thread. So far this works fine. If there's anything that can be done better, let us know in the comments below.
Just came across this myself.
Finally found my issue was with a .png file that I added that had a capital letter in it an caused exactly the same problem. Eclipse never flagged the file until I closed it and opened Eclipse back up.
A simple method that only uses RGB is
cR=R1-R2
cG=G1-G2
cB=B1-B2
uR=R1+R2
distance=cR*cR*(2+uR/256) + cG*cG*4 + cB*cB*(2+(255-uR)/256)
I've used this one for a while now, and it works well enough for most purposes.
You can either install PostgreSQL 9.2.1 in the pg_dump
client machine or just copy the $PGHOME
from the PostgreSQL server machine to the client machine. Note that there is no need to initdb
a new cluster in the client machine.
After you have finished installing the 9.2.1 software, remember to edit some environment variables in your .bash_profile
file.
You can use the GTK glib to abstract from OS stuff.
glib provides a g_dir_open() function which should do the trick.
context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
Should return the list of all the installed apps but in android 11 it'll only return the list of system apps. To get the list of all the applications(system+user) we need to provide an additional permission to the application i.e
<uses-permission android:name"android.permission.QUERY_ALL_PACKAGES">
Also, here is how to calculate a 64-bit NSNumber
initialized with the Unix epoch in milliseconds, in case that is how you want to store it in CoreData. I needed this for my app which interacts with a system that stores dates this way.
+ (NSNumber*) longUnixEpoch {
return [NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970] * 1000];
}
I was trying to run a .net core 3.1 site from IIS 10 on windows 10 pro box, and got this error. Did the following to resolve it.
First turn on the following iis feature on.
Then follow the link below.
Install the .net core hosting bundle.
The direct link is
I have installed the .net core sdk and run time as well. But this did not resolve the issue.
What made the difference is the .net core hosting bundle.
You can do :
document.forms["loginForm"].submit()
But this won't call the onclick
action of your button, so you will need to call it by hand.
Be aware that you must use the name
of your form and not the id
to access it.
Steps to start Apache httpd.exe (I am using x64 VC11 example here)
http://www.apachelounge.com/download/VC11/
Be sure that you have installed Visual C++ Redistributable for Visual Studio 2012 : VC11 vcredist_x64/86.exe
http://www.microsoft.com/en-us/download/details.aspx?id=30679
You may need to have Visual Studio 2012 Update 3 (VS2012.3)
http://www.microsoft.com/en-us/download/details.aspx?id=30679 (vcredirect.exe)
http://support.microsoft.com/kb/2835600
Unzip httpd-2.4.4-win64-VC11.zip and copy paste in
C:\Apache24
Unzip modules-2.4-win64-VC11.zip and copy paste them in
C:\Apache24\modules
http://www.apachelounge.com/viewtopic.php?p=25091
For further info on the modules see the Apache Lounge VC10 Win64 download page and/or the readme in the .zip's there.
http://www.apachelounge.com/download/win64/
In
C:\Apache24\conf\httpd.conf
un-comment (remove # sign) starting below this like copy pasted list in here
# Example:
# LoadModule foo_module modules/mod_foo.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule buffer_module modules/mod_buffer.so
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule charset_lite_module modules/mod_charset_lite.so
LoadModule data_module modules/mod_data.so
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule dav_lock_module modules/mod_dav_lock.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
LoadModule expires_module modules/mod_expires.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule filter_module modules/mod_filter.so
LoadModule headers_module modules/mod_headers.so
LoadModule heartbeat_module modules/mod_heartbeat.so
LoadModule heartmonitor_module modules/mod_heartmonitor.so
LoadModule ident_module modules/mod_ident.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_debug_module modules/mod_log_debug.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule lua_module modules/mod_lua.so
LoadModule mime_module modules/mod_mime.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_html_module modules/mod_proxy_html.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reflector_module modules/mod_reflector.so
LoadModule remoteip_module modules/mod_remoteip.so
LoadModule request_module modules/mod_request.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule sed_module modules/mod_sed.so
LoadModule session_module modules/mod_session.so
LoadModule session_cookie_module modules/mod_session_cookie.so
LoadModule session_crypto_module modules/mod_session_crypto.so
LoadModule session_dbd_module modules/mod_session_dbd.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule socache_dbm_module modules/mod_socache_dbm.so
LoadModule socache_memcache_module modules/mod_socache_memcache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule speling_module modules/mod_speling.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule status_module modules/mod_status.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule version_module modules/mod_version.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule watchdog_module modules/mod_watchdog.so
LoadModule xml2enc_module modules/mod_xml2enc.so
Then find
C:\Apache24\bin\ApacheMonitor.exe
and double click on it.
Then in Command Prompt (CMD.exe) type
C:\Apache24\bin\httpd.exe
and press enter. It shows any error remaining.
Build with the latest Update 3 Visual Studio® 2012 aka VC11. VC11 has improvements, fixes and optimizations over VC10 in areas like Performance, MemoryManagement and Stability. For example code quality tuning and improvements done across different code generation areas for "speed". And makes more use of modern processors and win7, win8, 2008 and Server 2012 internal features.
The VC11 binaries loads VC11, VC10 and VC9 modules, and does not run on XP and 2003. Minimum system required: Windows 7 SP1, Windows 8 / 8.1, Windows Vista SP2, Windows Server 2008 R2 SP1, Windows Server 2012 / R2
After you have downloaded and before you attempt to install it, you should make sure that it is intact and has not been tampered with. Use the PGP Signature and/or the SHA Checksums to verify the integrity.
Thank you
One can directly store the returned output of a function in a file.
print(output statement, file=open("filename", "a"))
you can update your war from the command line using java commands as mentioned here:
jar -uvf test.war yourclassesdir
Other useful commands:
Command to unzip/explode the war file
jar -xvf test.war
Command to create the war file
jar -cvf test.war yourclassesdir
Eg:
jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF
As far as I remember the standard, all function declarations are considered as "extern" by default, so there is no need to specify it explicitly.
That doesn't make this keyword useless since it can also be used with variables (and it that case - it's the only solution to solve linkage problems). But with the functions - yes, it's optional.
Using reduce which is available in python2.7 and python3.* you can easily replace mutiple substrings in a clean and pythonic way.
# Lets define a helper method to make it easy to use
def replacer(text, replacements):
return reduce(
lambda text, ptuple: text.replace(ptuple[0], ptuple[1]),
replacements, text
)
if __name__ == '__main__':
uncleaned_str = "abc&def#ghi"
cleaned_str = replacer(uncleaned_str, [("&","\&"),("#","\#")])
print(cleaned_str) # "abc\&def\#ghi"
In python2.7 you don't have to import reduce but in python3.* you have to import it from the functools module.
$num = "+918883967576";
$str = substr($num, 3);
echo $str;
Output:8883967576
Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.
My contribution ONLY for SQLite:
/**
* Returns an array of column names for a given table.
* Arg. $dsn should be replaced by $this->dsn in a class definition.
*
* @param string $dsn Database connection string,
* e.g.'sqlite:/home/user3/db/mydb.sq3'
* @param string $table The name of the table
*
* @return string[] An array of table names
*/
public function getTableColumns($dsn, $table) {
$dbh = new \PDO($dsn);
return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}
At least for the GitHub Flavoured Markdown, you can give the illusion by making all the non-header row entries bold with the regular __
or **
formatting:
|Regular | text | in header | turns bold |
|-|-|-|-|
| __So__ | __bold__ | __all__ | __table entries__ |
| __and__ | __it looks__ | __like a__ | __"headerless table"__ |
If you are using ASP.NET MVC – you do not need an additional HTTP handler and some modifications of the web.config file. All you need – just to add some simple action in a Home/Common controller:
[HttpPost]
public JsonResult KeepSessionAlive() {
return new JsonResult {Data = "Success"};
}
, write a piece of JavaScript code like this one (I have put it in one of site’s JavaScript file):
var keepSessionAlive = false;
var keepSessionAliveUrl = null;
function SetupSessionUpdater(actionUrl) {
keepSessionAliveUrl = actionUrl;
var container = $("#body");
container.mousemove(function () { keepSessionAlive = true; });
container.keydown(function () { keepSessionAlive = true; });
CheckToKeepSessionAlive();
}
function CheckToKeepSessionAlive() {
setTimeout("KeepSessionAlive()", 5*60*1000);
}
function KeepSessionAlive() {
if (keepSessionAlive && keepSessionAliveUrl != null) {
$.ajax({
type: "POST",
url: keepSessionAliveUrl,
success: function () { keepSessionAlive = false; }
});
}
CheckToKeepSessionAlive();
}
, and initialize this functionality by calling a JavaScript function:
SetupSessionUpdater('/Home/KeepSessionAlive');
Please note! I have implemented this functionality only for authorized users (there is no reason to keep session state for guests in most cases) and decision to keep session state active is not only based on – is browser open or not, but authorized user must do some activity on the site (move a mouse or type some key).
Something like that :
options(digits=2)
Definition of digits option :
digits: controls the number of digits to print when printing numeric values.
Using writeLines also allows you to dispense with the "\n" newline character, by using c()
. As in:
writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))
This is helpful if you plan on writing a multiline message with combined fixed and variable input, such as the [additional text for third line] above.
This problem occurs when your are including file with wrong path and server gives some 404 error in loading file.
You could use svcutil.exe to generate client code. This would include the definition of the service contract and any data contracts and fault contracts required.
Then, simply delete the client code: classes that implement the service contracts. You'll then need to implement them yourself, in your service.
The difference between echo, print, print_r and var_dump is very simple.
echo
echo is actually not a function but a language construct which is used to print output. It is marginally faster than the print.
echo "Hello World"; // this will print Hello World
echo "Hello ","World"; // Multiple arguments - this will print Hello World
$var_1=55;
echo "$var_1"; // this will print 55
echo "var_1=".$var_1; // this will print var_1=55
echo 45+$var_1; // this will print 100
$var_2="PHP";
echo "$var_2"; // this will print PHP
$var_3=array(99,98,97) // Arrays are not possible with echo (loop or index value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with echo (loop or index value required)
You can also use echo statement with or without parenthese
echo ("Hello World"); // this will print Hello World
Just like echo construct print is also a language construct and not a real function. The differences between echo and print is that print only accepts a single argument and print always returns 1. Whereas echo has no return value. So print statement can be used in expressions.
print "Hello World"; // this will print Hello World
print "Hello ","World"; // Multiple arguments - NOT POSSIBLE with print
$var_1=55;
print "$var_1"; // this will print 55
print "var_1=".$var_1; // this will print var_1=55
print 45+$var_1; // this will print 100
$var_2="PHP";
print "$var_2"; // this will print PHP
$var_3=array(99,98,97) // Arrays are not possible with print (loop or index value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with print (loop or index value required)
Just like echo, print can be used with or without parentheses.
print ("Hello World"); // this will print Hello World
print_r
The print_r() function is used to print human-readable information about a variable. If the argument is an array, print_r() function prints its keys and elements (same for objects).
print_r ("Hello World"); // this will print Hello World
$var_1=55;
print_r ("$var_1"); // this will print 55
print_r ("var_1=".$var_1); // this will print var_1=55
print_r (45+$var_1); // this will print 100
$var_2="PHP";
print_r ("$var_2"); // this will print PHP
$var_3=array(99,98,97) // this will print Array ( [0] => 1 [1] => 2 [2] => 3 )
$var_4=array("P"=>"3","J"=>"4"); // this will print Array ( [P] => 3 [J] => 4 )
var_dump
var_dump function usually used for debugging and prints the information ( type and value) about a variable/array/object.
var_dump($var_1); // this will print int(5444)
var_dump($var_2); // this will print string(5) "Hello"
var_dump($var_3); // this will print array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
var_dump($var_4); // this will print array(2) { ["P"]=> string(1) "3" ["J"]=> string(1) "4" }
The previous answers relate to the situation where the view controller that should present a view 1) has not been added yet to the view hierarchy, or 2) is not the top view controller.
Another possibility is that an alert should be presented while another alert is already presented, and not yet dismissed.
Sorry: There is a mistake in my code before because of the site validation.
String myFile = "/Name Folder/File.jpg";
String myPath = Environment.getExternalStorageDirectory()+myFile;
File f = new File(myPath);
Boolean deleted = f.delete();
I think is clear...
First you must to know your file location.
Second,,, Environment.getExternalStorageDirectory()
is a method who gets your app directory.
Lastly the class File who handle your file...
Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')
> true
The 1st January is an arbitrary date, doesn't mean anything.
Few years later, want to suggest just
for this: https://github.com/casey/just
action v1 v2=default:
@echo 'take action on {{v1}} and {{v2}}...'
SELECT DateAdded, COUNT(1) AS NUMBERADDBYDAY
FROM Responses
WHERE DateAdded >= dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY()
would be a better approach. I would not advice to use @@IDENTITY
, as this can return any ID.
CREATE PROC [dbo].[sp_Test] (
@myID int output,
@myFirstName nvarchar(50),
@myLastName nvarchar(50),
@myAddress nvarchar(50),
@myPort int
) AS
BEGIN
INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
VALUES (@myFirstName, @myLastName, @myAddress, @myPort);
SET @myID = SCOPE_IDENTITY();
END
GO
... or you can do it the right way and have a coherent rule for serialisation/deserialisation of dates all across your application. put this in application.properties:
spring.mvc.date-format=yyyy-MM-dd
LTrim function and RTrim function :
It uses the Trim function to remove both types of spaces.
select LTRIM(RTRIM(' SQL Server '))
output:
SQL Server
You can also use: ctrl+alt+insert
How about this:
def yes(prompt = 'Please enter Yes/No: '):
while True:
try:
i = raw_input(prompt)
except KeyboardInterrupt:
return False
if i.lower() in ('yes','y'): return True
elif i.lower() in ('no','n'): return False
You could use this syntax which is functionally equivalent:
switch (true) {
case condition1:
//e.g. if (condition1 === true)
break;
case condition2:
//e.g. elseif (condition2 === true)
break;
default:
//e.g. else
}
This works because each condition
is fully evaluated before comparison with the switch
value, so the first one that evaluates to true
will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break
.
Note that strict comparison is used, so a branch whose condition
is merely "truthy" will not be executed. You can cast a truthy value to true
with double negation: !!condition
.
I think you're confusing the issues of casting and converting here.
It's often hard to know the difference between the 2 in C# because both of them use the same C# operator: the cast.
In this situation you are almost certainly not looking for a cast operation. Casting a dynamic
to another dynamic
is essentially an identity conversion. It provides no value because you're just getting a dynamic
reference back to the same underlying object. The resulting lookup would be no different.
Instead what you appear to want in this scenario is a conversion. That is morphing the underlying object to a different type and accessing the resulting object in a dynamic
fashion. The best API for this is Convert.ChangeType
.
public static dynamic Convert(dynamic source, Type dest) {
return Convert.ChangeType(source, dest);
}
EDIT
The updated question has the following line:
obj definitely implements castTo
If this is the case then the Cast
method doesn't need to exist. The source object
can simply be assigned to a dynamic
reference.
dynamic d = source;
It sounds like what you're trying to accomplish is to see a particular interface or type in the hierarchy of source
through a dynamic
reference. That is simply not possible. The resulting dynamic
reference will see the implementation object directly. It doesn't look through any particular type in the hierarchy of source. So the idea of casting to a different type in the hierarchy and then back to dynamic
is exactly identical to just assigning to dynamic
in the first place. It will still point to the same underlying object.
I wanted to add this answer because I used the primary answer from this question as my basis for exporting from a datatable to Excel using OpenXML but then transitioned to OpenXMLWriter when I found it to be much faster than the above method.
You can find the full details in my answer in the link below. My code is in VB.NET though, so you'll have to convert it.
I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
plt.title(figure_title, y=1.08)
This also works for plt.suptitle()
, but not (yet) for plt.xlabel()
, etc.
Please think first of open/closed principle. The default methods in interfaces DO VIOLATE it. This is a bad feature in Java. It encourages bad design, bad architecture, low software quality. I would suggest to avoid using default methods completely.
Ask yourself a few questions: Why can't you put your methods to the abstract class? Would you need then more than one abstract class? Then think about what is your class responsible for. Are you sure all methods you are going to put to the single class really fulfill the same purpose? May be you will distinguish several purposes and will then split your class into several classes, for each purpose its own class.
The first line occurrences of "foo" will be replaced with "bar". And you can using the second line to check.
grep -rl 'foo' . | xargs sed -i 's/foo/bar/g'
grep 'foo' -r * | awk -F: {'print $1'} | sort -n | uniq -c
Why make it so complicated? This worked.
SELECT m_id,v_id,MAX(TIMESTAMP) AS TIME
FROM table_name
GROUP BY m_id
This shows you how to
DOM
Nodes
with XPath
Nodes
. We will call the code with the following statement
processFilteredXml(xmlIn, xpathExpr,(node) -> {/*Do something...*/;});
In our case we want to print some creatorNames
from a book.xml
using "//book/creators/creator/creatorName"
as xpath to perform a printNode
action on each Node that matches the XPath
.
Full code
@Test
public void printXml() {
try (InputStream in = readFile("book.xml")) {
processFilteredXml(in, "//book/creators/creator/creatorName", (node) -> {
printNode(node, System.out);
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private InputStream readFile(String yourSampleFile) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(yourSampleFile);
}
private void processFilteredXml(InputStream in, String xpath, Consumer<Node> process) {
Document doc = readXml(in);
NodeList list = filterNodesByXPath(doc, xpath);
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
process.accept(node);
}
}
public Document readXml(InputStream xmlin) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
return db.parse(xmlin);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NodeList filterNodesByXPath(Document doc, String xpathExpr) {
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
Object eval = expr.evaluate(doc, XPathConstants.NODESET);
return (NodeList) eval;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void printNode(Node node, PrintStream out) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
out.println(xmlString);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Prints
<creatorName>Fosmire, Michael</creatorName>
<creatorName>Wertz, Ruth</creatorName>
<creatorName>Purzer, Senay</creatorName>
For book.xml
<book>
<creators>
<creator>
<creatorName>Fosmire, Michael</creatorName>
<givenName>Michael</givenName>
<familyName>Fosmire</familyName>
</creator>
<creator>
<creatorName>Wertz, Ruth</creatorName>
<givenName>Ruth</givenName>
<familyName>Wertz</familyName>
</creator>
<creator>
<creatorName>Purzer, Senay</creatorName>
<givenName>Senay</givenName>
<familyName>Purzer</familyName>
</creator>
</creators>
<titles>
<title>Critical Engineering Literacy Test (CELT)</title>
</titles>
</book>
On THL W100 running the device as root (as described above) worked only together with tethering enabled (I used AirDroid for that).
SELECT REPLACE(CONVERT(varchar(20), (CAST(9876543 AS money)), 1), '.00', '')
output= 9,876,543
and you can replace 9876543 by your column name.
Having observed people, who have learned Java first, struggle with the concepts of pointers and memory management in C++, I'd say that learning C first is a good idea, in order to grasp these two concepts, isolated from the complexities of other C++ features.
var data="your data";//ex data="id="+id;
$.ajax({
method : "POST",
url : "file name", //url: "demo.php"
data : "data",
success : function(result){
//set result to div or target
//ex $("#divid).html(result)
}
});
To NEVER remove any code when making changes. We were told to comment all changes. Bear in mind we use source control. This policy didn't last long because developers were in an uproar about it and how it would make the code unreadable.
Do Ctrl+alt+t
and then:
sudo chmod 777 /opt/lampp/phpmyadmin/config.inc.php
open config.inc.php
test
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
save config.inc.php
sudo chmod 644 /opt/lampp/phpmyadmin/config.inc.php
restart the xampp and check phpmyadmin
If it works i think i am glad to help you!!!
Each answer is missing some points, so here is my solution:
$("#input").on("input", function(e) {_x000D_
var input = $(this);_x000D_
var val = input.val();_x000D_
_x000D_
if (input.data("lastval") != val) {_x000D_
input.data("lastval", val);_x000D_
_x000D_
//your change action goes here _x000D_
console.log(val);_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="input">_x000D_
<p>Try to drag the letters and copy paste</p>
_x000D_
The Input Event
fires on Keyboard input, Mouse Drag, Autofill and Copy-Paste tested on Chrome and Firefox.
Checking for previous value makes it detect real changes, which means not firing when pasting the same thing or typing the same character or etc.
Working example: http://jsfiddle.net/g6pcp/473/
update:
And if you like to run your change function
only when user finishes typing and prevent firing the change action several times, you could try this:
var timerid;_x000D_
$("#input").on("input", function(e) {_x000D_
var value = $(this).val();_x000D_
if ($(this).data("lastval") != value) {_x000D_
_x000D_
$(this).data("lastval", value);_x000D_
clearTimeout(timerid);_x000D_
_x000D_
timerid = setTimeout(function() {_x000D_
//your change action goes here _x000D_
console.log(value);_x000D_
}, 500);_x000D_
};_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="input">
_x000D_
If user starts typing (e.g. "foobar") this code prevents your change action
to run for every letter user types and and only runs when user stops typing, This is good specially for when you send the input to the server (e.g. search inputs), that way server does only one search for foobar
and not six searches for f
and then fo
and then foo
and foob
and so on.
Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT
clause). You can only select one column from such a query in this context.
Consider joining to the users
table instead; this will give you more flexibility when selecting what columns you want from users
.
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by
WHERE topics.cat_id = :cat
GROUP BY topics.id
Use repr
>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
var temp="/yourapp/";
$(location).attr('href','http://abcd.com'+temp);
Try this... used as an alternative
When I want to get all the POST params I am using the code below,
@RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(@RequestBody AClass anObject) {
// Source..
}
I am using the @RequestBody
annotation for post/put/delete http requests instead of the @RequestParam
which reads the GET parameters.
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
mysql -u app -p
mysql> set @@global.show_compatibility_56=ON;
as per http://bugs.mysql.com/bug.php?id=78159 worked for me.
Edit the System environment variables, and enter following path:
C:\Program Files\nodejs\node.exe;
C:\Users\{yourName}\AppData\Roaming\npm
A very simple CSS only answer is to put this at the top of your stylesheet:
a{padding-top: 90px;}
a:link{padding-top: unset;}
The first style regulates all anchor tags where the second styles anchor tags with a hyperlink.
Note: This currently works in Firefox and Edge but nor in Chrome.
I would be inclined to this which has the virtue of IE8 support.
li{
margin-top: 10px;
border:1px solid grey;
}
li:first-child {
margin-top:0;
}
You should check wheter the index exists before use it (compare it)
if (isset($_GET['s']) AND $_GET['s'] == 'foobar') {
echo "foo";
}
Use E_ALL | E_STRICT while developing!
Here is a method to merge a dictionary of data frames while keeping the column names in sync with the dictionary. Also it fills in missing values if needed:
def MergeDfDict(dfDict, onCols, how='outer', naFill=None):
keys = dfDict.keys()
for i in range(len(keys)):
key = keys[i]
df0 = dfDict[key]
cols = list(df0.columns)
valueCols = list(filter(lambda x: x not in (onCols), cols))
df0 = df0[onCols + valueCols]
df0.columns = onCols + [(s + '_' + key) for s in valueCols]
if (i == 0):
outDf = df0
else:
outDf = pd.merge(outDf, df0, how=how, on=onCols)
if (naFill != None):
outDf = outDf.fillna(naFill)
return(outDf)
def GenDf(size):
df = pd.DataFrame({'categ1':np.random.choice(a=['a', 'b', 'c', 'd', 'e'], size=size, replace=True),
'categ2':np.random.choice(a=['A', 'B'], size=size, replace=True),
'col1':np.random.uniform(low=0.0, high=100.0, size=size),
'col2':np.random.uniform(low=0.0, high=100.0, size=size)
})
df = df.sort_values(['categ2', 'categ1', 'col1', 'col2'])
return(df)
size = 5
dfDict = {'US':GenDf(size), 'IN':GenDf(size), 'GER':GenDf(size)}
MergeDfDict(dfDict=dfDict, onCols=['categ1', 'categ2'], how='outer', naFill=0)
Bootstrap 4.0
Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex
, and drop the xs
to allow bootstrap to automatically detect the viewport.
<div class="container-fluid">
<table id="productSizes" class="table">
<thead>
<tr class="d-flex">
<th class="col-1">Size</th>
<th class="col-3">Bust</th>
<th class="col-3">Waist</th>
<th class="col-5">Hips</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-1">6</td>
<td class="col-3">79 - 81</td>
<td class="col-3">61 - 63</td>
<td class="col-5">89 - 91</td>
</tr>
<tr class="d-flex">
<td class="col-1">8</td>
<td class="col-3">84 - 86</td>
<td class="col-3">66 - 68</td>
<td class="col-5">94 - 96</td>
</tr>
</tbody>
</table>
Bootstrap 3.2
Table column width use the same layout as grids do; using col-[viewport]-[size]
. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12
in this example.
<thead>
<tr>
<th class="col-xs-1">Size</th>
<th class="col-xs-3">Bust</th>
<th class="col-xs-3">Waist</th>
<th class="col-xs-5">Hips</th>
</tr>
</thead>
Remember to set the <th>
elements rather than the <td>
elements so it sets the whole column. Here is a working BOOTPLY.
Thanks to @Dan for reminding me to always work mobile view (col-xs-*
) first.
If the constructor of a class is private then you cannot create an object for class from outside of it.
class Test{
int x, y;
private Test(){
.......
.......
}
}
We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class
public static Test getObject(){
return new Test();
}
So now you can create an object for this class from outside of it. Like the way...
Test t = Test.getObject();
Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method
.
Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:
x <- 1:10
y <- x + c(-0.5,0.5)
plot(x,y, xlim=c(0,11), ylim=c(-1,12))
fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )
fit7 <- lm( y ~ x + cos(x*pi) )
xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')
Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).
This is what I use to sort in memory - it can easily be expanded to sort an array.
Sub sortlist()
Dim xarr As Variant
Dim yarr As Variant
Dim zarr As Variant
xarr = Sheets("sheet").Range("sing col range")
ReDim yarr(1 To UBound(xarr), 1 To 1)
ReDim zarr(1 To UBound(xarr), 1 To 1)
For n = 1 To UBound(xarr)
zarr(n, 1) = 1
Next n
For n = 1 To UBound(xarr) - 1
y = zarr(n, 1)
For a = n + 1 To UBound(xarr)
If xarr(n, 1) > xarr(a, 1) Then
y = y + 1
Else
zarr(a, 1) = zarr(a, 1) + 1
End If
Next a
yarr(y, 1) = xarr(n, 1)
Next n
y = zarr(UBound(xarr), 1)
yarr(y, 1) = xarr(UBound(xarr), 1)
yrng = "A1:A" & UBound(yarr)
Sheets("sheet").Range(yrng) = yarr
End Sub
#ifndef <token>
/* code */
#else
/* code to include if the token is defined */
#endif
#ifndef
checks whether the given token has been #defined
earlier in the file or in an included file; if not, it includes the code between it and the closing #else
or, if no #else
is present, #endif
statement. #ifndef
is often used to make header files idempotent by defining a token once the file has been included and checking that the token was not set at the top of that file.
#ifndef _INCL_GUARD
#define _INCL_GUARD
#endif
Yes you can usually see what SOAP version is supported based on the WSDL.
Take a look at Demo web service WSDL. It has a reference to the soap12 namespace indicating it supports SOAP 1.2. If that was absent then you'd probably be safe assuming the service only supported SOAP 1.1.
Here is one way of doing it.
If you HTML looks like this:
<div>Contact Details
<button type="button" class="edit_button">My Button</button>
</div>
apply the following CSS:
div {
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: gray;
overflow: auto;
}
.edit_button {
float: right;
margin: 0 10px 10px 0; /* for demo only */
}
The trick is to apply overflow: auto
to the div
, which starts a new block formatting context. The result is that the floated button is enclosed within the block area defined by the div
tag.
You can then add margins to the button if needed to adjust your styling.
In the original HTML and CSS, the floated button was out of the content flow so the border of the div
would be positioned with respect to the in-flow text, which does not include any floated elements.
See demo at: http://jsfiddle.net/audetwebdesign/AGavv/
I will avoid iterator as they can add/remove object during iteration, also for clean code use for loop. it will be simply clean & fewer lines.
Using Java 8 and Lamda [Update 4/2/2019]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
jsonObj.keySet().forEach(keyStr ->
{
Object keyvalue = jsonObj.get(keyStr);
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
});
}
Using old way [Update 4/2/2019]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (String keyStr : jsonObj.keySet()) {
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
}
}
Original Answer
import org.json.simple.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
}
You can access any LayoutParams
from code using View.getLayoutParams
. You just have to be very aware of what LayoutParams
your accessing. This is normally achieved by checking the containing ViewGroup
if it has a LayoutParams
inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams
. You'll be using RelativeLayout.LayoutParams#addRule(int verb)
and RelativeLayout.LayoutParams#addRule(int verb, int anchor)
You can get to it via code:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params); //causes layout update
install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB
The easiest way I found:
<Setter Property="Focusable" Value="false"/>
Network connection problems.
Maybe due to the persistent connection timeout.
The best way is to change to another network.
log4j.jar
filelog4j.jar
file to build pathCall logger by:
private static org.apache.log4j.Logger log
= Logger.getLogger(<class-where-this-is-used>.class);
if log4j properties does not exist, create new file log4j.properties file new file in bin directory:
/workspace/projectdirectory/bin/
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%t %-5p %c{2} - %m%n
For me the better solution was the following. Since the initiative of closing the connection was done by the server, the setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
had no effect and the TIME_WAIT was avoiding a new connection on the same port with error:
[Errno 10048]: Address already in use. Only one usage of each socket address (protocol/IP address/port) is normally permitted
I finally used the solution to let the OS choose the port itself, then another port is used if the precedent is still in TIME_WAIT.
I replaced:
self._socket.bind((guest, port))
with:
self._socket.bind((guest, 0))
As it was indicated in the python socket documentation of a tcp address:
If supplied, source_address must be a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.
Here's a recursive solution for flatten I put together in PowerShell:
#---helper function for ConvertTo-JhcUtilJsonTable
#
function getNodes {
param (
[Parameter(Mandatory)]
[System.Object]
$job,
[Parameter(Mandatory)]
[System.String]
$path
)
$t = $job.GetType()
$ct = 0
$h = @{}
if ($t.Name -eq 'PSCustomObject') {
foreach ($m in Get-Member -InputObject $job -MemberType NoteProperty) {
getNodes -job $job.($m.Name) -path ($path + '.' + $m.Name)
}
}
elseif ($t.Name -eq 'Object[]') {
foreach ($o in $job) {
getNodes -job $o -path ($path + "[$ct]")
$ct++
}
}
else {
$h[$path] = $job
$h
}
}
#---flattens a JSON document object into a key value table where keys are proper JSON paths corresponding to their value
#
function ConvertTo-JhcUtilJsonTable {
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[System.Object[]]
$jsonObj
)
begin {
$rootNode = 'root'
}
process {
foreach ($o in $jsonObj) {
$table = getNodes -job $o -path $rootNode
# $h = @{}
$a = @()
$pat = '^' + $rootNode
foreach ($i in $table) {
foreach ($k in $i.keys) {
# $h[$k -replace $pat, ''] = $i[$k]
$a += New-Object -TypeName psobject -Property @{'Key' = $($k -replace $pat, ''); 'Value' = $i[$k]}
# $h[$k -replace $pat, ''] = $i[$k]
}
}
# $h
$a
}
}
end{}
}
Example:
'{"name": "John","Address": {"house": "1234", "Street": "Boogie Ave"}, "pets": [{"Type": "Dog", "Age": 4, "Toys": ["rubberBall", "rope"]},{"Type": "Cat", "Age": 7, "Toys": ["catNip"]}]}' | ConvertFrom-Json | ConvertTo-JhcUtilJsonTable
Key Value
--- -----
.Address.house 1234
.Address.Street Boogie Ave
.name John
.pets[0].Age 4
.pets[0].Toys[0] rubberBall
.pets[0].Toys[1] rope
.pets[0].Type Dog
.pets[1].Age 7
.pets[1].Toys[0] catNip
.pets[1].Type Cat
The error is very straight forward, you imported react instead of React.
TechView.jsx
import React , { Component} from 'react';
class TechView extends Component {
constructor(props){
super(props);
this.state = {
name:'Gopinath'
}
}
render(){
return(
<span>hello Tech View</span>
);
}
}
export default TechView;
Also you don't need to import render in the above code unless it's the root level index.js.
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import TechView from './TechView';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<TechView />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
Note: You could have imported render the way you did in your original post and used it directly:
import React from 'react';
import { render } from 'react-dom';
import './index.css';
import TechView from './TechView';
import * as serviceWorker from './serviceWorker';
render(
<React.StrictMode>
<TechView />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
Here, TechView becomes the main react component, which is conventionally also known as App. So, in this context instead of naming the file as TechView.jsx I'd name it App.jsx and instead of naming the class as TechView I'd name it App.
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
The output is actually dependent on the content type being requested. However, at minimum you should put the resource that was created in Location. Just like the Post-Redirect-Get pattern.
In my case I leave it blank until requested otherwise. Since that is the behavior of JAX-RS when using Response.created().
However, just note that browsers and frameworks like Angular do not follow 201's automatically. I have noted the behaviour in http://www.trajano.net/2013/05/201-created-with-angular-resource/
Been using this for a while.
# post.rb
class Post < ApplicationRecord
attribute :country, :string, default: 'ID'
end
Um...
with open(os.path.join(src_dir, f)) as fin:
for line in fin:
Also, you never output to a new file.
The DictWriter()
class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer()
and pass in a simple row for the header:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.writer(outcsv)
writer.writerow(["Date", "temperature 1", "Temperature 2"])
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row + [0.0] for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)
The alternative would be to generate dictionaries when copying across your data:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
writer.writeheader()
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)
I had a related issue working within Spyder, but the problem seems to be the relationship between the escape character ( "\") and the "\" in the path name Here's my illustration and solution (note single \ vs double \\ ):
path = 'C:\Users\myUserName\project\subfolder'
path # 'C:\\Users\\myUserName\\project\subfolder'
os.listdir(path) # gives windows error
path = 'C:\\Users\\myUserName\\project\\subfolder'
os.listdir(path) # gives expected behavior
Here is some example code to help you get started:
package com.acme;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileArrayProvider {
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
And an example unit test:
package com.acme;
import java.io.IOException;
import org.junit.Test;
public class FileArrayProviderTest {
@Test
public void testFileArrayProvider() throws IOException {
FileArrayProvider fap = new FileArrayProvider();
String[] lines = fap
.readLines("src/main/java/com/acme/FileArrayProvider.java");
for (String line : lines) {
System.out.println(line);
}
}
}
Hope this helps.
If your terminal supports ANSI escape codes, this clears the screen and moves the cursor to the first row, first column:
System.out.print("\033[H\033[2J");
System.out.flush();
This works on almost all UNIX terminals and terminal emulators. The Windows cmd.exe
does not interprete ANSI escape codes.
Darian Moody has a nice solution to this challenge in his blog post:
a = 1
b = 2
c = True
rules = [a == 1,
b == 2,
c == True]
if all(rules):
print("Success!")
The all() method returns True
when all elements in the given iterable are true. If not, it returns False
.
You can read a little more about it in the python docs here and more information and examples here.
(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)
Try using the /
from the numeric keyboard.
Ctrl
+ /
in Chrome wasn't working for me, but when I used the /
(division symbol) from the numeric it worked.
Try this:
$comments_collection = $post->comments()->get()->toArray();
see this can help you
toArray() method in Collections
I didn't have any luck with yolk
, yolk3k
or pip install -v
but so I ended up using this (adapted to Python 3 from eric chiang's answer):
import json
import requests
from distutils.version import StrictVersion
def versions(package_name):
url = "https://pypi.python.org/pypi/{}/json".format(package_name)
data = requests.get(url).json()
return sorted(list(data["releases"].keys()), key=StrictVersion, reverse=True)
>>> print("\n".join(versions("gunicorn")))
19.1.1
19.1.0
19.0.0
18.0
17.5
0.17.4
0.17.3
...
I found my answer.
<?php
$profpic = "bg.jpg";
?>
<html>
<head>
<style type="text/css">
body {
background-image: url('<?php echo $profpic;?>');
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>
I researched and implemented this last semester for a game development course. Hopefully this sample code can point you in the right direction of how you might approach this.
class Entity {
public:
Entity(const unsigned int id, const std::string& enttype);
~Entity();
//Component Interface
const Component* GetComponent(const std::string& family) const;
void SetComponent(Component* newComp);
void RemoveComponent(const std::string& family);
void ClearComponents();
//Property Interface
bool HasProperty(const std::string& propName) const;
template<class T> T& GetPropertyDataPtr(const std::string& propName);
template<class T> const T& GetPropertyDataPtr(const std::string& propName) const;
//Entity Interface
const unsigned int GetID() const;
void Update(float dt);
private:
void RemoveProperty(const std::string& propName);
void ClearProperties();
template<class T> void AddProperty(const std::string& propName);
template<class T> Property<T>* GetProperty(const std::string& propName);
template<class T> const Property<T>* GetProperty(const std::string& propName) const;
unsigned int m_Id;
std::map<const string, IProperty*> m_Properties;
std::map<const string, Component*> m_Components;
};
Components specify behavior and operate on properties. Properties are shared between all components by a reference and get updates for free. This means no large overhead for message passing. If there's any questions I'll try to answer as best I can.
From Activity#showDialog(int)
:
This method is deprecated.
Use the newDialogFragment
class withFragmentManager
instead; this is also available on older platforms through the Android compatibility package.
You could use 'corrplot' package.
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
M <- cor(d) # get correlations
library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix
More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
display
syntax instead, for clarityThe display
CSS property in fact sets two things at once: the outer display type, and the inner display type. The outer display type affects how the element (which acts as a container) is displayed in its context. The inner display type affects how the children of the element (or the children of the container) are laid out.
If you use the two-value display
syntax, which is only supported in some browsers like Firefox, the difference between the two is much more obvious:
display: block
is equivalent to display: block flow
display: inline
is equivalent to display: inline flow
display: flex
is equivalent to display: block flex
display: inline-flex
is equivalent to display: inline flex
display: grid
is equivalent to display: block grid
display: inline-grid
is equivalent to display: inline grid
block
or inline
:An element with the outer display type of block
will take up the whole width available to it, like <div>
does. An element with the outer display type of inline
will only take up the width that it needs, with wrapping, like <span>
does.
flow
, flex
or grid
:The inner display type flow
is the default inner display type when flex
or grid
is not specified. It is the way of laying out children elements that we are used to in a <p>
for instance. flex
and grid
are new ways of laying out children that each deserve their own post.
The difference between display: flex
and display: inline-flex
is the outer display type, the first's outer display type is block
, and the second's outer display type is inline
. Both of them have the inner display type of flex
.
The API doc for IllegalArgumentException
:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
From looking at how it is used in the JDK libraries, I would say:
It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.
It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).
I would use IllegalArgumentException
to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException
. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.
Sadly, I don't think there is. The Matrix
class is responsible for all image manipulations, whether it's rotating, shrinking/growing, skewing, etc.
http://developer.android.com/reference/android/graphics/Matrix.html
My apologies, but I can't think of an alternative. Maybe someone else might be able to, but the times I've had to manipulate an image I've used a Matrix.
Best of luck!
You can get the results with a simple:
@app.route('your route', methods=['GET'])
def yourMethod(params):
response = flask.jsonify({'some': 'data'})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:
Looping style:
# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]
# dictionary we want for the result
dictionary = {}
# loop that makes it work
for realName, falseName, position in data:
dictionary.setdefault(realName, {})[falseName] = position
dictionary now equals:
{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}
One nice clean way is to add a data-default
attribute to the select
<select id="my_select" data-default="b">
...
</select>
An then the code is really simple:
$("#reset").on("click", function () {
var $select = $('#my_select');
$select.val($select.data('default'));
});
Live example: http://jsfiddle.net/T8sCf/7/
Use tr:first-child
to take the first tr
:
.category_table tr:first-child td {
vertical-align: top;
}
If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level td
s in the first top-level tr
get the styles:
.category_table > tbody > tr:first-child > td {
vertical-align: top;
}
That is not possible. Reading is downloading. When a user is reading a file, browser is downloading that file to temp. So even if you disable the download button, the user can click "File -> Save As" or copy that file from temp folder.
There are a few things you can do:
Method 1
The following code will embed a PDF without any toolbars and hide the print/download icons
<embed src="{URL_TO_PDF.PDF}#toolbar=0&navpanes=0&scrollbar=0" width="425" height="425">
Method 02
Using Google Drive
Right click on pdf
and goto Share(below image)
Then go to Advanced option in left bottom
Tick Both check boxes. After copy embed
link and paste it to your src
. No download and Save drive option is not allowed
If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:
public class Foo {
private static final int widgets;
static {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
widgets = first + second;
}
}
If first
and second
weren't in a block, they'd look like fields. If they were in a block without static
in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.
Now in this particular case, you could use a static method instead:
public class Foo {
private static final int widgets = getWidgets();
static int getWidgets() {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
return first + second;
}
}
... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).
@RobW's answer is correct, but this is more performant ! Because it uses a hashmap/set:
const customStringify = function (v) {
const cache = new Set();
return JSON.stringify(v, function (key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.has(value)) {
// Circular reference found
try {
// If this value does not reference a parent it can be deduped
return JSON.parse(JSON.stringify(value));
}
catch (err) {
// discard key if value cannot be deduped
return;
}
}
// Store value in our set
cache.add(value);
}
return value;
});
};
Similar to KyleMit answer, its possible to select directly the tables used by SP_WHO2, although I think it's only need dbo.sysprocesses table.
If someone open this SP, it can understand what it does. This is my best select to have a similar output as SP_WHO2
select convert(char(5),sp.spid) as SPID
, CASE lower(sp.status)
When 'sleeping' Then lower(sp.status)
Else upper(sp.status)
END as Status
, convert(sysname, rtrim(sp.loginame)) as LOGIN
, CASE sp.hostname
When Null Then ' .'
When ' ' Then ' .'
Else rtrim(sp.hostname)
END as HostName
, CASE isnull(convert(char(5),sp.blocked),'0')
When '0' Then ' .'
Else isnull(convert(char(5),sp.blocked),'0')
END as BlkBy
, case when sp.dbid = 0 then null when sp.dbid <> 0 then db_name(sp.dbid) end as DBName
, sp.cmd as Command
, sp.cpu as CPUTime
, sp.physical_io as DiskIO
, sp.last_batch as LastBatch
, sp.program_name as ProgramName
from master.dbo.sysprocesses sp (nolock)
;
Over this select, you can select the fields you need and have the order you want.
You can use Get-Member
if(Get-Member -inputobject $var -name "Property" -Membertype Properties){
#Property exists
}
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
#function to find mode
def mode(data):
modecnt=0
#for count of number appearing
for i in range(len(data)):
icount=data.count(data[i])
#for storing count of each number in list will be stored
if icount>modecnt:
#the loop activates if current count if greater than the previous count
mode=data[i]
#here the mode of number is stored
modecnt=icount
#count of the appearance of number is stored
return mode
print mode(data1)
In Visual Studio 2008 it is Ctrl + E + W.
display: inline-block
is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:
(it looks like your picture anyway ;))
CSS:
p, div {
display: inline-block;
vertical-align: middle;
}
p, div {
display: inline !ie7; /* hack for IE7 and below */
}
table {
background: #000;
color: #fff;
font-size: 16px;
font-weight: bold; margin: 0 10px;
}
td {
padding: 5px;
text-align: center;
}
HTML:
<p>some text</p>
<div>
<table summary="">
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
<tr><td>D</td></tr>
</table>
</div>
<p>continues afterwards</p>
In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.
Have a look at the following document:
https://developers.google.com/maps/documentation/urls/guide
You can use URLs in search, directions, map and street view modes.
For example, to show the marker at specified position you can use the following URL:
https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324
For further details please read aforementioned documentation.
You can also file feature requests for this API in Google issue tracker.
Hope this helps!
For Cross-Browser Compatibility :
Example Goes Below :
<html><body class="entire-webpage"></body></html>
.entire-webpage{
zoom: 2;
-moz-transform: scale(2);/* Firefox Property */
-moz-transform-origin: 0 0;
-o-transform: scale(2);/* Opera Property */
-o-transform-origin: 0 0;
-webkit-transform: scale(2);/* Safari Property */
-webkit-transform-origin: 0 0;
transform: scale(2); /* Standard Property */
transform-origin: 0 0; /* Standard Property */
}
In case you have a predicate
and/or a non empty output
to fill with the filtered string, I would consider:
output.reserve(str.size() + output.size());
std::copy_if(str.cbegin(),
str.cend(),
std::back_inserter(output),
predicate});
In the original question the predicate is [](char c){return c != 'a';}
It may be due to the fact that the known_hosts file is owned by another user i.e root in most cases. You can visit the path directory given (/home/taimoor/.ssh/known_hosts in my case) and check if the root is the owner and change it to the default owner.
Example:
I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.
I cloned the repository with HTTPS URL instead of SSH URL hence even after adding the SSH Key it was asking me for password on Bash Shell.
I just edited the ./.git/config
file and changed the value of url
variable by simply replacing the https://
to ssh://
E.g.
[core]
...
...
...
[remote "origin"]
url = https://<username>@bitbucket.org/<username>/<repository_name>.git
fetch = +refs/heads/*:refs/remotes/origin/*
...
...
...
Changed to:
[core]
...
...
...
[remote "origin"]
url = ssh://<username>@bitbucket.org/<username>/<repository_name>.git
fetch = +refs/heads/*:refs/remotes/origin/*
...
...
...
Short-sightedness, I'd guess.
When originally designed, interfaces were intended only to be used with instances of class
IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();
It was only with the introduction of interfaces as constraints for generics did adding a static method to an interface have a practical use.
(responding to comment:) I believe changing it now would require a change to the CLR, which would lead to incompatibilities with existing assemblies.
SSIS (SQL Server Integration Services) is an upgrade of DTS (Data Transformation Services), which is a feature of the previous version of SQL Server. SSIS packages can be created in BIDS (Business Intelligence Development Studio). These can be used to merge data from heterogeneous data sources into SQL Server. They can also be used to populate data warehouses, to clean and standardize data, and to automate administrative tasks.
SQL Server Integration Services (SSIS) is a component of Microsoft SQL Server 2005. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is only available in the "Standard" and "Enterprise" editions. Integration Services provides a platform to build data integration and workflow applications. The primary use for SSIS is data warehousing as the product features a fast and flexible tool for data extraction, transformation, and loading (ETL).). The tool may also be used to automate maintenance of SQL Server databases, update multidimensional cube data, and perform other functions.
If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:
plt.axes[0].get_lines()[0].set_color('black')
As I mentioned in lyceus answer, his code will fail on non-English locale Windows because then the output of mode
may not contain the substrings "columns" or "lines":
You can find the correct substring without looking for text:
preg_match('/---+(\n[^|]+?){2}(?<cols>\d+)/', `mode`, $matches);
$cols = $matches['cols'];
Note that I'm not even bothering with lines because it's unreliable (and I actually don't care about them).
Edit: According to comments about Windows 8 (oh you...), I think this may be more reliable:
preg_match('/CON.*:(\n[^|]+?){3}(?<cols>\d+)/', `mode`, $matches);
$cols = $matches['cols'];
Do test it out though, because I didn't test it.
Change =
to ==
i.e
if (strcmp("hello", "hello") == 0)
You want to compare the result of strcmp()
to 0. So you need ==
. Assigning it to 0 won't work because rvalues cannot be assigned to.
Here's a one-module Python replacement for perl -p
:
# Provide compatibility with `perl -p`
# Usage:
#
# python -mloop_over_stdin_lines '<program>'
# In, `<program>`, use the variable `line` to read and change the current line.
# Example:
#
# python -mloop_over_stdin_lines 'line = re.sub("pattern", "replacement", line)'
# From the perlrun documentation:
#
# -p causes Perl to assume the following loop around your
# program, which makes it iterate over filename arguments
# somewhat like sed:
#
# LINE:
# while (<>) {
# ... # your program goes here
# } continue {
# print or die "-p destination: $!\n";
# }
#
# If a file named by an argument cannot be opened for some
# reason, Perl warns you about it, and moves on to the next
# file. Note that the lines are printed automatically. An
# error occurring during printing is treated as fatal. To
# suppress printing use the -n switch. A -p overrides a -n
# switch.
#
# "BEGIN" and "END" blocks may be used to capture control
# before or after the implicit loop, just as in awk.
#
import re
import sys
for line in sys.stdin:
exec(sys.argv[1], globals(), locals())
try:
print line,
except:
sys.exit('-p destination: $!\n')
I am using below command in redis 3.2.8
redis-cli KEYS *YOUR_KEY_PREFIX* | xargs redis-cli DEL
You can get more help related to keys pattern search from here :- https://redis.io/commands/keys. Use your convenient glob-style pattern as per your requirement like *YOUR_KEY_PREFIX*
or YOUR_KEY_PREFIX??
or any other.
And if any of you have integrated Redis PHP library than below function will help you.
flushRedisMultipleHashKeyUsingPattern("*YOUR_KEY_PATTERN*"); //function call
function flushRedisMultipleHashKeyUsingPattern($pattern='')
{
if($pattern==''){
return true;
}
$redisObj = $this->redis;
$getHashes = $redisObj->keys($pattern);
if(!empty($getHashes)){
$response = call_user_func_array(array(&$redisObj, 'del'), $getHashes); //setting all keys as parameter of "del" function. Using this we can achieve $redisObj->del("key1","key2);
}
}
Thank you :)
TextBox2.Text = "Line 1" & Environment.NewLine & "Line 2"
or
TextBox2.Text = "Line 1"
TextBox2.Text += Environment.NewLine
TextBox2.Text += "Line 2"
This, is how it is done.
With BDD it's
@Test
public void testOrderWithBDD() {
// Given
ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);
//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);
willDoNothing().given(firstMock).methodOne();
willDoNothing().given(secondMock).methodTwo();
// When
firstMock.methodOne();
secondMock.methodTwo();
// Then
then(firstMock).should(inOrder).methodOne();
then(secondMock).should(inOrder).methodTwo();
}
It depends on what environment you're running in. In a web browser you simply need to make sure that file1.js
is loaded before file2.js
:
<script src="file1.js"></script>
<script src="file2.js"></script>
In node.js, the recommended way is to make file1 a module then you can load it with the require
function:
require('path/to/file1.js');
It's also possible to use node's module style in HTML using the require.js library.
I've found an elegant one line solution using LINQ or Lambda expression, both work the same (LINQ is converted to Lambda when program is compiled). The solution works for any array type and for any number of arrays.
Using LINQ:
public static T[] ConcatArraysLinq<T>(params T[][] arrays)
{
return (from array in arrays
from arr in array
select arr).ToArray();
}
Using Lambda:
public static T[] ConcatArraysLambda<T>(params T[][] arrays)
{
return arrays.SelectMany(array => array.Select(arr => arr)).ToArray();
}
I've provided both for one's preference. Performance wise @Sergey Shteyn's or @deepee1's solutions are a bit faster, Lambda expression being the slowest. Time taken is dependant on type(s) of array elements, but unless there are millions of calls, there is no significant difference between the methods.
The built-in function system.time()
will do it.
Use like: system.time(result <- myfunction(with, arguments))
ampersand (&) is escaped to &
double quotes (") are escaped to "
single quotes (') are escaped to '
less than (<) is escaped to <
greater than (>) is escaped to >
In C#, use System.Security.SecurityElement.Escape
or System.Net.WebUtility.HtmlEncode
to escape these illegal characters.
string xml = "<node>it's my \"node\" & i like it 0x12 x09 x0A 0x09 0x0A <node>";
string encodedXml1 = System.Security.SecurityElement.Escape(xml);
string encodedXml2= System.Net.WebUtility.HtmlEncode(xml);
encodedXml1
"<node>it's my "node" & i like it 0x12 x09 x0A 0x09 0x0A <node>"
encodedXml2
"<node>it's my "node" & i like it 0x12 x09 x0A 0x09 0x0A <node>"
it depends on how you trigger the event. the key you are looking is textbox.clientid.
x.aspx code
<script type="text/javascript">
function disable_textbox(tid) {
var mytextbox = document.getElementById(tid);
mytextbox.disabled=false
}
</script>
code behind x.aspx.cs
string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID ");</script>";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);
You could try this(this uses a constructor, but I'm sure you can change it around a bit):
function Obj() {
this.subObj = {
// code
}
this.subObj.parent = this;
}
I want to post a simple solution for every schema you've got. If you are using MySQL DB, you can simply get from your schema all the table's name and add the WHERE-LIKE condition on it. You also could do it with the usual command line as follows:
SHOW TABLES WHERE tables_in_<your_shcema_name> LIKE '%<table_partial_name>%';
where tables_in_<your_shcema_name>
returns the column's name of SHOW TABLES
command.
This error can apparently happen for a number of reasons. Here is my experience for those who land here after searching for "Cannot GET /"
I experienced this error when I installed ng-bootstrap v6 into an Angular 8 project. I downgraded ng-bootstrap to v5 and it seems to be okay now, since ng-bootstrap v6 is only compatible with Angular 9.
This happened while working in Visual Studio 2019 with the Angular .NET Core template. At the same time, the output panel of Visual Studio displayed this esoteric sounding error: "TS1086: An accessor cannot be declared in ambient context," which led me here, which, after a little reading, made me think it was a versioning issue. It appears that it was.
I fixed it by changing "@ng-bootstrap/ng-bootstrap": "^6.0.0"," to "@ng-bootstrap/ng-bootstrap": "^5.0.0" in the package.json file and rebuilding.
On some system, instead of the .bashrc file, you can edit your profils' specific by editing:
sudo nano /etc/profile
As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.
If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString))
. This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body")
are unaffected by this change.
you have many HTML and java script mistakes includes:
tag, using non UTF-8 encoding for form submission, no need,...
You must use document.forms.FORMNAME
or document.forms[0]
for first appear form in page
Corrected:
function validate_frm_new_user_request()_x000D_
{_x000D_
alert('test');_x000D_
var valid = true;_x000D_
_x000D_
if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
{_x000D_
alert ( "Please enter your valid ISID Information." );_x000D_
document.forms.frm_new_user_request.u_userid.focus();_x000D_
valid = false;_x000D_
console.log("FALSE::Empty Value ");_x000D_
}_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
<tr align="left">_x000D_
<td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td align="center" colspan="4">_x000D_
<input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
If you don't want to use a library, this should cover most/all of the same form element types.
function serialize(form) {
if (!form || !form.elements) return;
var serial = [], i, j, first;
var add = function (name, value) {
serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
}
var elems = form.elements;
for (i = 0; i < elems.length; i += 1, first = false) {
if (elems[i].name.length > 0) { /* don't include unnamed elements */
switch (elems[i].type) {
case 'select-one': first = true;
case 'select-multiple':
for (j = 0; j < elems[i].options.length; j += 1)
if (elems[i].options[j].selected) {
add(elems[i].name, elems[i].options[j].value);
if (first) break; /* stop searching for select-one */
}
break;
case 'checkbox':
case 'radio': if (!elems[i].checked) break; /* else continue */
default: add(elems[i].name, elems[i].value); break;
}
}
}
return serial.join('&');
}
Try this:
function someFunction(username, password) {
return new Promise((resolve, reject) => {
// Do something with the params username and password...
if ( /* everything turned out fine */ ) {
resolve("Stuff worked!");
} else {
reject(Error("It didn't work!"));
}
});
}
someFunction(username, password)
.then((result) => {
// Do something...
})
.catch((err) => {
// Handle the error...
});
Many things have been changed in last 6 years on multi-threading front.
Instead of using join()
and lock API, you can use
1.ExecutorService invokeAll()
API
Executes the given tasks, returning a list of Futures holding their status and results when all complete.
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A
CountDownLatch
is initialized with a given count. The await methods block until the current count reaches zero due to invocations of thecountDown()
method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
3.ForkJoinPool or newWorkStealingPool()
in Executors is other way
4.Iterate through all Future
tasks from submit on ExecutorService
and check the status with blocking call get()
on Future
object
Have a look at related SE questions:
How to wait for a thread that spawns it's own thread?
Executors: How to synchronously wait until all tasks have finished if tasks are created recursively?
sed -i "" -e $'4 a\\n''Project_Name=sowstest' start
It works with signed and unsigned values used powerful bit manipulation and generates the first zeroes on the left.
public static String representDigits(int num) {
int checkBit = 1 << (Integer.SIZE * 8 - 2 ); // avoid the first digit
StringBuffer sb = new StringBuffer();
if (num < 0 ) { // checking the first digit
sb.append("1");
} else {
sb.append("0");
}
while(checkBit != 0) {
if ((num & checkBit) == checkBit){
sb.append("1");
} else {
sb.append("0");
}
checkBit >>= 1;
}
return sb.toString();
}
There is an android.location.Location.distanceBetween()
method which does this quite well.
You need to make sure that the exe is in a folder that's on the PATH
environment variable.
You can do this by either installing it into a folder that's already on the PATH
or by adding your folder to the PATH
.
You can have your installer do this - but you will need to restart the machine to make sure it gets picked up.
I didn't find the answer I was looking for, so I wrote this function. This will make an array that contains only the duplicates between the two arrays, but not print the number of times an element is duplicated, so it's not directly answering the question, but I'm hoping it'll help someone in my situation.
function findDuplicates($array1,$array2)
{
$combined = array_merge($array1,$array2);
$counted = array_count_values($combined);
$dupes = [];
$keys = array_keys($counted);
foreach ($keys as $key)
{
if ($counted[$key] > 1)
{$dupes[] = $key;}
}
sort($dupes);
return $dupes;
}
$array1 = [1,2,3,4,5];
$array2 = [4,5,6,7,8];
$dupes = findDuplicates($array1,$array2);
print_r($dupes);
Outputs:
Array
(
[0] => 4
[1] => 5
)
testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
if id == 1:
print testlist[id]
I guess that it's exacly what you want. ;-) 'id' will be always the index of the values on the list.
You can also exclude more than one using only one --exclude
. Like this example:
tar -pczf MyBackup.tar.gz --exclude={"/home/user/public_html/tmp","/home/user/public_html/data"} /home/user/public_html/
In --exclude=
you must finish the directory name without /
and must in between MyBackup.tar.gz and /home/user/public_html/
The syntax is:
tar <OPTIONS> <TARBALL_WILL_CREATE> <ARGS> <PATH_TO_COMPRESS>
As well as the suggestions given already, there is one other possiblity I can infer from your question:
- You still want the result to be a date
- But you want to 'discard' the Days, Hours, etc
- Leaving a year/month only date field
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, <dateField>), 0) AS [year_month_date_field]
FROM
<your_table>
This gets the number of whole months from a base date (0) and then adds them to that base date. Thus rounding Down to the month in which the date is in.
NOTE: In SQL Server 2008, You will still have the TIME attached as 00:00:00.000 This is not exactly the same as "removing" any notation of day and time altogether. Also the DAY set to the first. e.g. 2009-10-01 00:00:00.000
For Activities shown within TabActivities use getParent()
final AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
instead of
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this. Just add:
* {
-webkit-print-color-adjust: exact !important; /* Chrome, Safari */
color-adjust: exact !important; /*Firefox*/
}
As noted by the others it is possible to have multi-column primary keys. It should be noted however that if you have some functional dependencies that are not introduced by a key, you should consider normalizing your relation.
Example:
Person(id, name, email, street, zip_code, area)
There can be a functional dependency between id -> name,email, street, zip_code and area
But often a zip_code
is associated with a area
and thus there is an internal functional dependecy between zip_code -> area
.
Thus one may consider splitting it into another table:
Person(id, name, email, street, zip_code)
Area(zip_code, name)
So that it is consistent with the third normal form.
Arrays in JS have two types of properties:
Regular elements and associative properties (which are nothing but objects)
When you define a = new Array()
, you are defining an empty array. Note that there are no associative objects yet
When you define b = new Array(2)
, you are defining an array with two undefined locations.
In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.
console.log (a)
or console.log(b)
prints the array elements i.e. []
and [undefined, undefined]
respectively. But since a1/a2
and b1/b2
are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2)
kind of syntax
Typical default display properties for ul
ul {
display: block;
list-style-type: disc;
margin-before: 1em;
margin-after: 1em;
margin-start: 0;
margin-end: 0;
padding-start: 40px;
}
You can use DataFrame.select_dtypes
to select string
columns and then apply
function str.strip
.
Notice: Values cannot be types
like dicts
or lists
, because their dtypes
is object
.
df_obj = df.select_dtypes(['object'])
print (df_obj)
0 a
1 c
df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
print (df)
0 1
0 a 10
1 c 5
But if there are only a few columns use str.strip
:
df[0] = df[0].str.strip()
If you're using T-SQL
, the only thing wrong with your code is that you used braces {}
instead of parentheses ()
.
PS: Both IDENTITY
and PRIMARY KEY
imply NOT NULL
, so you can omit that if you wish.
for(int i=1;i<=9;i++) {
p3.add(new JButton(""+i) {{
// initialize the JButton directly
setBackground(Color.BLACK);
setForeground(Color.GRAY);
}});
}
Using Value2
gives a performance benefit. As per Charles Williams blog
Range.Value2 works the same way as Range.Value, except that it does not check the cell format and convert to Date or Currency. And thats probably why its faster than .Value when retrieving numbers.
So
DirArray = [a1:a5].Value2
A similar approach to @Peter Coppins answer. This, I think, is a bit easier and doesn't require the use of the Orca utility:
Check the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" registry key and make sure the value "mso.dll" is NOT present. If it is present, then Office 64-bit seems to be installed and you should not need this workaround.
Download the Microsoft Access Database Engine 2010 Redistributable.
From the command line, run: AccessDatabaseEngine_x64.exe /passive
(Note: this installer silently crashed or failed for me, so I unzipped the components and ran: AceRedist.msi /passive and that installed fine. Maybe a Windows 10 thing.)
Source: How to install 64-bit Microsoft Database Drivers alongside 32-bit Microsoft Office
I'd like to provide an abstract, high-level perspective.
I/O operations interact with the environment. The environment is not part of your program, and not under your control. The environment truly exists "concurrently" with your program. As with all things concurrent, questions about the "current state" don't make sense: There is no concept of "simultaneity" across concurrent events. Many properties of state simply don't exist concurrently.
Let me make this more precise: Suppose you want to ask, "do you have more data". You could ask this of a concurrent container, or of your I/O system. But the answer is generally unactionable, and thus meaningless. So what if the container says "yes" – by the time you try reading, it may no longer have data. Similarly, if the answer is "no", by the time you try reading, data may have arrived. The conclusion is that there simply is no property like "I have data", since you cannot act meaningfully in response to any possible answer. (The situation is slightly better with buffered input, where you might conceivably get a "yes, I have data" that constitutes some kind of guarantee, but you would still have to be able to deal with the opposite case. And with output the situation is certainly just as bad as I described: you never know if that disk or that network buffer is full.)
So we conclude that it is impossible, and in fact unreasonable, to ask an I/O system whether it will be able to perform an I/O operation. The only possible way we can interact with it (just as with a concurrent container) is to attempt the operation and check whether it succeeded or failed. At that moment where you interact with the environment, then and only then can you know whether the interaction was actually possible, and at that point you must commit to performing the interaction. (This is a "synchronisation point", if you will.)
Now we get to EOF. EOF is the response you get from an attempted I/O operation. It means that you were trying to read or write something, but when doing so you failed to read or write any data, and instead the end of the input or output was encountered. This is true for essentially all the I/O APIs, whether it be the C standard library, C++ iostreams, or other libraries. As long as the I/O operations succeed, you simply cannot know whether further, future operations will succeed. You must always first try the operation and then respond to success or failure.
In each of the examples, note carefully that we first attempt the I/O operation and then consume the result if it is valid. Note further that we always must use the result of the I/O operation, though the result takes different shapes and forms in each example.
C stdio, read from a file:
for (;;) {
size_t n = fread(buf, 1, bufsize, infile);
consume(buf, n);
if (n == 0) { break; }
}
The result we must use is n
, the number of elements that were read (which may be as little as zero).
C stdio, scanf
:
for (int a, b, c; scanf("%d %d %d", &a, &b, &c) == 3; ) {
consume(a, b, c);
}
The result we must use is the return value of scanf
, the number of elements converted.
C++, iostreams formatted extraction:
for (int n; std::cin >> n; ) {
consume(n);
}
The result we must use is std::cin
itself, which can be evaluated in a boolean context and tells us whether the stream is still in the good()
state.
C++, iostreams getline:
for (std::string line; std::getline(std::cin, line); ) {
consume(line);
}
The result we must use is again std::cin
, just as before.
POSIX, write(2)
to flush a buffer:
char const * p = buf;
ssize_t n = bufsize;
for (ssize_t k = bufsize; (k = write(fd, p, n)) > 0; p += k, n -= k) {}
if (n != 0) { /* error, failed to write complete buffer */ }
The result we use here is k
, the number of bytes written. The point here is that we can only know how many bytes were written after the write operation.
POSIX getline()
char *buffer = NULL;
size_t bufsiz = 0;
ssize_t nbytes;
while ((nbytes = getline(&buffer, &bufsiz, fp)) != -1)
{
/* Use nbytes of data in buffer */
}
free(buffer);
The result we must use is nbytes
, the number of bytes up to and including the newline (or EOF if the file did not end with a newline).
Note that the function explicitly returns -1
(and not EOF!) when an error occurs or it reaches EOF.
You may notice that we very rarely spell out the actual word "EOF". We usually detect the error condition in some other way that is more immediately interesting to us (e.g. failure to perform as much I/O as we had desired). In every example there is some API feature that could tell us explicitly that the EOF state has been encountered, but this is in fact not a terribly useful piece of information. It is much more of a detail than we often care about. What matters is whether the I/O succeeded, more-so than how it failed.
A final example that actually queries the EOF state: Suppose you have a string and want to test that it represents an integer in its entirety, with no extra bits at the end except whitespace. Using C++ iostreams, it goes like this:
std::string input = " 123 "; // example
std::istringstream iss(input);
int value;
if (iss >> value >> std::ws && iss.get() == EOF) {
consume(value);
} else {
// error, "input" is not parsable as an integer
}
We use two results here. The first is iss
, the stream object itself, to check that the formatted extraction to value
succeeded. But then, after also consuming whitespace, we perform another I/O/ operation, iss.get()
, and expect it to fail as EOF, which is the case if the entire string has already been consumed by the formatted extraction.
In the C standard library you can achieve something similar with the strto*l
functions by checking that the end pointer has reached the end of the input string.
while(!feof)
is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.
Instead of using width
(which is a suggestion when using flexbox), you could use flex: 0 0 230px;
which means:
0
= don't grow (shorthand for flex-grow
)0
= don't shrink (shorthand for flex-shrink
)230px
= start at 230px
(shorthand for flex-basis
)which means: always be 230px
.
See fiddle, thanks @TylerH
Oh, and you don't need the justify-content
and align-items
here.
img {
max-width: 100%;
}
#container {
display: flex;
x-justify-content: space-around;
x-align-items: stretch;
max-width: 1200px;
}
.column.left {
width: 230px;
flex: 0 0 230px;
}
.column.right {
width: 230px;
flex: 0 0 230px;
border-left: 1px solid #eee;
}
.column.center {
border-left: 1px solid #eee;
}
This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k
accordingly (k - 1)
if you have a header row for filtering:
k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count