If B
is a Boolean array, write
B = B*1
(A bit code golfy.)
Just subtract the two datetime values and multiply by 24:
Select Cast((@DateTime2 - @DateTime1) as Float) * 24.0
a test script might be:
Declare @Dt1 dateTime Set @Dt1 = '12 Jan 2009 11:34:12'
Declare @Dt2 dateTime Set @Dt2 = getdate()
Select Cast((@Dt2 - @Dt1) as Float) * 24.0
This works because all datetimes are stored internally as a pair of integers, the first integer is the number of days since 1 Jan 1900, and the second integer (representing the time) is the number of (1) ticks since Midnight. (For SmallDatetimes the time portion integer is the number of minutes since midnight). Any arithmetic done on the values uses the time portion as a fraction of a day. 6am = 0.25, noon = 0.5, etc... See MSDN link here for more details.
So Cast((@Dt2 - @Dt1) as Float) gives you total days between two datetimes. Multiply by 24 to convert to hours. If you need total minutes, Multiple by Minutes per day (24 * 60 = 1440) instead of 24...
NOTE 1: This is not the same as a dotNet or javaScript tick - this tick is about 3.33 milliseconds.
[Flags]
is pretty handy. Syntactic sugar to be sure, but still rather nice.
[Flags]
enum SandwichStuff
{
Cheese = 1,
Pickles = 2,
Chips = 4,
Ham = 8,
Eggs = 16,
PeanutButter = 32,
Jam = 64
};
public Sandwich MakeSandwich(SandwichStuff stuff)
{
Console.WriteLine(stuff.ToString());
// ...
}
// ...
MakeSandwich(SandwichStuff.Cheese
| SandwichStuff.Ham
| SandwichStuff.PeanutButter);
// produces console output: "Cheese, Ham, PeanutButter"
Leppie points out something I hadn't realized, and which rather dampens my enthusiasm for this attribute: it does not instruct the compiler to allow bit combinations as valid values for enumeration variables, the compiler allows this for enumerations regardless. My C++ background showing through... sigh
The method you are looking for is Series.combine. However, it seems some care has to be taken around datatypes. In your example, you would (as I did when testing the answer) naively call
df['col_3'] = df.col_1.combine(df.col_2, func=get_sublist)
However, this throws the error:
ValueError: setting an array element with a sequence.
My best guess is that it seems to expect the result to be of the same type as the series calling the method (df.col_1 here). However, the following works:
df['col_3'] = df.col_1.astype(object).combine(df.col_2, func=get_sublist)
df
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
Use a CountDownLatch:
CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
taskExecutor.execute(new MyTask());
}
try {
latch.await();
} catch (InterruptedException E) {
// handle
}
and within your task (enclose in try / finally)
latch.countDown();
If you have control over the request, you could set the content type to binary/octet-stream. This allows to query for parameters without consuming the input stream.
However, this might be specific to some application servers. I only tested tomcat, jetty seems to behave the same way according to https://stackoverflow.com/a/11434646/957103.
Tell the correlation to ignore the NAs with use
argument, e.g.:
cor(data$price, data$exprice, use = "complete.obs")
Here this should help you
The below jsfiddle link will help you understand how to rotate a image.I used the same one to rotate the dial of a clock.
var rotation = function (){
$("#image").rotate({
angle:0,
animateTo:360,
callback: rotation,
easing: function (x,t,b,c,d){
return c*(t/d)+b;
}
});
}
rotation();
Where: • t: current time,
• b: begInnIng value,
• c: change In value,
• d: duration,
• x: unused
No easing (linear easing): function(x, t, b, c, d) { return b+(t/d)*c ; }
Here is example:
$array = array("Jon","Smith");
foreach($array as $value) {
echo $value;
}
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
Getting Datafrom MySQL database
hope this helps :)
May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.
BLOB A string with a maximum length of 65535 characters.
The MySQL manual says:
The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers
I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
Use the ArrayList copy constructor, then sort that.
List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);
After making the copy, any changes to newList do not affect oldList.
Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.
Aside from the orders-of-magnitude performance advantage over heap allocation, stack allocation is preferable for long running server applications. Even the best managed heaps eventually get so fragmented that application performance degrades.
Whenever you are trying to compare the strings, compare them with respect to each character. For this you can use built in string function called strcmp(input1,input2); and you should use the header file called #include<string.h>
Try this code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char s[]="STACKOVERFLOW";
char s1[200];
printf("Enter the string to be checked\n");//enter the input string
scanf("%s",s1);
if(strcmp(s,s1)==0)//compare both the strings
{
printf("Both the Strings match\n");
}
else
{
printf("Entered String does not match\n");
}
system("pause");
}
You can do this by AWS S3 Cognito try this link here :
http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-examples.html#Amazon_S3
Also try this code
Just change Region, IdentityPoolId and Your bucket name
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>AWS S3 File Upload</title>_x000D_
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.12.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<input type="file" id="file-chooser" />_x000D_
<button id="upload-button">Upload to S3</button>_x000D_
<div id="results"></div>_x000D_
<script type="text/javascript">_x000D_
AWS.config.region = 'your-region'; // 1. Enter your region_x000D_
_x000D_
AWS.config.credentials = new AWS.CognitoIdentityCredentials({_x000D_
IdentityPoolId: 'your-IdentityPoolId' // 2. Enter your identity pool_x000D_
});_x000D_
_x000D_
AWS.config.credentials.get(function(err) {_x000D_
if (err) alert(err);_x000D_
console.log(AWS.config.credentials);_x000D_
});_x000D_
_x000D_
var bucketName = 'your-bucket'; // Enter your bucket name_x000D_
var bucket = new AWS.S3({_x000D_
params: {_x000D_
Bucket: bucketName_x000D_
}_x000D_
});_x000D_
_x000D_
var fileChooser = document.getElementById('file-chooser');_x000D_
var button = document.getElementById('upload-button');_x000D_
var results = document.getElementById('results');_x000D_
button.addEventListener('click', function() {_x000D_
_x000D_
var file = fileChooser.files[0];_x000D_
_x000D_
if (file) {_x000D_
_x000D_
results.innerHTML = '';_x000D_
var objKey = 'testing/' + file.name;_x000D_
var params = {_x000D_
Key: objKey,_x000D_
ContentType: file.type,_x000D_
Body: file,_x000D_
ACL: 'public-read'_x000D_
};_x000D_
_x000D_
bucket.putObject(params, function(err, data) {_x000D_
if (err) {_x000D_
results.innerHTML = 'ERROR: ' + err;_x000D_
} else {_x000D_
listObjs();_x000D_
}_x000D_
});_x000D_
} else {_x000D_
results.innerHTML = 'Nothing to upload.';_x000D_
}_x000D_
}, false);_x000D_
function listObjs() {_x000D_
var prefix = 'testing';_x000D_
bucket.listObjects({_x000D_
Prefix: prefix_x000D_
}, function(err, data) {_x000D_
if (err) {_x000D_
results.innerHTML = 'ERROR: ' + err;_x000D_
} else {_x000D_
var objKeys = "";_x000D_
data.Contents.forEach(function(obj) {_x000D_
objKeys += obj.Key + "<br>";_x000D_
});_x000D_
results.innerHTML = objKeys;_x000D_
}_x000D_
});_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
OR operator can be alternative of case when in where condition
ALTER PROCEDURE [dbo].[RPT_340bClinicDrugInventorySummary]
-- Add the parameters for the stored procedure here
@ClinicId BIGINT = 0,
@selecttype int,
@selectedValue varchar (50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT
drugstock_drugname.n_cur_bal,drugname.cdrugname,clinic.cclinicname
FROM drugstock_drugname
INNER JOIN drugname ON drugstock_drugname.drugnameid_FK = drugname.drugnameid_PK
INNER JOIN drugstock_drugndc ON drugname.drugnameid_PK = drugstock_drugndc.drugnameid_FK
INNER JOIN drugndc ON drugstock_drugndc.drugndcid_FK = drugndc.drugid_PK
LEFT JOIN clinic ON drugstock_drugname.clinicid_FK = clinic.clinicid_PK
WHERE (@ClinicId = 0 AND 1 = 1)
OR (@ClinicId != 0 AND drugstock_drugname.clinicid_FK = @ClinicId)
-- Alternative Case When You can use OR
AND ((@selecttype = 1 AND 1 = 1)
OR (@selecttype = 2 AND drugname.drugnameid_PK = @selectedValue)
OR (@selecttype = 3 AND drugndc.drugid_PK = @selectedValue)
OR (@selecttype = 4 AND drugname.cdrugclass = 'C2')
OR (@selecttype = 5 AND LEFT(drugname.cdrugclass, 1) = 'C'))
ORDER BY clinic.cclinicname, drugname.cdrugname
END
You should use the new available m2e plugin for Maven integration in Eclipse. With help of that plugin, you should create a new project and move your sources into that project. These are the steps:
File > New > Project...
Maven
and select Maven Project
and click Next
.Create a simple project
(to skip the archetype selection).jar
, and a Name.Run as > Maven install
.Ok it turns out I was doing something stupid. I hadn't appended the new file name to the path.
I had
rootDirectory = "C:\\safesite_documents"
but it should have been
rootDirectory = "C:\\safesite_documents\\newFile.jpg"
Sorry it was a stupid mistake as always.
In case you update the image multiple times and it gets CACHED and does not update, add a random string at the end:
// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
Actually the C++ standard (i.e. C++ 0x draft) says (tnx to @Xeo & @Ben Voigt for pointing that out to me):
23.2.4 Associative containers
5 For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. Keys in an associative container are immutable.
6 iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type.
So VC++ 2008 Dinkumware implementation is faulty.
Old answer:
You got that error because in certain implementations of the std lib the set::iterator
is the same as set::const_iterator
.
For example libstdc++ (shipped with g++) has it (see here for the entire source code):
typedef typename _Rep_type::const_iterator iterator;
typedef typename _Rep_type::const_iterator const_iterator;
And in SGI's docs it states:
iterator Container Iterator used to iterate through a set.
const_iterator Container Const iterator used to iterate through a set. (Iterator and const_iterator are the same type.)
On the other hand VC++ 2008 Express compiles your code without complaining that you're calling non const methods on set::iterator
s.
Changing php.ini
for a web application requires restarting Apache.
You should verify that the change took place by running a PHP script that executes the function phpinfo()
. The output of that function will tell you a lot of PHP parameters, including the timeout value.
You might also have changed a copy of php.ini
that is not the same file used by Apache.
I had faced the same issue. I solved it by removing the external JUnit jar dependency which I added by download from the internet externally. But then I went to project->properties->build path->add library->junit->choosed the version(ex junit4)->apply.
It automatically added the dependency. it solved my issue.
You can use the sp_columns stored procedure:
exec sp_columns MyTable
This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:
//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
...
}
Hope it helps
If you give generally give a span
the property display:block
, it'll then behave like a div
, i.e you can set width and height.
You can also skip the div
or span
and just set the a
the to display: block
and apply the backgound style to it.
<a href="" class="myImage"><!----></a>
<style>
.myImage {display: block; width: 160px; height: 20px; margin:0 0 10px 0; background: url(image.png) center top no-repeat;}
.myImage:hover{background-image(image_hover.png);}
</style>
I have this sample Java Code:
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
public class TestClass {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(8081);
Socket accept = socket.accept();
InputStream inputStream = accept.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
char readChar;
while ((readChar = (char) inputStreamReader.read()) != -1) {
System.out.print(readChar);
}
inputStream.close();
accept.close();
System.exit(1);
}
}
and I have this test.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload!</title>
</head>
<body>
<form method="post" action="http://localhost:8081" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit">
</form>
</body>
</html>
and finally the file I will be using for testing purposes, named a.dat has the following content:
0x39 0x69 0x65
if you interpret the bytes above as ASCII or UTF-8 characters, they will actually will be representing:
9ie
So let 's run our Java Code, open up test.html in our favorite browser, upload a.dat
and submit the form and see what our server receives:
POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 196
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary06f6g54NVbSieT6y
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,tr;q=0.6
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF
------WebKitFormBoundary06f6g54NVbSieT6y
Content-Disposition: form-data; name="file"; filename="a.dat"
Content-Type: application/octet-stream
9ie
------WebKitFormBoundary06f6g54NVbSieT6y--
Well I am not surprised to see the characters 9ie because we told Java to print them treating them as UTF-8 characters. You may as well choose to read them as raw bytes..
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF
is actually the last HTTP Header here. After that comes the HTTP Body, where meta and contents of the file we uploaded actually can be seen.
For better understanding why wait() and notify() method belongs to Object class, I'll give you a real life example: Suppose a gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists. To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.
Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives the key to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.
Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchronized keyword, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.
Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.
However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bathroom is open (“notify”) or ask people to wait when it is locked wait.
In my case, was the Docker that cause problems:
Your code would have worked if it had been in this format: YYYY-MM-DD
, this is the computer standard for date formats http://en.wikipedia.org/wiki/ISO_8601
Use jQuery.attr()
in your click handler:
$("#myform").attr('action', 'page1.php');
If you want to use pip
to install required package and import it after installation, you can use this code:
def install_and_import(package):
import importlib
try:
importlib.import_module(package)
except ImportError:
import pip
pip.main(['install', package])
finally:
globals()[package] = importlib.import_module(package)
install_and_import('transliterate')
If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.
I noticed some caching issues with service calls when repeating the same service call (long polling). Adding metadata didn't help. One solution is to pass a timestamp
to ensure ie
thinks it's a different http
service request. That worked for me, so adding a server side scripting code snippet to automatically update this tag wouldn't hurt:
<meta http-equiv="expires" content="timestamp">
date.setTime( date.getTime() + days * 86400000 );
Adding a quick cheat sheet that may help after the long break with Angular:
Example:
declarations: [AppComponent]
What can we inject here? Components, pipes, directives
Example:
imports: [BrowserModule, AppRoutingModule]
What can we inject here? other modules
Example:
providers: [UserService]
What can we inject here? services
Example:
bootstrap: [AppComponent]
What can we inject here? the main component that will be generated by this module (top parent node for a component tree)
Example:
entryComponents: [PopupComponent]
What can we inject here? dynamically generated components (for instance by using ViewContainerRef.createComponent())
Example:
export: [TextDirective, PopupComponent, BrowserModule]
What can we inject here? components, directives, modules or pipes that we would like to have access to them in another module (after importing this module)
You may want to take a look here, this tool saves a BAK file from a remote SQL Server to your local harddrive: FIDA BAK to local
I'll try and break it down (example from documention)
/*
* The cellForRowAtIndexPath takes for argument the tableView (so if the same object
* is delegate for several tableViews it can identify which one is asking for a cell),
* and an indexPath which determines which row and section the cell is returned for.
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*
* This is an important bit, it asks the table view if it has any available cells
* already created which it is not using (if they are offScreen), so that it can
* reuse them (saving the time of alloc/init/load from xib a new cell ).
* The identifier is there to differentiate between different types of cells
* (you can display different types of cells in the same table view)
*/
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
/*
* If the cell is nil it means no cell was available for reuse and that we should
* create a new one.
*/
if (cell == nil) {
/*
* Actually create a new cell (with an identifier so that it can be dequeued).
*/
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
/*
* Now that we have a cell we can configure it to display the data corresponding to
* this row/section
*/
NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
UIImage *theImage = [UIImage imageWithContentsOfFile:path];
cell.imageView.image = theImage;
/* Now that the cell is configured we return it to the table view so that it can display it */
return cell;
}
This is a DataSource
method so it will be called on whichever object has declared itself as the DataSource
of the UITableView
. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).
A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.
The following code can cause similar error:
using (var session = SessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
movie = session.Get<Movie>(movieId);
tx.Commit();
}
Assert.That(movie.Actors.Count == 1);
You can fix it simply:
using (var session = SessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
movie = session.Get<Movie>(movieId);
Assert.That(movie.Actors.Count == 1);
tx.Commit();
}
I would recommend using mingw/msys as a development environment. Especially if you are porting simple console programs. Msys implements a Unix-like shell on Windows, and mingw is a port of the GNU compiler collection (GCC) and other GNU build tools to the Windows platform. It is an open-source project, and well-suited to the task. I currently use it to build utility programs and console applications for Windows XP, and it most certainly has that unistd.h
header you are looking for.
The install procedure can be a little bit tricky, but I found that the best place to start is in MSYS.
It worked for Me.
private Point _mouseLoc;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
_mouseLoc = e.Location;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int dx = e.Location.X - _mouseLoc.X;
int dy = e.Location.Y - _mouseLoc.Y;
this.Location = new Point(this.Location.X + dx, this.Location.Y + dy);
}
}
Perl is a context-based language. It doesn't do its work according to the data you give it. Instead, it figures out how to treat the data based on the operators you use and the context in which you use them. If you do numbers sorts of things, you get numbers:
# numeric addition with strings:
my $sum = '5.45' + '0.01'; # 5.46
If you do strings sorts of things, you get strings:
# string replication with numbers:
my $string = ( 45/2 ) x 4; # "22.522.522.522.5"
Perl mostly figures out what to do and it's mostly right. Another way of saying the same thing is that Perl cares more about the verbs than it does the nouns.
Are you trying to do something and it isn't working?
For me, I found the suggestion in the following thread helped:
It suggested running the following command in the Terminal application:
sudo /usr/sbin/DevToolsSecurity --enable
I included the binary into my projects resources directory like so:
src\main\resources\chrome\chromedriver_win32.zip
src\main\resources\chrome\chromedriver_mac64.zip
src\main\resources\chrome\chromedriver_linux64.zip
Code:
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public WebDriver getWebDriver() throws IOException {
File tempDir = Files.createTempDirectory("chromedriver").toFile();
tempDir.deleteOnExit();
File chromeDriverExecutable;
final String zipResource;
if (SystemUtils.IS_OS_WINDOWS) {
zipResource = "chromedriver_win32.zip";
} else if (SystemUtils.IS_OS_LINUX) {
zipResource = "chromedriver_linux64.zip";
} else if (SystemUtils.IS_OS_MAC) {
zipResource = "chrome/chromedriver_mac64.zip";
} else {
throw new RuntimeException("Unsuppoerted OS");
}
try (InputStream is = getClass().getResourceAsStream("/chrome/" + zipResource)) {
try (ZipInputStream zis = new ZipInputStream(is)) {
ZipEntry entry;
entry = zis.getNextEntry();
chromeDriverExecutable = new File(tempDir, entry.getName());
chromeDriverExecutable.deleteOnExit();
try (OutputStream out = new FileOutputStream(chromeDriverExecutable)) {
IOUtils.copy(zis, out);
}
}
}
System.setProperty("webdriver.chrome.driver", chromeDriverExecutable.getAbsolutePath());
return new ChromeDriver();
}
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
There are two ways to handle the situation where we do not want the index to be stored in csv file.
As others have stated you can use index=False while saving your
dataframe to csv file.
df.to_csv('file_name.csv',index=False)
df.to_csv(' file_name.csv ')
df_new = pd.read_csv('file_name.csv').drop(['unnamed 0'],axis=1)
Well I did not read correctly the man echo
page for this.
echo had 2 options that could do this if I added a 3rd escape character.
The 2 options are -n
and -e
.
-n
will not output the trailing newline. So that saves me from going to a new line each time I echo something.
-e
will allow me to interpret backslash escape symbols.
Guess what escape symbol I want to use for this: \r
. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.
So the echo line would look like this:
echo -ne "Movie $movies - $dir ADDED!"\\r
I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \
symbols in there.
As mentioned by William, printf
can also do similar (and even more extensive) tasks like this.
I'm using NetBeans and needed a solution for this also. After googleling around and starting from Christopher's answer i managed to build a script that helps you easily do this in NetBeans. I'm putting the instructions here in case someone else will need them.
What you have to do is download one-jar. You can use the link from here: http://one-jar.sourceforge.net/index.php?page=getting-started&file=ant Extract the jar archive and look for one-jar\dist folder that contains one-jar-ant-task-.jar, one-jar-ant-task.xml and one-jar-boot-.jar. Extract them or copy them to a path that we will add to the script below, as the value of the property one-jar.dist.dir.
Just copy the following script at the end of your build.xml script (from your NetBeans project), just before /project tag, replace the value for one-jar.dist.dir with the correct path and run one-jar target.
For those of you that are unfamiliar with running targets, this tutorial might help: http://www.oracle.com/technetwork/articles/javase/index-139904.html . It also shows you how to place sources into one jar, but they are exploded, not compressed into jars.
<property name="one-jar.dist.dir" value="path\to\one-jar-ant"/>
<import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />
<target name="one-jar" depends="jar">
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="src.dir" value="src"/>
<property name="bin.dir" value="bin"/>
<property name="build.dir" value="build"/>
<property name="dist.dir" value="dist"/>
<property name="external.lib.dir" value="${dist.dir}/lib"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.target.dir" value="${build.dir}/jars"/>
<property name="final.jar" value="${dist.dir}/${ant.project.name}.jar"/>
<property name="main.class" value="${main.class}"/>
<path id="project.classpath">
<fileset dir="${external.lib.dir}">
<include name="*.jar"/>
</fileset>
</path>
<mkdir dir="${bin.dir}"/>
<!-- <mkdir dir="${build.dir}"/> -->
<!-- <mkdir dir="${classes.dir}"/> -->
<mkdir dir="${jar.target.dir}"/>
<copy includeemptydirs="false" todir="${classes.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
<!-- <echo message="${ant.project.name}: ${ant.file}"/> -->
<javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
<src path="${src.dir}"/>
<classpath refid="project.classpath"/>
</javac>
<delete file="${final.jar}" />
<one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
<main>
<fileset dir="${classes.dir}"/>
</main>
<lib>
<fileset dir="${external.lib.dir}" />
</lib>
</one-jar>
<delete dir="${jar.target.dir}"/>
<delete dir="${bin.dir}"/>
<delete dir="${external.lib.dir}"/>
</target>
Best of luck and don't forget to vote up if it helped you.
>>> print 5.0 / 2
2.5
>>> print 5.0 // 2
2.0
select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;
This is the fastest way to retrieve the row counts but there are a few important caveats:
ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE
(the default), or in earlier versions with ESTIMATE_PERCENT => 100
. See this post for an explanation of how
the AUTO_SAMPLE_SIZE algorithm works in 11g.LAST_ANALYZED
, the current results may be different.Setting the modified http header to some date in 1995 usually does the trick.
Here's an example:
Expires: Wed, 15 Nov 1995 04:58:08 GMT Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT Cache-Control: no-cache, must-revalidate
In addition to previous answers describing how to enable general logging, I had to modify one additional variable in my vanilla MySql 5.6 installation before any SQL was written to the log:
SET GLOBAL log_output = 'FILE';
The default setting was 'NONE'.
function getDatas() {
let cacheKey = 'memories';
if (cacheKey in localStorage) {
let datas = JSON.parse(localStorage.getItem(cacheKey));
// if expired
if (datas['expires'] < Date.now()) {
localStorage.removeItem(cacheKey);
getDatas()
} else {
setDatas(datas);
}
} else {
$.ajax({
"dataType": "json",
"success": function(datas, textStatus, jqXHR) {
let today = new Date();
datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days
setDatas(datas);
localStorage.setItem(cacheKey, JSON.stringify(datas));
},
"url": "http://localhost/phunsanit/snippets/PHP/json.json_encode.php",
});
}
}
function setDatas(datas) {
// display json as text
$('#datasA').text(JSON.stringify(datas));
// your code here
....
}
// call
getDatas();
From git reset
"pull" or "merge" always leaves the original tip of the current branch in
ORIG_HEAD
.git reset --hard ORIG_HEAD
Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.
git reset --merge ORIG_HEAD
After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "
git reset --hard ORIG_HEAD
" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge
" keeps your local changes.
Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
This is useful if you have problems with multiple commits, like running 'git am
' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).In addition, merge always sets '
.git/ORIG_HEAD
' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD
'.
Note: from here
HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.
So HEAD is NOT a synonym for "current branch" everywhere already.
HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).
But it almost always means the "current commit".
It is the commit "git commit
" builds on top of, and "git diff --cached
" and "git status
" compare against.
It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".
HEAD@{5.minutes.ago}
could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".
git1.8.4 (July 2013) introduces introduced a new notation!
(Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.
Instead of typing four capital letters "
HEAD
", you can say "@
" now,
e.g. "git log @
".
See commit cdfd948
Typing '
HEAD
' is tedious, especially when we can use '@
' instead.The reason for choosing '
@
' is that it follows naturally from theref@op
syntax (e.g.HEAD@{u}
), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD
'.So now we can use '
git show @~1
', and all that goody goodness.Until now '
@
' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.
Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.
Here are some of its applications:
There is no easy way to do this. I needed this as well, but wanted a function that can take any two variables and test for equality. That includes non-object values, objects, arrays and any level of nesting.
In your question, you mention wanting to ignore the order of the values in an array. My solution doesn't inherently do that, but you can achieve it by sorting the arrays before comparing for equality
I also wanted the option of casting non-objects to strings so that [1,2]===["1",2]
Since my project uses UnderscoreJs, I decided to make it a mixin rather than a standalone function.
You can test it out on http://jsfiddle.net/nemesarial/T44W4/
Here is my mxin:
_.mixin({
/**
Tests for the equality of two variables
valA: first variable
valB: second variable
stringifyStatics: cast non-objects to string so that "1"===1
**/
equal:function(valA,valB,stringifyStatics){
stringifyStatics=!!stringifyStatics;
//check for same type
if(typeof(valA)!==typeof(valB)){
if((_.isObject(valA) || _.isObject(valB))){
return false;
}
}
//test non-objects for equality
if(!_.isObject(valA)){
if(stringifyStatics){
var valAs=''+valA;
var valBs=''+valB;
ret=(''+valA)===(''+valB);
}else{
ret=valA===valB;
}
return ret;
}
//test for length
if(_.size(valA)!=_.size(valB)){
return false;
}
//test for arrays first
var isArr=_.isArray(valA);
//test whether both are array or both object
if(isArr!==_.isArray(valB)){
return false;
}
var ret=true;
if(isArr){
//do test for arrays
_.each(valA,function(val,idx,lst){
if(!ret){return;}
ret=ret && _.equal(val,valB[idx],stringifyStatics);
});
}else{
//do test for objects
_.each(valA,function(val,idx,lst){
if(!ret){return;}
//test for object member exists
if(!_.has(valB,idx)){
ret=false;
return;
}
// test for member equality
ret=ret && _.equal(val,valB[idx],stringifyStatics);
});
}
return ret;
}
});
This is how you use it:
_.equal([1,2,3],[1,2,"3"],true)
To demonstrate nesting, you can do this:
_.equal(
['a',{b:'b',c:[{'someId':1},2]},[1,2,3]],
['a',{b:'b',c:[{'someId':"1"},2]},["1",'2',3]]
,true);
You either have to declare public $timestamps = false;
in every model, or create a BaseModel, define it there, and have all your models extend it instead of eloquent. Just bare in mind pivot tables MUST have timestamps if you're using Eloquent.
Update: Note that timestamps are no longer REQUIRED in pivot tables after Laravel v3.
Update: You can also disable timestamps by removing $table->timestamps()
from your migration.
You can always use String.format(....). i.e.,
String string = String.format("A String %s %2d", aStringVar, anIntVar);
I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.
Late to the party, but here's some simple javascript-only code to scroll any element to the bottom:
function scrollToBottom(e) {
e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}
In methods chain form:
db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
{
Serial_Number = g.Key,
uid = g.Max(row => row.uid)
});
you can use tar, with --exclude option , and then untar it in destination. eg
cd /source_directory
tar cvf test.tar --exclude=dir_to_exclude *
mv test.tar /destination
cd /destination
tar xvf test.tar
see the man page of tar for more info
I generated json file in the following format (Hope that it will help you) :
{
"countries": [
{
"code": "+7 840",
"name": "Abkhazia"
},
{
"code": "+93",
"name": "Afghanistan"
},
{
"code": "+355",
"name": "Albania"
},
{
"code": "+213",
"name": "Algeria"
},
{
"code": "+1 684",
"name": "American Samoa"
},
{
"code": "+376",
"name": "Andorra"
},
{
"code": "+244",
"name": "Angola"
},
{
"code": "+1 264",
"name": "Anguilla"
},
{
"code": "+1 268",
"name": "Antigua and Barbuda"
},
{
"code": "+54",
"name": "Argentina"
},
{
"code": "+374",
"name": "Armenia"
},
{
"code": "+297",
"name": "Aruba"
},
{
"code": "+247",
"name": "Ascension"
},
{
"code": "+61",
"name": "Australia"
},
{
"code": "+672",
"name": "Australian External Territories"
},
{
"code": "+43",
"name": "Austria"
},
{
"code": "+994",
"name": "Azerbaijan"
},
{
"code": "+1 242",
"name": "Bahamas"
},
{
"code": "+973",
"name": "Bahrain"
},
{
"code": "+880",
"name": "Bangladesh"
},
{
"code": "+1 246",
"name": "Barbados"
},
{
"code": "+1 268",
"name": "Barbuda"
},
{
"code": "+375",
"name": "Belarus"
},
{
"code": "+32",
"name": "Belgium"
},
{
"code": "+501",
"name": "Belize"
},
{
"code": "+229",
"name": "Benin"
},
{
"code": "+1 441",
"name": "Bermuda"
},
{
"code": "+975",
"name": "Bhutan"
},
{
"code": "+591",
"name": "Bolivia"
},
{
"code": "+387",
"name": "Bosnia and Herzegovina"
},
{
"code": "+267",
"name": "Botswana"
},
{
"code": "+55",
"name": "Brazil"
},
{
"code": "+246",
"name": "British Indian Ocean Territory"
},
{
"code": "+1 284",
"name": "British Virgin Islands"
},
{
"code": "+673",
"name": "Brunei"
},
{
"code": "+359",
"name": "Bulgaria"
},
{
"code": "+226",
"name": "Burkina Faso"
},
{
"code": "+257",
"name": "Burundi"
},
{
"code": "+855",
"name": "Cambodia"
},
{
"code": "+237",
"name": "Cameroon"
},
{
"code": "+1",
"name": "Canada"
},
{
"code": "+238",
"name": "Cape Verde"
},
{
"code": "+ 345",
"name": "Cayman Islands"
},
{
"code": "+236",
"name": "Central African Republic"
},
{
"code": "+235",
"name": "Chad"
},
{
"code": "+56",
"name": "Chile"
},
{
"code": "+86",
"name": "China"
},
{
"code": "+61",
"name": "Christmas Island"
},
{
"code": "+61",
"name": "Cocos-Keeling Islands"
},
{
"code": "+57",
"name": "Colombia"
},
{
"code": "+269",
"name": "Comoros"
},
{
"code": "+242",
"name": "Congo"
},
{
"code": "+243",
"name": "Congo, Dem. Rep. of (Zaire)"
},
{
"code": "+682",
"name": "Cook Islands"
},
{
"code": "+506",
"name": "Costa Rica"
},
{
"code": "+385",
"name": "Croatia"
},
{
"code": "+53",
"name": "Cuba"
},
{
"code": "+599",
"name": "Curacao"
},
{
"code": "+537",
"name": "Cyprus"
},
{
"code": "+420",
"name": "Czech Republic"
},
{
"code": "+45",
"name": "Denmark"
},
{
"code": "+246",
"name": "Diego Garcia"
},
{
"code": "+253",
"name": "Djibouti"
},
{
"code": "+1 767",
"name": "Dominica"
},
{
"code": "+1 809",
"name": "Dominican Republic"
},
{
"code": "+670",
"name": "East Timor"
},
{
"code": "+56",
"name": "Easter Island"
},
{
"code": "+593",
"name": "Ecuador"
},
{
"code": "+20",
"name": "Egypt"
},
{
"code": "+503",
"name": "El Salvador"
},
{
"code": "+240",
"name": "Equatorial Guinea"
},
{
"code": "+291",
"name": "Eritrea"
},
{
"code": "+372",
"name": "Estonia"
},
{
"code": "+251",
"name": "Ethiopia"
},
{
"code": "+500",
"name": "Falkland Islands"
},
{
"code": "+298",
"name": "Faroe Islands"
},
{
"code": "+679",
"name": "Fiji"
},
{
"code": "+358",
"name": "Finland"
},
{
"code": "+33",
"name": "France"
},
{
"code": "+596",
"name": "French Antilles"
},
{
"code": "+594",
"name": "French Guiana"
},
{
"code": "+689",
"name": "French Polynesia"
},
{
"code": "+241",
"name": "Gabon"
},
{
"code": "+220",
"name": "Gambia"
},
{
"code": "+995",
"name": "Georgia"
},
{
"code": "+49",
"name": "Germany"
},
{
"code": "+233",
"name": "Ghana"
},
{
"code": "+350",
"name": "Gibraltar"
},
{
"code": "+30",
"name": "Greece"
},
{
"code": "+299",
"name": "Greenland"
},
{
"code": "+1 473",
"name": "Grenada"
},
{
"code": "+590",
"name": "Guadeloupe"
},
{
"code": "+1 671",
"name": "Guam"
},
{
"code": "+502",
"name": "Guatemala"
},
{
"code": "+224",
"name": "Guinea"
},
{
"code": "+245",
"name": "Guinea-Bissau"
},
{
"code": "+595",
"name": "Guyana"
},
{
"code": "+509",
"name": "Haiti"
},
{
"code": "+504",
"name": "Honduras"
},
{
"code": "+852",
"name": "Hong Kong SAR China"
},
{
"code": "+36",
"name": "Hungary"
},
{
"code": "+354",
"name": "Iceland"
},
{
"code": "+91",
"name": "India"
},
{
"code": "+62",
"name": "Indonesia"
},
{
"code": "+98",
"name": "Iran"
},
{
"code": "+964",
"name": "Iraq"
},
{
"code": "+353",
"name": "Ireland"
},
{
"code": "+972",
"name": "Israel"
},
{
"code": "+39",
"name": "Italy"
},
{
"code": "+225",
"name": "Ivory Coast"
},
{
"code": "+1 876",
"name": "Jamaica"
},
{
"code": "+81",
"name": "Japan"
},
{
"code": "+962",
"name": "Jordan"
},
{
"code": "+7 7",
"name": "Kazakhstan"
},
{
"code": "+254",
"name": "Kenya"
},
{
"code": "+686",
"name": "Kiribati"
},
{
"code": "+965",
"name": "Kuwait"
},
{
"code": "+996",
"name": "Kyrgyzstan"
},
{
"code": "+856",
"name": "Laos"
},
{
"code": "+371",
"name": "Latvia"
},
{
"code": "+961",
"name": "Lebanon"
},
{
"code": "+266",
"name": "Lesotho"
},
{
"code": "+231",
"name": "Liberia"
},
{
"code": "+218",
"name": "Libya"
},
{
"code": "+423",
"name": "Liechtenstein"
},
{
"code": "+370",
"name": "Lithuania"
},
{
"code": "+352",
"name": "Luxembourg"
},
{
"code": "+853",
"name": "Macau SAR China"
},
{
"code": "+389",
"name": "Macedonia"
},
{
"code": "+261",
"name": "Madagascar"
},
{
"code": "+265",
"name": "Malawi"
},
{
"code": "+60",
"name": "Malaysia"
},
{
"code": "+960",
"name": "Maldives"
},
{
"code": "+223",
"name": "Mali"
},
{
"code": "+356",
"name": "Malta"
},
{
"code": "+692",
"name": "Marshall Islands"
},
{
"code": "+596",
"name": "Martinique"
},
{
"code": "+222",
"name": "Mauritania"
},
{
"code": "+230",
"name": "Mauritius"
},
{
"code": "+262",
"name": "Mayotte"
},
{
"code": "+52",
"name": "Mexico"
},
{
"code": "+691",
"name": "Micronesia"
},
{
"code": "+1 808",
"name": "Midway Island"
},
{
"code": "+373",
"name": "Moldova"
},
{
"code": "+377",
"name": "Monaco"
},
{
"code": "+976",
"name": "Mongolia"
},
{
"code": "+382",
"name": "Montenegro"
},
{
"code": "+1664",
"name": "Montserrat"
},
{
"code": "+212",
"name": "Morocco"
},
{
"code": "+95",
"name": "Myanmar"
},
{
"code": "+264",
"name": "Namibia"
},
{
"code": "+674",
"name": "Nauru"
},
{
"code": "+977",
"name": "Nepal"
},
{
"code": "+31",
"name": "Netherlands"
},
{
"code": "+599",
"name": "Netherlands Antilles"
},
{
"code": "+1 869",
"name": "Nevis"
},
{
"code": "+687",
"name": "New Caledonia"
},
{
"code": "+64",
"name": "New Zealand"
},
{
"code": "+505",
"name": "Nicaragua"
},
{
"code": "+227",
"name": "Niger"
},
{
"code": "+234",
"name": "Nigeria"
},
{
"code": "+683",
"name": "Niue"
},
{
"code": "+672",
"name": "Norfolk Island"
},
{
"code": "+850",
"name": "North Korea"
},
{
"code": "+1 670",
"name": "Northern Mariana Islands"
},
{
"code": "+47",
"name": "Norway"
},
{
"code": "+968",
"name": "Oman"
},
{
"code": "+92",
"name": "Pakistan"
},
{
"code": "+680",
"name": "Palau"
},
{
"code": "+970",
"name": "Palestinian Territory"
},
{
"code": "+507",
"name": "Panama"
},
{
"code": "+675",
"name": "Papua New Guinea"
},
{
"code": "+595",
"name": "Paraguay"
},
{
"code": "+51",
"name": "Peru"
},
{
"code": "+63",
"name": "Philippines"
},
{
"code": "+48",
"name": "Poland"
},
{
"code": "+351",
"name": "Portugal"
},
{
"code": "+1 787",
"name": "Puerto Rico"
},
{
"code": "+974",
"name": "Qatar"
},
{
"code": "+262",
"name": "Reunion"
},
{
"code": "+40",
"name": "Romania"
},
{
"code": "+7",
"name": "Russia"
},
{
"code": "+250",
"name": "Rwanda"
},
{
"code": "+685",
"name": "Samoa"
},
{
"code": "+378",
"name": "San Marino"
},
{
"code": "+966",
"name": "Saudi Arabia"
},
{
"code": "+221",
"name": "Senegal"
},
{
"code": "+381",
"name": "Serbia"
},
{
"code": "+248",
"name": "Seychelles"
},
{
"code": "+232",
"name": "Sierra Leone"
},
{
"code": "+65",
"name": "Singapore"
},
{
"code": "+421",
"name": "Slovakia"
},
{
"code": "+386",
"name": "Slovenia"
},
{
"code": "+677",
"name": "Solomon Islands"
},
{
"code": "+27",
"name": "South Africa"
},
{
"code": "+500",
"name": "South Georgia and the South Sandwich Islands"
},
{
"code": "+82",
"name": "South Korea"
},
{
"code": "+34",
"name": "Spain"
},
{
"code": "+94",
"name": "Sri Lanka"
},
{
"code": "+249",
"name": "Sudan"
},
{
"code": "+597",
"name": "Suriname"
},
{
"code": "+268",
"name": "Swaziland"
},
{
"code": "+46",
"name": "Sweden"
},
{
"code": "+41",
"name": "Switzerland"
},
{
"code": "+963",
"name": "Syria"
},
{
"code": "+886",
"name": "Taiwan"
},
{
"code": "+992",
"name": "Tajikistan"
},
{
"code": "+255",
"name": "Tanzania"
},
{
"code": "+66",
"name": "Thailand"
},
{
"code": "+670",
"name": "Timor Leste"
},
{
"code": "+228",
"name": "Togo"
},
{
"code": "+690",
"name": "Tokelau"
},
{
"code": "+676",
"name": "Tonga"
},
{
"code": "+1 868",
"name": "Trinidad and Tobago"
},
{
"code": "+216",
"name": "Tunisia"
},
{
"code": "+90",
"name": "Turkey"
},
{
"code": "+993",
"name": "Turkmenistan"
},
{
"code": "+1 649",
"name": "Turks and Caicos Islands"
},
{
"code": "+688",
"name": "Tuvalu"
},
{
"code": "+1 340",
"name": "U.S. Virgin Islands"
},
{
"code": "+256",
"name": "Uganda"
},
{
"code": "+380",
"name": "Ukraine"
},
{
"code": "+971",
"name": "United Arab Emirates"
},
{
"code": "+44",
"name": "United Kingdom"
},
{
"code": "+1",
"name": "United States"
},
{
"code": "+598",
"name": "Uruguay"
},
{
"code": "+998",
"name": "Uzbekistan"
},
{
"code": "+678",
"name": "Vanuatu"
},
{
"code": "+58",
"name": "Venezuela"
},
{
"code": "+84",
"name": "Vietnam"
},
{
"code": "+1 808",
"name": "Wake Island"
},
{
"code": "+681",
"name": "Wallis and Futuna"
},
{
"code": "+967",
"name": "Yemen"
},
{
"code": "+260",
"name": "Zambia"
},
{
"code": "+255",
"name": "Zanzibar"
},
{
"code": "+263",
"name": "Zimbabwe"
}
]
}
Use this way to delete only one side
@ManyToOne(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
// @JoinColumn(name = "qid")
@JoinColumn(name = "qid", referencedColumnName = "qid", foreignKey = @ForeignKey(name = "qid"), nullable = false)
// @JsonIgnore
@JsonBackReference
private QueueGroup queueGroup;
There is a special security expression in spring security:
hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).
I have never used it but I think it is exactly what you are looking for.
Example usage:
<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
...
</security:authorize>
Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.
As far as I can tell, chrome doesn't work properly if you are referencing localhost (say, you're developing a site locally)
This works:
var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
function openRequestedPopup() {
windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}
This does not work
var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
function openRequestedPopup() {
windowObjectReference = window.open("http://localhost/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}
This also does not work, when loaded from http://localhost/webappFolder/Landing.do
var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
function openRequestedPopup() {
windowObjectReference = window.open("/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}
Did a quick google. Seems that to find the file size you do this,
long size = f.length();
The differences between the three methods you posted can be found here
getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.
Java 8 style, using the java.time classes:
// Monday, February 29 is a leap day in 2016 (otherwise, February only has 28 days)
LocalDate start = LocalDate.parse("2016-02-28"),
end = LocalDate.parse("2016-03-02");
// 4 days between (end is inclusive in this example)
Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end) + 1)
.forEach(System.out::println);
Output:
2016-02-28
2016-02-29
2016-03-01
2016-03-02
Alternative:
LocalDate next = start.minusDays(1);
while ((next = next.plusDays(1)).isBefore(end.plusDays(1))) {
System.out.println(next);
}
Java 9 added the datesUntil() method:
start.datesUntil(end.plusDays(1)).forEach(System.out::println);
The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.
The semantics of the recursive execution is as follows:
What I wound up doing was: Put time duration in by hand, e.g. 1 min, 03 sec. Simple but effective. It seems Excel overwrote everything else, even when I used the 'custom format' given in some answers.
Whilst the solutions proposed appear to work for simple examples, doing this in general is a bad idea. A number might not be exactly an integer but when you try to format it, it's close enough to an integer that you get 1.000000
. This can happen if you do a calculation that in theory should give exactly 1, but in practice gives a number very close to but not exactly equal to one due to rounding errors.
Instead, format it first and if your string ends in a period followed by zeros then strip them. There are also some formats that you can use that strip trailing zeros automatically. This might be good enough for your purpose.
double d = 1.0002;
Console.WriteLine(d.ToString("0.##"));
d = 1.02;
Console.WriteLine(d.ToString("0.##"));
Output:
1
1.02
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
EDIT: Consider looking at and upvoting Malvineous's answer on this page. Netmasks are a much more elegant solution.
Simply use a percent sign as a wildcard in the IP address.
From http://dev.mysql.com/doc/refman/5.1/en/grant.html
You can specify wildcards in the host name. For example,
user_name@'%.example.com'
applies touser_name
for any host in theexample.com
domain, anduser_name@'192.168.1.%'
applies touser_name
for any host in the192.168.1
class C subnet.
The problem is that for json.load
you should pass a file like object with a read
function defined. So either you use json.load(response)
or json.loads(response.read())
.
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast
(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.
The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.
The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).
What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?
Sub AddReferences(wbk As Workbook)
' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub
Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
Dim i As Integer
On Error GoTo EH
With wbk.VBProject.References
For i = 1 To .Count
If .Item(i).Name = sRefName Then
Exit For
End If
Next i
If i > .Count Then
.AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
End If
End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
Resume EX
Resume ' debug code
End Sub
Public Sub DebugPrintExistingRefs()
Dim i As Integer
With Application.ThisWorkbook.VBProject.References
For i = 1 To .Count
Debug.Print " AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
Next i
End With
End Sub
The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.
This snippet is dependency injection friendly (I even use it in combination of ngmin and uglify) and it's a more elegant domain driven based solution.
The example below registers a Phone resource and a constant phoneRoutes, which contains all your routing information for that (phone) domain. Something I didn't like in the provided answer was the location of the resolve logic -- the main module should not know anything or be bothered about the way the resource arguments are provided to the controller. This way the logic stays in the same domain.
Note: if you're using ngmin (and if you're not: you should) you only have to write the resolve functions with the DI array convention.
angular.module('myApp').factory('Phone',function ($resource) {
return $resource('/api/phone/:id', {id: '@id'});
}).constant('phoneRoutes', {
'/phone': {
templateUrl: 'app/phone/index.tmpl.html',
controller: 'PhoneIndexController'
},
'/phone/create': {
templateUrl: 'app/phone/edit.tmpl.html',
controller: 'PhoneEditController',
resolve: {
phone: ['$route', 'Phone', function ($route, Phone) {
return new Phone();
}]
}
},
'/phone/edit/:id': {
templateUrl: 'app/phone/edit.tmpl.html',
controller: 'PhoneEditController',
resolve: {
form: ['$route', 'Phone', function ($route, Phone) {
return Phone.get({ id: $route.current.params.id }).$promise;
}]
}
}
});
The next piece is injecting the routing data when the module is in the configure state and applying it to the $routeProvider.
angular.module('myApp').config(function ($routeProvider,
phoneRoutes,
/* ... otherRoutes ... */) {
$routeProvider.when('/', { templateUrl: 'app/main/index.tmpl.html' });
// Loop through all paths provided by the injected route data.
angular.forEach(phoneRoutes, function(routeData, path) {
$routeProvider.when(path, routeData);
});
$routeProvider.otherwise({ redirectTo: '/' });
});
Testing the route configuration with this setup is also pretty easy:
describe('phoneRoutes', function() {
it('should match route configuration', function() {
module('myApp');
// Mock the Phone resource
function PhoneMock() {}
PhoneMock.get = function() { return {}; };
module(function($provide) {
$provide.value('Phone', FormMock);
});
inject(function($route, $location, $rootScope, phoneRoutes) {
angular.forEach(phoneRoutes, function (routeData, path) {
$location.path(path);
$rootScope.$digest();
expect($route.current.templateUrl).toBe(routeData.templateUrl);
expect($route.current.controller).toBe(routeData.controller);
});
});
});
});
You can see it in full glory in my latest (upcoming) experiment. Although this method works fine for me, I really wonder why the $injector isn't delaying construction of anything when it detects injection of anything that is a promise object; it would make things soooOOOOOooOOOOO much easier.
Edit: used Angular v1.2(rc2)
I think the problem is that the browser could not load the jQueryUI image sprite that contains the X icon. Please use Fiddler, Firebug, or some other that can give you access to the HTTP requests the browser makes to the server and verify the image sprite is loaded successfully.
You can use the glob() function to do this.
Here is some documentation on it: http://php.net/manual/en/function.glob.php
Try this one
UPDATE employee
set EMPLOYEE.MAIDEN_NAME =
(SELECT ADD1
FROM EMPS
WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00'
AND EMPLOYEE.EMP_CODE <='ZZ';
check if file exist in side the document/catchimage path :
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
// ur code here
} else {
// ur code here**
}
yourLabel.intrinsicContentSize.width
for Objective-C / Swift
public partial class result : System.Web.UI.Page
{
static DataTable table1 = new DataTable("Shashank");
static DataSet set = new DataSet("office");
protected void Page_Load(object sender, EventArgs e)
{
lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
lblFirstName.Text = Request.Form["txtFirstName"];
lblLastName.Text = Request.Form["txtLastName"];
lblTitle.Text = Request.Form["txtTitle"];
Int32 Rcount = Convert.ToInt32(table1.Rows.Count);
if (Rcount == 0)
{
table1.Columns.Add("ID");
table1.Columns.Add("FName");
table1.Columns.Add("LName");
table1.Columns.Add("Title");
table1.Rows.Add(lblEmployeeNumber.Text, lblFirstName.Text, lblLastName.Text, lblTitle.Text);
set.Tables.Add(table1);
}
else
{
if (lblEmployeeNumber.Text != "")
{
DataRow dr = table1.NewRow();
dr["ID"] = lblEmployeeNumber.Text;
dr["FName"] = lblFirstName.Text;
dr["LName"] = lblLastName.Text;
dr["Title"] = lblTitle.Text;
table1.Rows.Add(dr);
}
}
gvrEmp.DataSource = set;
gvrEmp.DataBind();
}
}
This is just a modification of lunicon's answer (https://stackoverflow.com/a/24387115/3519572) if you want to replace one namespace for another during parsing. And if you want to see what exactly is going on, just uncomment the output lines and set a breakpoint.
public class XMLReaderWithNamespaceCorrection extends StreamReaderDelegate {
private final String wrongNamespace;
private final String correctNamespace;
public XMLReaderWithNamespaceCorrection(XMLStreamReader reader, String wrongNamespace, String correctNamespace) {
super(reader);
this.wrongNamespace = wrongNamespace;
this.correctNamespace = correctNamespace;
}
@Override
public String getAttributeNamespace(int arg0) {
// System.out.println("--------------------------\n");
// System.out.println("arg0: " + arg0);
// System.out.println("getAttributeName: " + getAttributeName(arg0));
// System.out.println("super.getAttributeNamespace: " + super.getAttributeNamespace(arg0));
// System.out.println("getAttributeLocalName: " + getAttributeLocalName(arg0));
// System.out.println("getAttributeType: " + getAttributeType(arg0));
// System.out.println("getAttributeValue: " + getAttributeValue(arg0));
// System.out.println("getAttributeValue(correctNamespace, LN):"
// + getAttributeValue(correctNamespace, getAttributeLocalName(arg0)));
// System.out.println("getAttributeValue(wrongNamespace, LN):"
// + getAttributeValue(wrongNamespace, getAttributeLocalName(arg0)));
String origNamespace = super.getAttributeNamespace(arg0);
boolean replace = (((wrongNamespace == null) && (origNamespace == null))
|| ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
return replace ? correctNamespace : origNamespace;
}
@Override
public String getNamespaceURI() {
// System.out.println("getNamespaceCount(): " + getNamespaceCount());
// for (int i = 0; i < getNamespaceCount(); i++) {
// System.out.println(i + ": " + getNamespacePrefix(i));
// }
//
// System.out.println("super.getNamespaceURI: " + super.getNamespaceURI());
String origNamespace = super.getNamespaceURI();
boolean replace = (((wrongNamespace == null) && (origNamespace == null))
|| ((wrongNamespace != null) && wrongNamespace.equals(origNamespace)));
return replace ? correctNamespace : origNamespace;
}
}
usage:
InputStream is = new FileInputStream(xmlFile);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithNamespaceCorrection xr =
new XMLReaderWithNamespaceCorrection(xsr, "http://wrong.namespace.uri", "http://correct.namespace.uri");
rootJaxbElem = (JAXBElement<SqgRootType>) um.unmarshal(xr);
handleSchemaError(rootJaxbElem, pmRes);
Add the following inside the end of the try/catch to avoid the error that appears when the JSP engine flushes the response via getWriter()
out.clear(); // where out is a JspWriter
out = pageContext.pushBody();
As has been noted, this isn't best practice, but it avoids the errors in your logs.
For your example, you'd add this:
interface JQuery{
printArea():void;
}
Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.
Suppose your textbox field name is Income
Call this validate method when you need to validate your field:
function validate() {
var currency = document.getElementById("Income").value;
var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
if (pattern.test(currency)) {
alert("Currency is in valid format");
return true;
}
alert("Currency is not in valid format!Enter in 00.00 format");
return false;
}
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
Another alternative:
myPlanetsList.Select(i => i.Moons).Sum();
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended
To build on Ilya's answer try the following query:
SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~")
AND ((Left([Name],4))<>"MSys")
AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name
(this one works without modification with an MDB)
ACCDB users may need to do something like this
SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~")
AND ((Left([Name],4))<>"MSys")
AND ((MSysObjects.Type) In (1,4,6))
AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name
As there is an extra table is included that appears to be a system table of some sort.
Given a command like attrib
:
require 'open3'
a="attrib"
Open3.popen3(a) do |stdin, stdout, stderr|
puts stdout.read
end
I've found that while this method isn't as memorable as
system("thecommand")
or
`thecommand`
in backticks, a good thing about this method compared to other methods is
backticks don't seem to let me puts
the command I run/store the command I want to run in a variable, and system("thecommand")
doesn't seem to let me get the output whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.
See "Executing commands in ruby" and Ruby's Open3 documentation.
You can achieve this using the location
object.
location.href = "http://someurl";
I need to select character to split urls in string, so I decided to create list of characters which could not be found in URL by myself:
>>> allowed = "-_.~!*'();:@&=+$,/?%#[]?@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
>>> from string import printable
>>> ''.join(set(printable).difference(set(allowed)))
'`" <\x0b\n\r\x0c\\\t{^}|>'
So, the possible choices are the newline, tab, space, backslash and "<>{}^|
. I guess I'll go with the space or newline. :)
I found that pathlib module also supports this.
from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')
final int[][] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Produces:
1 2 3
4 5 6
7 8 9
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
I think you may be after
select
jobID, JobName,
sum(case when Priority = 1 then 1 else 0 end) as priority1,
sum(case when Priority = 2 then 1 else 0 end) as priority2,
sum(case when Priority = 3 then 1 else 0 end) as priority3,
sum(case when Priority = 4 then 1 else 0 end) as priority4,
sum(case when Priority = 5 then 1 else 0 end) as priority5
from
Jobs
group by
jobID, JobName
However I am uncertain if you need to the jobID and JobName in your results if so remove them and remove the group by,
Simple condition:
if any(str(elem) in ['a','b'] for elem in df['column'].tolist()):
You could convert it to an array and then print that out with Arrays.toString(Object[])
:
System.out.println(Arrays.toString(stack.toArray()));
put(100, "one")
. Note that the key is the first argument, and the value is the 2nd.BiMap
(from guava)If you want to center one element itself you could use alignSelf:
logoImg: {
position: 'absolute',
alignSelf: 'center',
bottom: '-5%'
}
This is an example (Note the logo parent is a view with position: relative)
Yet another way to fix this on Mac OS X with Homebrew installed, is this:
brew install Caskroom/cask/java
Please try this
SELECT *
FROM [Village]
WHERE CONVERT(VARCHAR, CastleType) = 'foo'
I have PHP 5.3.1 and Apache
When I add the extension=php_intl.dll
to php.ini and restart apache, it comes an alert that says "the requested operation has failed"
And this error on Event Monitor:
Faulting application name: httpd.exe, version: 2.2.14.0, time stamp: 0x4ac181d6
Faulting module name: php5ts.dll, version: 5.3.1.0, time stamp: 0x4b051b35
Exception code: 0xc0000005
The problem was some DLLs like icudt36.dll were missing (noticed with sysinternals ProcMon), I've downloaded php 5.3.1 zip version and extract all DLL's to PHP folder. That solved the problem.
You're mixing the parts together instead of separating them cleanly.
printf '\e[1;34m%-6s\e[m' "This is text"
Basically, put the fixed stuff in the format and the variable stuff in the parameters.
If you are trying to make more than just one folder on the root of the sdcard,
ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"
then instead of folder.mkdir()
you would use folder.mkdirs()
I've made this mistake in the past & I took forever to figure it out.
You can use the below expression:
(^\d*\.?\d*[1-9]+\d*$)|(^[1-9]+\.?\d*$)
Valid entries: 1 1. 1.1 1.0 all positive real numbers
Invalid entries: all negative real numbers and 0 and 0.0
For live video conferencing you can't ignore the need of a streaming server.
Yes, flash will let you display video from a webcam within the local flash control, but that won't let you then send that video over the network - for that you need a streaming server to send it to.
If you're going to build something like this it's prudent to think about how you're going to host the video from a very early stage as it will influence how you build the application. Flash/Flex/Silverlight/Windows Media....etc....
You should also look at new triggers.
MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:
use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;
delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row
begin
insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*NEW.id,*/ NEW.data);
end;//
/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
A non-LINQ version:
/// <summary>
/// Returns latest writen file from the specified directory.
/// If the directory does not exist or doesn't contain any file, DateTime.MinValue is returned.
/// </summary>
/// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
/// <returns></returns>
private static DateTime GetLatestWriteTimeFromFileInDirectory(DirectoryInfo directoryInfo)
{
if (directoryInfo == null || !directoryInfo.Exists)
return DateTime.MinValue;
FileInfo[] files = directoryInfo.GetFiles();
DateTime lastWrite = DateTime.MinValue;
foreach (FileInfo file in files)
{
if (file.LastWriteTime > lastWrite)
{
lastWrite = file.LastWriteTime;
}
}
return lastWrite;
}
/// <summary>
/// Returns file's latest writen timestamp from the specified directory.
/// If the directory does not exist or doesn't contain any file, null is returned.
/// </summary>
/// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
/// <returns></returns>
private static FileInfo GetLatestWritenFileFileInDirectory(DirectoryInfo directoryInfo)
{
if (directoryInfo == null || !directoryInfo.Exists)
return null;
FileInfo[] files = directoryInfo.GetFiles();
DateTime lastWrite = DateTime.MinValue;
FileInfo lastWritenFile = null;
foreach (FileInfo file in files)
{
if (file.LastWriteTime > lastWrite)
{
lastWrite = file.LastWriteTime;
lastWritenFile = file;
}
}
return lastWritenFile;
}
You can use this to get border on one side
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
EDITED
As many including me wanted to have a one side border with transparent background, I have implemented a BorderDrawable
which could give me borders with different size and color in the same way as we use css. But this could not be used via xml. For supporting XML, I have added a BorderFrameLayout
in which your layout can be wrapped.
See my github for the complete source.
This issue is still open here: https://github.com/docker/compose/issues/2925
You can set hostname but it is not reachable from other containers. So it is mostly useless.
I believe that there are plenty of circumstances in which it does make sense and it simplifies programming to have some globals that are known across several (tightly coupled) modules. In this spirit, I would like to elaborate a bit on the idea of having a module of globals which is imported by those modules which need to reference them.
When there is only one such module, I name it "g". In it, I assign default values for every variable I intend to treat as global. In each module that uses any of them, I do not use "from g import var", as this only results in a local variable which is initialized from g only at the time of the import. I make most references in the form g.var, and the "g." serves as a constant reminder that I am dealing with a variable that is potentially accessible to other modules.
If the value of such a global variable is to be used frequently in some function in a module, then that function can make a local copy: var = g.var. However, it is important to realize that assignments to var are local, and global g.var cannot be updated without referencing g.var explicitly in an assignment.
Note that you can also have multiple such globals modules shared by different subsets of your modules to keep things a little more tightly controlled. The reason I use short names for my globals modules is to avoid cluttering up the code too much with occurrences of them. With only a little experience, they become mnemonic enough with only 1 or 2 characters.
It is still possible to make an assignment to, say, g.x when x was not already defined in g, and a different module can then access g.x. However, even though the interpreter permits it, this approach is not so transparent, and I do avoid it. There is still the possibility of accidentally creating a new variable in g as a result of a typo in the variable name for an assignment. Sometimes an examination of dir(g) is useful to discover any surprise names that may have arisen by such accident.
Verify the postgres connection hostname/address in pgadmin and use the same in your connection parameter.
DBI connect('database=chaosLRdb;host="keep what is mentioned" ;port=5433','postgres',...)
That would be:
b.rstrip('\n')
If you want to strip space from each and every line, you might consider instead:
a.read().splitlines()
This will give you a list of lines, without the line end characters.
You can use CTE also like below.
With cte as
(select Activity, SUM(Amount) as "Total Amount 2009"
from Activities, Incomes
where Activities.UnitName = ? AND
Incomes.ActivityId = Activities.ActivityID
GROUP BY Activity
),
cte1 as
(select Activity, SUM(Amount) as "Total Amount 2008"
from Activities, Incomes2008
where Activities.UnitName = ? AND
Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activity
)
Select cte.Activity, cte.[Total Amount 2009] ,cte1.[Total Amount 2008]
from cte join cte1 ON cte.ActivityId = cte1.ActivityID
WHERE a.UnitName = ?
ORDER BY cte.Activity
In xml:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleInverse"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_margin="@dimen/dimen_10dp"
android:indeterminateTint="@{viewModel.getComplainStatusUpdate(position)}"
android:indeterminate="true"
android:indeterminateOnly="false"
android:max="100"
android:clickable="false"
android:indeterminateDrawable="@drawable/round_progress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
ViewModel:
fun getComplainStatusUpdate(position: Int):Int{
val list = myAllComplainList!!.getValue()
if (list!!.get(position).complainStatus.equals("P")) {
// progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
// progressBar.setBackgroundResource(R.drawable.circle_shape)
return Color.RED
} else if (list!!.get(position).complainStatus.equals("I")) {
return Color.GREEN
} else {
return Color.GREEN
}
return Color.CYAN
}
Pseudo classes like :hover
never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover
rule.
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
Please look at the weightSum of LinearLayout and the layout_weight of each View. android:weightSum="4" android:layout_weight="2" android:layout_weight="2" Their layout_height are both 0px, but I am not sure it is relevan
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="4">
<fragment android:name="com.example.SettingFragment"
android:id="@+id/settingFragment"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="2"
/>
<Button
android:id="@+id/dummy_button"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="2"
android:text="DUMMY"
/>
</LinearLayout>
%RANDOM% gives you a random number between 0 and 32767.
You can control the number's range with:
set /a num=%random% %%100
- will produce number between 0~99.
This one:
set /a num=%random% %%100 +1
- will produce number between 1~100.
Vikas answer works perfectly for me, here I also add support for the delay (show / hide).
var popover = $('#example');
var options = {
animation : true,
html: true,
trigger: 'manual',
placement: 'right',
delay: {show: 500, hide: 100}
};
popover
.popover(options)
.on("mouseenter", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.is(":hover")) {
popover.popover("show");
popover.siblings(".popover").on("mouseleave", function () {
$(t).popover('hide');
});
}
}, options.delay.show);
})
.on("mouseleave", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
$(t).popover("hide")
}
}, options.delay.hide);
});
Also please pay attention I changed:
if (!$(".popover:hover").length) {
with:
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
so that it references exactly at that opened popover, and not any other (since now, through the delay, more than 1 could be open at the same time)
--Kotlin Version
package com.ps.salestrackingapp.Services
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.util.Log
class LocationService : Service() {
private var mLocationManager: LocationManager? = null
var mLocationListeners = arrayOf(LocationListener(LocationManager.GPS_PROVIDER), LocationListener(LocationManager.NETWORK_PROVIDER))
class LocationListener(provider: String) : android.location.LocationListener {
internal var mLastLocation: Location
init {
Log.e(TAG, "LocationListener $provider")
mLastLocation = Location(provider)
}
override fun onLocationChanged(location: Location) {
Log.e(TAG, "onLocationChanged: $location")
mLastLocation.set(location)
Log.v("LastLocation", mLastLocation.latitude.toString() +" " + mLastLocation.longitude.toString())
}
override fun onProviderDisabled(provider: String) {
Log.e(TAG, "onProviderDisabled: $provider")
}
override fun onProviderEnabled(provider: String) {
Log.e(TAG, "onProviderEnabled: $provider")
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
Log.e(TAG, "onStatusChanged: $provider")
}
}
override fun onBind(arg0: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e(TAG, "onStartCommand")
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onCreate() {
Log.e(TAG, "onCreate")
initializeLocationManager()
try {
mLocationManager!!.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
mLocationListeners[1])
} catch (ex: java.lang.SecurityException) {
Log.i(TAG, "fail to request location update, ignore", ex)
} catch (ex: IllegalArgumentException) {
Log.d(TAG, "network provider does not exist, " + ex.message)
}
try {
mLocationManager!!.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
mLocationListeners[0])
} catch (ex: java.lang.SecurityException) {
Log.i(TAG, "fail to request location update, ignore", ex)
} catch (ex: IllegalArgumentException) {
Log.d(TAG, "gps provider does not exist " + ex.message)
}
}
override fun onDestroy() {
Log.e(TAG, "onDestroy")
super.onDestroy()
if (mLocationManager != null) {
for (i in mLocationListeners.indices) {
try {
mLocationManager!!.removeUpdates(mLocationListeners[i])
} catch (ex: Exception) {
Log.i(TAG, "fail to remove location listners, ignore", ex)
}
}
}
}
private fun initializeLocationManager() {
Log.e(TAG, "initializeLocationManager")
if (mLocationManager == null) {
mLocationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
}
companion object {
private val TAG = "BOOMBOOMTESTGPS"
private val LOCATION_INTERVAL = 1000
private val LOCATION_DISTANCE = 0f
}
}
While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.
Add a parameter to your app.run()
. By default it runs on localhost
, change it to app.run(host= '0.0.0.0')
to run on all your machine's IP addresses. 0.0.0.0
is a special value, you'll need to navigate to the actual IP address.
Documented on the Flask site under "Externally Visible Server" on the Quickstart page:
Externally Visible Server
If you run the server you will notice that the server is only available from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have debug disabled or trust the users on your network, you can make the server publicly available.
Just change the call of the
run()
method to look like this:
app.run(host='0.0.0.0')
This tells your operating system to listen on a public IP.
Environment variables can be used to set spring properties as described in the documentation. So, to set the active profiles (spring.profiles.active
) you can use the following code on Unix systems:
SPRING_PROFILES_ACTIVE=test gradle clean bootRun
And on Windows you can use:
SET SPRING_PROFILES_ACTIVE=test
gradle clean bootRun
jQuery is about 40 times SLOWER, please do not use jQuery for that simple task.
function htmlToPlaintext(text) {
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
}
usage :
var plain_text = htmlToPlaintext( your_html );
angular.module('myApp.filters', []).
filter('htmlToPlaintext', function() {
return function(text) {
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
}
);
use :
<div>{{myText | htmlToPlaintext}}</div>
The first thing you tried seems to work fine. Here is an example program.
Press the "Start" button at the top of this page to run it to see the output yourself.
import java.util.Arrays;
public class Foo{
public static void main(String[] args) {
String [] stringArray = {"ab", "aB", "c", "0", "2", "1Ad", "a10"};
orderedGuests(stringArray);
}
public static void orderedGuests(String[] hotel)
{
Arrays.sort(hotel);
System.out.println(Arrays.toString(hotel));
}
}
You Can Try this
import ftplib
path = 'pub/Health_Statistics/NCHS/nhanes/2001-2002/'
filename = 'L28POC_B.xpt'
ftp = ftplib.FTP("Server IP")
ftp.login("UserName", "Password")
ftp.cwd(path)
ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
ftp.quit()
It took me more than 4 hours to fix this problem. I followed the guide from http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android
I'm using Android Studio (Eclipse with ADT could not work properly because of the build problem).
Solution that worked for me:
I put the /assets/www/index.html under app/src/main/assets directory. (take care AndroidStudio has different perspectives like Project or Android)
use super.loadUrl("file:///android_asset/www/index.html"); instead of super.loadUrl("file:///android_assets/www/index.html"); (no s)
Here is a full example which reads the contents of the given web page.
The web page is read from an HTML form. We use standard InputStream
classes, but it could be done more easily with JSoup library.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
These are the Maven dependencies. We use Apache Commons library to validate URL strings.
package com.zetcode.web;
import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
String page = request.getParameter("webpage");
String content = new WebPageReader().setWebPageName(page).getWebPageContent();
ServletOutputStream os = response.getOutputStream();
os.write(content.getBytes(StandardCharsets.UTF_8));
}
}
The ReadWebPage
servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader
.
package com.zetcode.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;
public class WebPageReader {
private String webpage;
private String content;
public WebPageReader setWebPageName(String name) {
webpage = name;
return this;
}
public String getWebPageContent() {
try {
boolean valid = validateUrl(webpage);
if (!valid) {
content = "Invalid URL; use http(s)://www.example.com format";
return content;
}
URL url = new URL(webpage);
try (InputStream is = url.openStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8))) {
content = br.lines().collect(
Collectors.joining(System.lineSeparator()));
}
} catch (IOException ex) {
content = String.format("Cannot read webpage %s", ex);
Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
}
return content;
}
private boolean validateUrl(String webpage) {
UrlValidator urlValidator = new UrlValidator();
return urlValidator.isValid(webpage);
}
}
WebPageReader
validates the URL and reads the contents of the web page.
It returns a string containing the HTML code of the page.
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
</head>
<body>
<form action="ReadWebPage">
<label for="page">Enter a web page name:</label>
<input type="text" id="page" name="webpage">
<button type="submit">Submit</button>
</form>
</body>
</html>
Finally, this is the home page containing the HTML form. This is taken from my tutorial about this topic.
War -
distribute Java-based web applications. A WAR has the same file structure as a JAR file, which is a single compressed file that contains multiple files bundled inside it.
Jar -
The .jar files contain libraries, resources and accessories files like property files.
WAR files are used to combine JSPs, servlets, Java class files, XML files, javascript libraries, JAR libraries, static web pages, and any other resources needed to run the application.
Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.
Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).
"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.
The issue is with the h1
header margin. You need to try this:
h1 {
margin-top:0;
}
Hope this helps someone in the future. My problem was that I was following the same tutorial as the OP to enable global CORS. However, I also set an Action specific CORS rule in my AccountController.cs file:
[EnableCors(origins: "", headers: "*", methods: "*")]
and was getting errors about the origin cannot be null or empty string. BUT the error was happening in the Global.asax.cs file of all places. Solution is to change it to:
[EnableCors(origins: "*", headers: "*", methods: "*")]
notice the * in the origins? Missing that was what was causing the error in the Global.asax.cs file.
Hope this helps someone.
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
I use current milliseconds with random numbers
i.e
Random random=new Random();
String ext = ".jpeg";
File dir = new File("/home/pregzt");
String name = String.format("%s%s",System.currentTimeMillis(),random.nextInt(100000)+ext);
File file = new File(dir, name);
for ( i = 0; i < total.length; i++ );
^-- remove the semi-colon here
With this semi-colon, the loop loops until i == total.length
, doing nothing, and then what you thought was the body of the loop is executed.
Try this !!!. This will solve your problem for sure!
Method 1 -
Step 1 - Go to 'Environmental Variables'.
Step 2 - Find PATH variable and add the path to your PHP folder.
Step 3 - For 'XAMPP' users put 'C:\xampp\php' and 'WAMP' users put 'C:\wamp64\bin\php\php7.1.9' ) and save.
Method 2-
In VS Code
File -> Preferences -> Settings.
Open 'settings.json' file and put the below codes.
If you are using WAMP put this code and Save.
"php.validate.executablePath": "C:\\wamp64\\bin\\php\\php7.1.9\\php.exe",
"php.executablePath": "C:\\wamp64\\bin\\php\\php7.1.9\\php.exe"
If you are using XAMPP put this code and Save.
"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"
Note - Replace php7.1.9 with your PHP version.
At the beginning of your file you set raw_input
to 0. Do not do this, at it modifies the built-in raw_input()
function. Therefore, whenever you call raw_input()
, it is essentially calling 0()
, which raises the error. To remove the error, remove the first line of your code:
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I know this is not really an answer to the question, but it might be worth knowing for someone searching this post. It is also possible to install a Maven repository proxy like nexus.
Your maven would be configured to contact the local Nexus proxy, and Nexus would then retrieve (and cache) the artifacts. It can be configured through a web interface and has support for (http) proxies).
This can be an advantage, especially in a company setting, as artefacts are locally available and can be downloaded fast, and you are not that dependent on the availability of external Maven repositories anymore.
To link back to the question; with Nexus there is a nice GUI for the proxy configuration, and it needs to be done on one place only, and not for every developer.
Not tested but you can give a try. Tested and working. I hope you can play with AutoSizeMode
of DataGridViewColum
to achieve what you need.
Try setting
dataGridView1.DataSource = yourdatasource;<--set datasource before you set AutoSizeMode
//Set the following properties after setting datasource
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
This should work
You can change your UI culture to anything you want, but you should change the number separator like this:
CultureInfo info = new CultureInfo("fa-IR");
info.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = info;
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
With this, your strings converts like this: "12.49" instead of "12,49" or "12/49"
You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.
The HTTP spec and Firebug were very useful for me when I had to do it for my homework.
Good luck with yours. :)
Using the trick
Attribute VB_PredeclaredId = True
I found another more compact way:
Option Explicit
Option Base 0
Option Compare Binary
Private v_cBox As ComboBox
'
' Class creaor
Public Function New_(ByRef cBox As ComboBox) As ComboBoxExt_c
If Me Is ComboBoxExt_c Then
Set New_ = New ComboBoxExt_c
Call New_.New_(cBox)
Else
Set v_cBox = cBox
End If
End Function
As you can see the New_ constructor is called to both create and set the private members of the class (like init) only problem is, if called on the non-static instance it will re-initialize the private member. but that can be avoided by setting a flag.
public string GetXMLAsString(XmlDocument myxml)
{
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
myxml.WriteTo(xmlTextWriter);
return stringWriter.ToString();
}
}
}
In order to access the data from a ReadableStream
you need to call one of the conversion methods (docs available here).
As an example:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
// The response is a Response instance.
// You parse the data into a useable format using `.json()`
return response.json();
}).then(function(data) {
// `data` is the parsed version of the JSON returned from the above endpoint.
console.log(data); // { "userId": 1, "id": 1, "title": "...", "body": "..." }
});
EDIT: If your data return type is not JSON or you don't want JSON then use text()
As an example:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
return response.text();
}).then(function(data) {
console.log(data); // this will be a string
});
Hope this helps clear things up.
Different database systems have different names for the same type of index, so be careful with this. For example, what SQL Server and Sybase call "clustered index" is called in Oracle an "index-organised table".
There is a better solution to this answer that is more Angular based.
Save your string in a variable in the .ts file
MyStrings = ["one","two","three"]
In the html file use *ngFor.
<div class="one" *ngFor="let string of MyStrings; let i = index">
<div class="two">{{string}}</div>
</div>
if you want to dynamically insert the div element, just push more strings into the MyStrings array
myFunction(nextString){
this.MyString.push(nextString)
}
this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.
For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.
One way to address this is to create a custom manual colour scale as follows:
#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)
#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)
and then add the color scale onto the plot as needed:
#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale
#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale
The first plot looks like this:
and the second plot looks like this:
This way you don't need to remember or check each data frame to see that they have the appropriate levels.
@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
I've experienced the same problem. One of the responds to your question led me to the following idea (which worked eventually). I use Python 3.7.
# just an example
def func(): # define a function
func.y = 4 # here y is a local variable, which I want to access; func.y defines
# a method for my example function which will allow me to access
# function's local variable y
x = func.y + 8 # this is the main task for the function: what it should do
return x
func() # now I'm calling the function
a = func.y # I put it's local variable into my new variable
print(a) # and print my new variable
Then I launch this program in Windows PowerShell and get the answer 4. Conclusion: to be able to access a local function's variable one might add the name of the function and a dot before the name of the local variable (and then, of course, use this construction for calling the variable both in the function's body and outside of it). I hope this will help.
To understand sed
command, we have to build it step by step.
Here is your original text
user@linux:~$ echo "Here is a String"
Here is a String
user@linux:~$
Let's try to remove Here
string with s
ubstition option in sed
user@linux:~$ echo "Here is a String" | sed 's/Here //'
is a String
user@linux:~$
At this point, I believe you would be able to remove String
as well
user@linux:~$ echo "Here is a String" | sed 's/String//'
Here is a
user@linux:~$
But this is not your desired output.
To combine two sed commands, use -e
option
user@linux:~$ echo "Here is a String" | sed -e 's/Here //' -e 's/String//'
is a
user@linux:~$
Hope this helps
In order to support refactoring correctly (rename class), then you should use either:
MyClass.class.getName(); // full name with package
or (thanks to @James Van Huis):
MyClass.class.getSimpleName(); // class name and no more
import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below
dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")
for filename in os.listdir(dir_src):
if filename.endswith('.txt'):
shutil.copy( dir_src + filename, dir_dst)
print(filename)
Very informative answer from @stej, but here is a short answer: Among other options, you have 3 simple options to format [System.DateTime] stored in a variable:
Pass the variable to the Get-Date cmdlet:
Get-Date -Format "HH:mm" $date
Use toString() method:
$date.ToString("HH:mm")
Use Composite formatting:
"{0:HH:mm}" -f $date
You may append the 3 bytes to the file before exporting, it works for me . Before doing that system only work in Windows and HP -UX but failed in Linux.
FileOutputStream fStream = new FileOutputStream( f );
final byte[] bom = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
OutputStreamWriter writer = new OutputStreamWriter( fStream, "UTF8" );
fStream.write( bom );
Have a UTF-8 BOM (3 bytes, hex EF BB BF) at the start of the file. Otherwise Excel will interpret the data according to your locale's default encoding (e.g. cp1252) instead of utf-8
Generating CSV file for Excel, how to have a newline inside a value
If you have 2 arrays need to be merged based on values even its in different order
let arr1 = [
{ id:"1", value:"this", other: "that" },
{ id:"2", value:"this", other: "that" }
];
let arr2 = [
{ id:"2", key:"val2"},
{ id:"1", key:"val1"}
];
you can do like this
const result = arr1.map(item => {
const obj = arr2.find(o => o.id === item.id);
return { ...item, ...obj };
});
console.log(result);
Once you have your key stored in a PEM file, you can read it back easily using PemObject and PemReader classes provided by BouncyCastle, as shown in this this tutorial.
Create a PemFile class that encapsulates file handling:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
public class PemFile {
private PemObject pemObject;
public PemFile(String filename) throws FileNotFoundException, IOException {
PemReader pemReader = new PemReader(new InputStreamReader(
new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
} finally {
pemReader.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
Then instantiate private and public keys as usual:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Main {
protected final static Logger LOGGER = Logger.getLogger(Main.class);
public final static String RESOURCES_DIR = "src/main/resources/rsa-sample/";
public static void main(String[] args) throws FileNotFoundException,
IOException, NoSuchAlgorithmException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
LOGGER.info("BouncyCastle provider added.");
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
try {
PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
+ "id_rsa");
LOGGER.info(String.format("Instantiated private key: %s", priv));
PublicKey pub = generatePublicKey(factory, RESOURCES_DIR
+ "id_rsa.pub");
LOGGER.info(String.format("Instantiated public key: %s", pub));
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private static PrivateKey generatePrivateKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return factory.generatePrivate(privKeySpec);
}
private static PublicKey generatePublicKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
return factory.generatePublic(pubKeySpec);
}
}
Hope this helps.
The best time for Kruskal's is O(E logV). For Prim's using fib heaps we can get O(E+V lgV). Therefore on a dense graph, Prim's is much better.
Quick little solution in pure js, no plugins needed:
function replaceQueryParam(param, newval, search) {
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
Call it like this:
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
Or, if you want to stay on the same page and replace multiple params:
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
edit, thanks Luke: To remove the parameter entirely, pass false
or null
for the value: replaceQueryParam('rows', false, params)
. Since 0
is also falsy, specify '0'
.
numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)
This would work, if your are trying to Sum up a list.
FYI Numpy 1.15 (release date pending) will include a context manager for setting print options locally. This means that the following will work the same as the corresponding example in the accepted answer (by unutbu and Neil G) without having to write your own context manager. E.g., using their example:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
Using vlines
:
import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p = plot(x, y, "o")
vlines(70,100,250)
The basic call signatures are:
vlines(x, ymin, ymax)
hlines(y, xmin, xmax)
var nameCheckBoxList = "myCheckListName";
var selectedValues = $("[name=" + nameCheckBoxList + "]:checked").map(function(){return this.value;});
Other type of format :
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
The reason why you always got True
has already been given, so I'll just offer another suggestion:
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
Another trick: you can alleviate the possible memory problems by using mmap.mmap()
to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory):
import mmap
with open('example.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
print('true')
NOTE: in python 3, mmaps behave like bytearray
objects rather than strings, so the subsequence you look for with find()
has to be a bytes
object rather than a string as well, eg. s.find(b'blabla')
:
#!/usr/bin/env python3
import mmap
with open('example.txt', 'rb', 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(b'blabla') != -1:
print('true')
You could also use regular expressions on mmap
e.g., case-insensitive search: if re.search(br'(?i)blabla', s):
You need to select the entire column where you have the dates, so click the "text to columns" button, and select delimited > uncheck all the boxes and go until you click the button finish.
This will make the cell format and then the values will be readed as date.
Hope it will helped.
I also had a similar issue. Someone might find what worked for me helpful.
Machine is running Ubuntu 16.04 and has Docker CE. After looking through the answers and links provided here, especially from the link from the Docker website given by Elliot Beach, I opened my /etc/apt/sources.list and examined it.
The file had both deb [arch=amd64] https://download.docker.com/linux/ubuntu (lsb_release -cs) stable
and deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
.
Since the second one was what was needed, I simply commented out the first, saved the document and now the issue is fixed. As a test, I went back into the same document, removed the comment sign and ran sudo apt-get update
again. The issue returned when I did that.
So to recap : not only did I have my parent Ubuntu distribution name as stated on the Docker website but I also commented out the line still containing (lsb_release -cs).
As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the file and there is nothing left to read. You can use file.tell()
to see where in the file the pointer is and file.seek
to set the pointer. For example:
>>> file = open('myfile.txt')
>>> file.tell()
0
>>> file.readline()
'one\n'
>>> file.tell()
4L
>>> file.readline()
'2\n'
>>> file.tell()
6L
>>> file.seek(4)
>>> file.readline()
'2\n'
Also, you should know that file.readlines()
reads the whole file and stores it as a list. That's useful to know because you can replace:
for line in file.readlines():
#do stuff
file.seek(0)
for line in file.readlines():
#do more stuff
with:
lines = file.readlines()
for each_line in lines:
#do stuff
for each_line in lines:
#do more stuff
You can also iterate over a file, one line at a time, without holding the whole file in memory (this can be very useful for very large files) by doing:
for line in file:
#do stuff
Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.
Just use this: ExtractFilePath(your_path_file_name)
I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.
Maybe you don't necessary need reflection for that -- here is a plain OO design that might solve your problem:
Validation
which expose a method validate
which checks the fields and return whatever is appropriate. Validation
and check that easily.I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.
If you use Java and spring MVC you just need to add the following annotation to your method returning your page :
@CrossOrigin(origins = "*")
"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.
You should use hyphens in a crawlable web application URL. Why? Because the hyphen separates words (so that a search engine can index the individual words), and is not a word character. Underscore is a word character, meaning it should be considered part of a word.
Double-click this in Chrome: camelCase
Double-click this in Chrome: under_score
Double-click this in Chrome: hyphen-ated
See how Chrome (I hear Google makes a search engine too) only thinks one of those is two words?
camelCase
and underscore
also require the user to use the shift key, whereas hyphenated
does not.
So if you should use hyphens in a crawlable web application, why would you bother doing something different in an intranet application? One less thing to remember.
Update to Tomcat 7.0.58 (or newer).
See: https://bz.apache.org/bugzilla/show_bug.cgi?id=57173#c16
The performance improvement that triggered this regression has been reverted from from trunk, 8.0.x (for 8.0.16 onwards) and 7.0.x (for 7.0.58 onwards) and will not be reapplied.
I would use two classes. Keep your test class and add a second class called testhover which you only add to those you want to hover - alongside the test class. This isn't directly what you asked but without more context it feels like the best solution and is possibly the cleanest and simplest way of doing it.
Example:
.test { border: 0px; }_x000D_
.testhover:hover { border: 1px solid red; }
_x000D_
<div class="test"> blah </div>_x000D_
<div class="test"> blah </div>_x000D_
<div class="test testhover"> blah </div>
_x000D_
$duplicate_query=mysql_query("SELECT * FROM student") or die(mysql_error());
$duplicate=mysql_num_rows($duplicate_query);
if($duplicate==0)
{
while($value=mysql_fetch_array($duplicate_query)
{
if(($value['name']==$name)&& ($value['email']==$email)&& ($value['mobile']==$mobile)&& ($value['resume']==$resume))
{
echo $query="INSERT INTO student(name,email,mobile,resume)VALUES('$name','$email','$mobile','$resume')";
$res=mysql_query($query);
if($query)
{
echo "Success";
}
else
{
echo "Error";
}
else
{
echo "Duplicate Entry";
}
}
}
}
else
{
echo "Records Already Exixts";
}
Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object
and are what you are using, and invoke their base class through super()
, e.g.
class X(object):
def __init__(self, x):
pass
def doit(self, bar):
pass
class Y(X):
def __init__(self):
super(Y, self).__init__(123)
def doit(self, foo):
return super(Y, self).doit(foo)
Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.
For completeness sake, old-style classes call base methods explicitly using the base class, i.e.
def doit(self, foo):
return X.doit(self, foo)
But since you shouldn't be using old-style anymore, I wouldn't care about this too much.
Python 3 only knows about new-style classes (no matter if you derive from object
or not).
Here is an alternative that worked for me:
$('div#somediv').css({'width': '70%'});
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
In VB.NET, you can apply multiple conditions even if the other conditions don't apply to the Select parameter. See below:
Select Case parameter
Case "userID"
' does something here.
Case "packageID"
' does something here.
Case "mvrType" And otherFactor
' does something here.
Case Else
' does some processing...
End Select
Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/
edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/
The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/
solution :
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
In Swift 2+ for me works:
I have UITabBarViewController in storyboard and I had selectedIndex property like this:
But I delete it, and add in my viewDidLoad method of my initial class, like this:
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.selectedIndex = 2
}
I hope I can help someone.
in C# 6 the recommended approach is to use Exception Filters, here is an example:
try
{
throw new OverflowException();
}
catch(Exception e ) when ((e is DivideByZeroException) || (e is OverflowException))
{
// this will execute iff e is DividedByZeroEx or OverflowEx
Console.WriteLine("E");
}
There are different ways to do that.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],
'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })
def getMonth(s): return s.split("-")[1] def getDay(s): return s.split("-")[0] def getYear(s): return s.split("-")[2] def getYearMonth(s): return s.split("-")[1]+"-"+s.split("-")[2]
year
, month
, day
and 'yearMonth
'. In your case, you need one of both. You can group using two columns 'year','month'
or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x)) df['month']= df['Date'].apply(lambda x: getMonth(x)) df['day']= df['Date'].apply(lambda x: getDay(x)) df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
3 20-Jan-14 25 15 14 Jan 20 Jan-14
4 21-Feb-14 60 80 14 Feb 21 Feb-14
In this case, we are grouping by two columns:
for key,g in df.groupby(['year','month']): print key,g
Output:
('13', 'Jun') Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
('13', 'Aug') Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
('14', 'Jan') Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
('14', 'Feb') Date abc xyz year month day YearMonth
In this case, we are grouping by one column:
for key,g in df.groupby(['YearMonth']): print key,g
Output:
Jun-13 Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
Aug-13 Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
Jan-14 Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
Feb-14 Date abc xyz year month day YearMonth
4 21-Feb-14 60 80 14 Feb 21 Feb-14
get_group
print df.groupby(['YearMonth']).get_group('Jun-13')
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
get_group
. This hack would help to filter values and get the grouped values.This also would give the same result.
print df[df['YearMonth']=='Jun-13']
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
You can select list of abc
or xyz
values during Jun-13
print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values
Output:
[100 -20] #abc values
[200 50] #xyz values
You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.
for x in set(df.YearMonth):
print df[df['YearMonth']==x].abc.values
print df[df['YearMonth']==x].xyz.values
I recommend also to check this answer as well.
$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();
In this way you can also achieve in zend framework 2 also. Thanks.
ALTER TABLE mytable ALTER COLUMN mycolumn newtype
Beware of the limitations of the ALTER COLUMN clause listed in the article
Thanks to galloglass' answer. The code works great with Python 2.7. There is only one thing I want to metion. When read the manifest.mbdb file, you should use binary mode. Otherwise, not all content are read.
I also made some minor changes to make the code work with Python 3.4. Here is the code.
#!/usr/bin/env python
import sys
import hashlib
mbdx = {}
def getint(data, offset, intsize):
"""Retrieve an integer (big-endian) and new offset from the current offset"""
value = 0
while intsize > 0:
value = (value << 8) + data[offset]
offset = offset + 1
intsize = intsize - 1
return value, offset
def getstring(data, offset):
"""Retrieve a string and new offset from the current offset into the data"""
if chr(data[offset]) == chr(0xFF) and chr(data[offset + 1]) == chr(0xFF):
return '', offset + 2 # Blank string
length, offset = getint(data, offset, 2) # 2-byte length
value = data[offset:offset + length]
return value.decode(encoding='latin-1'), (offset + length)
def process_mbdb_file(filename):
mbdb = {} # Map offset of info in this file => file info
data = open(filename, 'rb').read() # 'b' is needed to read all content at once
if data[0:4].decode() != "mbdb": raise Exception("This does not look like an MBDB file")
offset = 4
offset = offset + 2 # value x05 x00, not sure what this is
while offset < len(data):
fileinfo = {}
fileinfo['start_offset'] = offset
fileinfo['domain'], offset = getstring(data, offset)
fileinfo['filename'], offset = getstring(data, offset)
fileinfo['linktarget'], offset = getstring(data, offset)
fileinfo['datahash'], offset = getstring(data, offset)
fileinfo['unknown1'], offset = getstring(data, offset)
fileinfo['mode'], offset = getint(data, offset, 2)
fileinfo['unknown2'], offset = getint(data, offset, 4)
fileinfo['unknown3'], offset = getint(data, offset, 4)
fileinfo['userid'], offset = getint(data, offset, 4)
fileinfo['groupid'], offset = getint(data, offset, 4)
fileinfo['mtime'], offset = getint(data, offset, 4)
fileinfo['atime'], offset = getint(data, offset, 4)
fileinfo['ctime'], offset = getint(data, offset, 4)
fileinfo['filelen'], offset = getint(data, offset, 8)
fileinfo['flag'], offset = getint(data, offset, 1)
fileinfo['numprops'], offset = getint(data, offset, 1)
fileinfo['properties'] = {}
for ii in range(fileinfo['numprops']):
propname, offset = getstring(data, offset)
propval, offset = getstring(data, offset)
fileinfo['properties'][propname] = propval
mbdb[fileinfo['start_offset']] = fileinfo
fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
id = hashlib.sha1(fullpath.encode())
mbdx[fileinfo['start_offset']] = id.hexdigest()
return mbdb
def modestr(val):
def mode(val):
if (val & 0x4):
r = 'r'
else:
r = '-'
if (val & 0x2):
w = 'w'
else:
w = '-'
if (val & 0x1):
x = 'x'
else:
x = '-'
return r + w + x
return mode(val >> 6) + mode((val >> 3)) + mode(val)
def fileinfo_str(f, verbose=False):
if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
if (f['mode'] & 0xE000) == 0xA000:
type = 'l' # symlink
elif (f['mode'] & 0xE000) == 0x8000:
type = '-' # file
elif (f['mode'] & 0xE000) == 0x4000:
type = 'd' # dir
else:
print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
type = '?' # unknown
info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" %
(type, modestr(f['mode'] & 0x0FFF), f['userid'], f['groupid'], f['filelen'],
f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
for name, value in f['properties'].items(): # extra properties
info = info + ' ' + name + '=' + repr(value)
return info
verbose = True
if __name__ == '__main__':
mbdb = process_mbdb_file(
r"Manifest.mbdb")
for offset, fileinfo in mbdb.items():
if offset in mbdx:
fileinfo['fileID'] = mbdx[offset]
else:
fileinfo['fileID'] = "<nofileID>"
print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
print(fileinfo_str(fileinfo, verbose))
To change the title font size, use the following example
title('mytitle','FontSize',12);
to the change the graph axes label font size, do the following
axes('FontSize',24);
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
If you want to change settings in the launcher, change icon size, or grid size just hold down on an empty part of your home screen. Tap the three Dots and there you go.
From https://forums.oneplus.net/threads/how-to-change-icon-and-grid-size-trebuchet-settings.84820/
When configuring the phone for first time I saw something about a grid somewhere, but couldn't find it again. Luckily I found the answer on the link above.
TL;DR
Summary; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use multipart/form-data
. Otherwise, use application/x-www-form-urlencoded
.
The MIME types you mention are the two Content-Type
headers for HTTP POST requests that user-agents (browsers) must support. The purpose of both of those types of requests is to send a list of name/value pairs to the server. Depending on the type and amount of data being transmitted, one of the methods will be more efficient than the other. To understand why, you have to look at what each is doing under the covers.
For application/x-www-form-urlencoded
, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&
), and names are separated from values by the equals symbol (=
). An example of this would be:
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
According to the specification:
[Reserved and] non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character
That means that for each non-alphanumeric byte that exists in one of our values, it's going to take three bytes to represent it. For large binary files, tripling the payload is going to be highly inefficient.
That's where multipart/form-data
comes in. With this method of transmitting name/value pairs, each pair is represented as a "part" in a MIME message (as described by other answers). Parts are separated by a particular string boundary (chosen specifically so that this boundary string does not occur in any of the "value" payloads). Each part has its own set of MIME headers like Content-Type
, and particularly Content-Disposition
, which can give each part its "name." The value piece of each name/value pair is the payload of each part of the MIME message. The MIME spec gives us more options when representing the value payload -- we can choose a more efficient encoding of binary data to save bandwidth (e.g. base 64 or even raw binary).
Why not use multipart/form-data
all the time? For short alphanumeric values (like most web forms), the overhead of adding all of the MIME headers is going to significantly outweigh any savings from more efficient binary encoding.
Usually when you get this problem, it happens because a script is trying to reference an element that doesn't exist yet while the page is loading.
As richie mentioned: "The HTML parser will parse the HTML content from top to bottom..."
So you can add your JavaScript references to the bottom of the HTML file. This will not only improve performance; it will also ensure that all elements referenced in your script files have already been loaded by the HTML parser.
So you could have something like this:
<html>
<head>
<!-- Style sheet references and CSS definitions -->
</head>
<body>
<!-- HTML markup and other page content -->
<!-- JavaScript references. You could include jQuery here as well and do all your scripting here. -->
</body>
</html>
Open xCode can be exhausting if you do it everytime, so you need to add this flag :
OR if you have build.json file at the root of your project, you must add this lines:
{
"ios": {
"debug": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
},
"release": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
}
}
}
Hope this will help in the future
you can add a condition to the after_update
like so:
class SomeModel < ActiveRecord::Base
after_update :send_notification, if: :published_changed?
...
end
there's no need to add a condition within the send_notification
method itself.
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output