The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.
This is more or less what it should look like (no libcurl available here to test)
#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://localhost/aaa.txt";
char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
I use python setup.py build_ext -R/usr/local/lib -I/usr/local/include/libcalg-1.0
and the compiled .so file is under the build folder.
you can type python setup.py --help build_ext
to see the explanations of -R and -I
You can make you request headers by yourself using:
// open a socket connection on port 80
$fp = fsockopen($host, 80);
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
// close the socket connection:
fclose($fp);
Like writen on how make request
In my case, HTTPS protocol was not supported by libcurl at the first place. To find out which protocols are supported and which are not, I checked the curl version using command:
curl --version
It provided information as follows:
curl 7.50.3 (x86_64-apple-darwin15.6.0) libcurl/7.50.3 SecureTransport zlib/1.2.5
Protocols: dict file ftp ftps gopher http imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile NTLM NTLM_WB SSL libz UnixSockets
where https protocol happens to be not supported.
Then I re-installed curl and installed it using the following commands(after unpacked):
./configure --with-darwinssl (enable ssl communication in mac) make make test sudo make install
And after several minutes of work, Problems resolved!
Then I re-run the curl version command, it showed:
curl 7.50.3 (x86_64-apple-darwin15.6.0) libcurl/7.50.3 SecureTransport zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile NTLM NTLM_WB SSL libz UnixSockets
HTTPS protocol showed up!
Finally, a useful site to refer when you run into curl problems.
https://curl.haxx.se/docs/install.html
in the directory that you want to donwload:
git init
git remote add origin -f repoUrl // folder url
touch .git/info/sparse-checkout
git pull origin master
only 4 lines of code
You can use the isNaN function to determine if a value does not convert to a number. Example as below:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x))
{
alert("Must input numbers");
return false;
}
}
Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.
For example:
round(200.3456, 2); // returns 200.35
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)
) or large integer part (e.g. round(90080070060.1d, 9)
). Thanks to Sloin for pointing this out.
I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.
(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Note that HALF_UP
is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.
Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()
Always remember that floating point representations using float
and double
are inexact.
For example, consider these expressions:
999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001
For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:
System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));
Some excellent further reading on the topic:
float
and double
if exact answers are required" in Effective Java (2nd ed) by Joshua BlochIf you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.
Specifically, note that round(200, 0)
returns 200.0
. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).
Try to surround strings
(hoot
, story
, article
) with quotes '
:
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hoot' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//different template with story data
</div>
<div ng-if="data.type == 'article' ">
//different template with article data
</div>
</div>
Change the names of your inputs:
<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum" />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />
Then:
$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".
Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.
If you want to add it directly in the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_centerHorizontal="true" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
just use this:
int index = 2;
boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();
In curl request add time out 0 so its infinite time set like CURLOPT_TIMEOUT set 0
It's a link that links to nowhere essentially (it just adds "#" onto the URL). It's used for a number of different reasons. For instance, if you're using some sort of JavaScript/jQuery and don't want the actual HTML to link anywhere.
It's also used for page anchors, which is used to redirect to a different part of the page.
We can do this by setting out variable of System class in the following way
System.setOut(new PrintStream(new FileOutputStream("Path to output file"))). Also You need to close or flush 'out'(System.out.close() or System.out.flush()) variable so that you don't end up missing some output.
Source : http://xmodulo.com/how-to-save-console-output-to-file-in-eclipse.html
I faced the same problem. I hope you have installed from here and have also done pip install pytesseract
.
If everything is fine you should see that the path C:\Program Files (x86)\Tesseract-OCR where tesseract.exe
is available.
Adding Path variable did not helped me, I actually added new variable with name tesseract
in environment variables with a value of C:\Program Files (x86)\Tesseract-OCR\tesseract.exe
.
Typing tesseract
in the command line should now work as expected by giving you usage informations. You can now use pytesseract
as such (don't forget to restart your python kernel before running this!):
import pytesseract
from PIL import Image
value=Image.open("text_image.png")
text = pytesseract.image_to_string(value, config='')
print("text present in images:",text)
enjoy!
If your objects only contain fields (no methods), this works:
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
This actually also works when objects have methods. (tested with PHP 5.3 and 5.6)
Make use of brackets /^\d{2}[.-/]\d{2}[.-/]\d{4}$/
http://download.oracle.com/javase/tutorial/essential/regex/char_classes.html
Starting in Django 1.2 RC1, if you're using the Django admin date picker widge trick, the following has to be added to your template, or you'll see the calendar icon url being referenced through "/missing-admin-media-prefix/".
{% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>
The principal is the Random Class constructed with the same seed will generate the same pattern of numbers every time.
Perhaps this is lame but you can also just point them both at some external object:
var cities = [];
function ParentCtrl() {
var vm = this;
vm.cities = cities;
vm.cities[0] = 'Oakland';
}
function ChildCtrl($scope) {
var vm = this;
vm.cities = cities;
}
The benefit here is that edits in ChildCtrl now propogate back to the data in the parent.
Great question!
There are many websites and free web apps implemented in PHP that run on Apache, lots of people use it so you can mash up something pretty easy and besides, its a no-brainer way of serving static content. Node is fast, powerful, elegant, and a sexy tool with the raw power of V8 and a flat stack with no in-built dependencies.
I also want the ease/flexibility of Apache and yet the grunt and elegance of Node.JS, why can't I have both?
Fortunately with the ProxyPass directive in the Apache httpd.conf
its not too hard to pipe all requests on a particular URL to your Node.JS application.
ProxyPass /node http://localhost:8000
Also, make sure the following lines are NOT commented out so you get the right proxy and submodule to reroute http requests:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
Then run your Node app on port 8000!
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Apache!\n');
}).listen(8000, '127.0.0.1');
Then you can access all Node.JS logic using the /node/
path on your url, the rest of the website can be left to Apache to host your existing PHP pages:
Now the only thing left is convincing your hosting company let your run with this configuration!!!
do this
sudo apt-get install php-curl
and restart server
sudo service apache2 restart
You can use the IAsyncResult and Action class/interface to achieve this.
public void TimeoutExample()
{
IAsyncResult result;
Action action = () =>
{
// Your code here
};
result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(10000))
Console.WriteLine("Method successful.");
else
Console.WriteLine("Method timed out.");
}
Quick and dirty:
LP
== Long Pointer. Just think pointer or char*
C
= Const, in this case, I think they mean the character string is a const, not the pointer being const.
STR
is string
the T
is for a wide character or char (TCHAR) depending on compile options.
If you identify a page that takes time to load, use SharePoint's Developer Dashboard to see which component takes time.
While using a std::map
is fine or using a 256-sized char table would be fine, you could save yourself an enormous amount of space agony by simply using an enum
. If you have C++11 features, you can use enum class
for strong-typing:
// First, we define base-pairs. Because regular enums
// Pollute the global namespace, I'm using "enum class".
enum class BasePair {
A,
T,
C,
G
};
// Let's cut out the nonsense and make this easy:
// A is 0, T is 1, C is 2, G is 3.
// These are indices into our table
// Now, everything can be so much easier
BasePair Complimentary[4] = {
T, // Compliment of A
A, // Compliment of T
G, // Compliment of C
C, // Compliment of G
};
Usage becomes simple:
int main (int argc, char* argv[] ) {
BasePair bp = BasePair::A;
BasePair complimentbp = Complimentary[(int)bp];
}
If this is too much for you, you can define some helpers to get human-readable ASCII characters and also to get the base pair compliment so you're not doing (int)
casts all the time:
BasePair Compliment ( BasePair bp ) {
return Complimentary[(int)bp]; // Move the pain here
}
// Define a conversion table somewhere in your program
char BasePairToChar[4] = { 'A', 'T', 'C', 'G' };
char ToCharacter ( BasePair bp ) {
return BasePairToChar[ (int)bp ];
}
It's clean, it's simple, and its efficient.
Now, suddenly, you don't have a 256 byte table. You're also not storing characters (1 byte each), and thus if you're writing this to a file, you can write 2 bits per Base pair instead of 1 byte (8 bits) per base pair. I had to work with Bioinformatics Files that stored data as 1 character each. The benefit is it was human-readable. The con is that what should have been a 250 MB file ended up taking 1 GB of space. Movement and storage and usage was a nightmare. Of coursse, 250 MB is being generous when accounting for even Worm DNA. No human is going to read through 1 GB worth of base pairs anyhow.
Swift
let indexpath = IndexPath(row: 0, section: 0)
if let cell = tableView.cellForRow(at: indexPath) as? <UITableViewCell or CustomCell> {
cell.backgroundColor = UIColor.red
}
If the cardinality of items doesn't matter (meaning: repeated elements are considered as one), then there is a way to do this without having to sort:
boolean result = new HashSet<>(listA).equals(new HashSet<>(listB));
This will create a Set
out of each List
, and then use HashSet
's equals
method which (of course) disregards ordering.
If cardinality matters, then you must confine yourself to facilities provided by List
; @jschoen's answer would be more fitting in that case.
Here's what I do:
Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.
These are the values from Bootstrap3:
/* Extra Small */
@media(max-width:767px){}
/* Small */
@media(min-width:768px) and (max-width:991px){}
/* Medium */
@media(min-width:992px) and (max-width:1199px){}
/* Large */
@media(min-width:1200px){}
The easiest way I've found to do this is:
<ComboBox Name="MyComboBox"
IsEditable="True"
IsReadOnly="True"
Text="-- Select Team --" />
You'll obviously need to add your other options, but this is probably the simplest way to do it.
There is however one downside to this method which is while the text inside your combo box will not be editable, it is still selectable. However, given the poor quality and complexity of every alternative I've found to date, this is probably the best option out there.
You shouldn't create jquery objects for each cell and row. Try this:
function responseHandler(response)
{
var c = [];
$.each(response, function(i, item) {
c.push("<tr><td>" + item.rank + "</td>");
c.push("<td>" + item.content + "</td>");
c.push("<td>" + item.UID + "</td></tr>");
});
$('#records_table').html(c.join(""));
}
I found using CSS inside my html inside my php did the trick for me.
<?php
echo '<h2 media="screen and (max-width: 480px)">';
echo 'My headline';
echo '</h2>';
echo '<h1 media="screen and (min-width: 481px)">';
echo 'My headline';
echo '</h1>';
?>
This will output a smaller sized headline if the screen is 480px or less. So no need to pass any vars using JS or similar.
iOS7 has new interface rules, so It's better to keep at least the back arrow when you push a UIView. It's very easy to change the "back" text programmatically. Just add this code before push the view (Or prepareForSegue if you are using StoryBoards):
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"NEW TITLE" style:UIBarButtonItemStylePlain target:nil action:nil];
}
This will change the default "Back" text, but will keep the iOS7 styled back arrow. You can also change the tint color for the back arrow before push the view:
- (void)viewDidLoad{
//NavBar background color:
self.navigationController.navigationBar.barTintColor=[UIColor redColor];
//NavBar tint color for elements:
self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
}
Hope this helps you!
You can try using StringBuilder
: -
final StringBuilder sb = new StringBuilder();
sb.append("SHOP MA\n");
sb.append("----------------------------\n");
sb.append("Pannampitiya\n");
sb.append("09-10-2012 harsha no: 001\n");
sb.append("No Item Qty Price Amount\n");
sb.append("1 Bread 1 50.00 50.00\n");
sb.append("____________________________\n");
// To use StringBuilder as String.. Use `toString()` method..
System.out.println(sb.toString());
Abstract Factory: A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes. Abstract Factory Example
Factory: It provides a way to delegate the instantiation logic to child classes. Factory Pattern Example
As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;
JsonSerializer serializer = new JsonSerializer();
MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");
The above code assumes that you have something like
public class MyObject
{
public string prop1 { get; set; };
public string prop2 { get; set; };
}
And your json looks like;
{
"prop1":"value1",
"prop2":"value2"
}
I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.
I know it's been a long time, but still the most obvious solution via fold (aka reduce in js) is missing, for the sake of completeness i'll leave it here:
function mapO(f, o) {
return Object.keys(o).reduce((acc, key) => {
acc[key] = f(o[key])
return acc
}, {})
}
Android Developer has the right answer, but the provided source code is pretty verbose and doesn't actually implement the pattern described in the diagram.
Here is a better template:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- stuff to scroll -->
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<!-- footer -->
</FrameLayout>
</RelativeLayout>
</ScrollView>
Its up to you to decide what views you use for the "scrolling" and "footer" parts. Also know that you probably have to set the ScrollView
s
fillViewPort .
A lot of great answers here. Below is a sample of the stored procedure that I wrote to accomplish this task for a Web App that I am developing:
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Create Temporary Table
SELECT * INTO #tempTable FROM <YourTable> WHERE Id = Id
--To trigger the auto increment
UPDATE #tempTable SET Id = NULL
--Update new data row in #tempTable here!
--Insert duplicate row with modified data back into your table
INSERT INTO <YourTable> SELECT * FROM #tempTable
-- Drop Temporary Table
DROP TABLE #tempTable
If you don't have any version of SQLServerManagerXX.msc, then you simply do not have it installed. I noticed it does not come with SQL server management studio 2019.
It's available (client-connectivity tools) in the SQL Server Express edition or SQL Server Developer edition which is good for dev/test (non-production) usage.
printf
is a function whereas cout
is a variable.
You can compress the bitmap as an byte's array and then uncompress it in another activity, like this.
Compress!!
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
setresult.putExtra("BMP",bytes);
Uncompress!!
byte[] bytes = data.getByteArrayExtra("BMP");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Focus
sets the input focus, so setting it to the form won't work because forms don't accept input. Try setting the form's ActiveControl
property to a different control. You could also use Select
to select a specific control or SelectNextControl
to select the next control in the tab order.
You cannot set the min
value of a SeekBar (always 0) and you cannot set the step
value of a SeekBar (always 1).
To set the value from 60 to 180 with a step of 1:
int step = 1;
int max = 180;
int min = 60;
// Ex :
// If you want values from 3 to 5 with a step of 0.1 (3, 3.1, 3.2, ..., 5)
// this means that you have 21 possible values in the seekbar.
// So the range of the seek bar will be [0 ; (5-3)/0.1 = 20].
seekbar.setMax( (max - min) / step );
seekbar.setOnSeekBarChangeListener(
new OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser)
{
// Ex :
// And finally when you want to retrieve the value in the range you
// wanted in the first place -> [3-5]
//
// if progress = 13 -> value = 3 + (13 * 0.1) = 4.3
double value = min + (progress * step);
}
}
);
I put another example within the code so that you understand the math.
A matrix is really just a vector with a dim
attribute (for the dimensions). So you can add dimensions to vec
using the dim()
function and vec
will then be a matrix:
vec <- 1:49
dim(vec) <- c(7, 7) ## (rows, cols)
vec
> vec <- 1:49
> dim(vec) <- c(7, 7) ## (rows, cols)
> vec
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 8 15 22 29 36 43
[2,] 2 9 16 23 30 37 44
[3,] 3 10 17 24 31 38 45
[4,] 4 11 18 25 32 39 46
[5,] 5 12 19 26 33 40 47
[6,] 6 13 20 27 34 41 48
[7,] 7 14 21 28 35 42 49
In NetBeans,
properties
rub
tabmysql-connector-java.jar
and applyyou could also grep the line out and then cut it like for instance:
grep 'text' filename | cut -c 1-5
To make autoresizing of UITableViewCell to work make sure you are doing these changes :
In your UIViewController's viewDidLoad function set below UITableView Properties :
self.tableView.estimatedRowHeight = <minimum cell height>
self.tableView.rowHeight = UITableViewAutomaticDimension
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
There is no way to declare global variables as you're probably imagining them in VB.NET.
What you can do (as some of the other answers have suggested) is declare everything that you want to treat as a global variable as static variables instead within one particular class:
Public Class GlobalVariables
Public Shared UserName As String = "Tim Johnson"
Public Shared UserAge As Integer = 39
End Class
However, you'll need to fully-qualify all references to those variables anywhere you want to use them in your code. In this sense, they are not the type of global variables with which you may be familiar from other languages, because they are still associated with some particular class.
For example, if you want to display a message box in your form's code with the user's name, you'll have to do something like this:
Public Class Form1: Inherits Form
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
MessageBox.Show("Hello, " & GlobalVariables.UserName)
End Sub
End Class
You can't simply access the variable by typing UserName
outside of the class in which it is defined—you must also specify the name of the class in which it is defined.
If the practice of fully-qualifying your variables horrifies or upsets you for whatever reason, you can always import the class that contains your global variable declarations (here, GlobalVariables
) at the top of each code file (or even at the project level, in the project's Properties window). Then, you could simply reference the variables by their name.
Imports GlobalVariables
Note that this is exactly the same thing that the compiler is doing for you behind-the-scenes when you declare your global variables in a Module
, rather than a Class
. In VB.NET, which offers modules for backward-compatibility purposes with previous versions of VB, a Module
is simply a sealed static class (or, in VB.NET terms, Shared NotInheritable Class
). The IDE allows you to call members from modules without fully-qualifying or importing a reference to them. Even if you decide to go this route, it's worth understanding what is happening behind the scenes in an object-oriented language like VB.NET. I think that as a programmer, it's important to understand what's going on and what exactly your tools are doing for you, even if you decide to use them. And for what it's worth, I do not recommend this as a "best practice" because I feel that it tends towards obscurity and clean object-oriented code/design. It's much more likely that a C# programmer will understand your code if it's written as shown above than if you cram it into a module and let the compiler handle everything.
Note that like at least one other answer has alluded to, VB.NET is a fully object-oriented language. That means, among other things, that everything is an object. Even "global" variables have to be defined within an instance of a class because they are objects as well. Any time you feel the need to use global variables in an object-oriented language, that a sign you need to rethink your design. If you're just making the switch to object-oriented programming, it's more than worth your while to stop and learn some of the basic patterns before entrenching yourself any further into writing code.
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
can check it in packages.config file.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.0.2" targetFramework="net40-Client" />
</packages>
Date.prototype.days = function(to) {_x000D_
return Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000)))_x000D_
}_x000D_
_x000D_
_x000D_
console.log(new Date('2014/05/20').days(new Date('2014/05/23'))); // 3 days_x000D_
_x000D_
console.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days
_x000D_
Try this!
List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));
It's a good practice to declare the ArrayList
with interface List
if you don't have to invoke the specific methods.
import matplotlib.pyplot as plt
plt.savefig("image.png")
In Jupyter Notebook you have to remove plt.show()
and add plt.savefig()
, together with the rest of the plt-code in one cell.
The image will still show up in your notebook.
OpenCV Specific
Opencv supports filesystem, probably through its dependency Boost.
#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);
You could use the ternary operator:
return string.IsNullOrEmpty(strTestString) ? "0" : strTestString
FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:
const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");
Check out the instanceof operator.
var isJqueryObject = obj instanceof jQuery
Use a controller method if you need to run arbitrary JavaScript code, or you could define a filter that returned true or false.
I just tested (should have done that first), and something like ng-show="!a && b"
worked as expected.
It documents your intent - you will be storing small numbers, rather than a character.
Also it looks nicer if you're using other typedefs such as uint16_t
or int32_t
.
Yes:
@import url("base.css");
Note:
@import
rule must precede all other rules (except @charset
).@import
statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of base.css
and special.css
into base-special.css
and reference only base-special.css
.This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.
public int GetAge(DateTime birthDate)
{
int age = DateTime.Now.Year - birthDate.Year;
if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
age--;
return age;
}
Ref: https://stackoverflow.com/a/17367570/132599
Avoid using double-dot-calling expressions, such as this:
var workbook = excel.Workbooks.Open(/*params*/)
...because in this way you create RCW objects not only for workbook, but for Workbooks, and you should release it too (which is not possible if a reference to the object is not maintained).
This resolved the issue for me. Your code becomes:
public Excel.Application excelApp = new Excel.Application();
public Excel.Workbooks workbooks;
public Excel.Workbook excelBook;
workbooks = excelApp.Workbooks;
excelBook = workbooks.Add(@"C:/pape.xltx");
...
Excel.Sheets sheets = excelBook.Worksheets;
Excel.Worksheet excelSheet = (Worksheet)(sheets[1]);
excelSheet.DisplayRightToLeft = true;
Range rng;
rng = excelSheet.get_Range("C2");
rng.Value2 = txtName.Text;
And then release all those objects:
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
excelBook .Save();
excelBook .Close(true);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
I wrap this in a try {} finally {}
to ensure everything gets released even if something goes wrong (what could possibly go wrong?) e.g.
public Excel.Application excelApp = null;
public Excel.Workbooks workbooks = null;
...
try
{
excelApp = new Excel.Application();
workbooks = excelApp.Workbooks;
...
}
finally
{
...
if (workbooks != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
}
Create views on two first "selects" and "union" them.
I wrote a simple program that solved the easy ones. It took its input from a file which was just a matrix with spaces and numbers. The datastructure to solve it was just a 9 by 9 matrix of a bit mask. The bit mask would specify which numbers were still possible on a certain position. Filling in the numbers from the file would reduce the numbers in all rows/columns next to each known location. When that is done you keep iterating over the matrix and reducing possible numbers. If each location has only one option left you're done. But there are some sudokus that need more work. For these ones you can just use brute force: try all remaining possible combinations until you find one that works.
Just create the database using createdb
CLI tool:
PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB
If the database exists, it will return an error:
createdb: database creation failed: ERROR: database "mydb" already exists
Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS
.
You can enter the following formula in the cell where you want to see the Overdue
or Not due
result:
=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))
This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue
, otherwise it is set to Not due
.
In Swift5 and Xcode 10
self.navigationItem.title = "your name"
let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
navigationController?.navigationBar.titleTextAttributes = textAttributes
1) Open a Developer Command Prompt for VS 2017 (or whatever version you have on your machine)(It should be located under: Start menu --> All programs --> Visual Studio 2017 (or whatever version you have on your machine) --> Visual Studio Tools --> Developer Command Prompt for VS 2017.
2) Enter the following command:
dumpbin /EXPORTS my_lib_name.lib
The chosen solution works, however they also snap the background to the top scrolling position. I extended the code above to fix that 'jump'.
//Set 2 global variables
var scrollTopPosition = 0;
var lastKnownScrollTopPosition = 0;
//when the document loads
$(document).ready(function(){
//this only runs on the right platform -- this step is not necessary, it should work on all platforms
if( navigator.userAgent.match(/iPhone|iPad|iPod/i) ) {
//There is some css below that applies here
$('body').addClass('platform-ios');
//As you scroll, record the scrolltop position in global variable
$(window).scroll(function () {
scrollTopPosition = $(document).scrollTop();
});
//when the modal displays, set the top of the (now fixed position) body to force it to the stay in the same place
$('.modal').on('show.bs.modal', function () {
//scroll position is position, but top is negative
$('body').css('top', (scrollTopPosition * -1));
//save this number for later
lastKnownScrollTopPosition = scrollTopPosition;
});
//on modal hide
$('.modal').on('hidden.bs.modal', function () {
//force scroll the body back down to the right spot (you cannot just use scrollTopPosition, because it gets set to zero when the position of the body is changed by bootstrap
$('body').scrollTop(lastKnownScrollTopPosition);
});
}
});
The css is pretty simple:
// You probably already have this, but just in case you don't
body.modal-open {
overflow: hidden;
width: 100%;
height: 100%;
}
//only on this platform does it need to be fixed as well
body.platform-ios.modal-open {
position: fixed;
}
That's what ln
is documented to do when the target already exists and is a directory. If you want /etc/nginx
to be a symlink rather than contain a symlink, you had better not create it as a directory first!
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
Then simply use the constructor as you would use the function:
pairReturn pR = new pairReturn(15);
and you can use pR.sth1, pR.sth2 as "2 results of the function"
ISSUE 1:
Started by user anonymous
That does not mean that Jenkins started as an anonymous user.
It just means that the person who started the build was not logged in. If you enable Jenkins security, you can create usernames for people and when they log in, the
"Started by anonymous"
will change to
"Started by < username >".
Note: You do not have to enable security in order to run jenkins or to clone correctly.
If you want to enable security and create users, you should see the options at Manage Jenkins > Configure System
.
ISSUE 2:
The "can't clone" error is a different issue altogether. It has nothing to do with you logging in to jenkins or enabling security. It just means that Jenkins does not have the credentials to clone from your git SCM.
Check out the Jenkins Git Plugin to see how to set up Jenkins to work with your git repository.
Hope that helps.
Replace [True | False (default)]
Effect
1. Replace the directive element.
Dependency:
1. When replace: true, the template or templateUrl must be required.
The image should be embedded in the message as an attachment like this:
--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png
base64 data
--boundary
And, the HTML part would reference the image like this:
<img src="cid:0123456789">
In some clients, src="sig.png" will work too.
You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.
Clients shouldn't block this image either as it isn't remote.
Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):
From
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"
This is a message with multiple parts in MIME format.
--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
test
--
[Picture of a Christmas Tree]
--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"
--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>test</p>
<p class="sig">-- <br><img src="cid:0123456789"></p>
</body>
</html>
--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64
R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7
--related_boundary--
--alternative_boundary--
You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.
You can change your progressbar colour using the code below:
progressBar.getProgressDrawable().setColorFilter(
getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_IN);
It's better to use a SecureString:
var password = new SecureString();
var phPassword phPassword = Marshal.SecureStringToGlobalAllocUnicode(password);
IntPtr phUserToken;
LogonUser(username, domain, phPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out phUserToken);
And:
Marshal.ZeroFreeGlobalAllocUnicode(phPassword);
password.Dispose();
Function definition:
private static extern bool LogonUser(
string pszUserName,
string pszDomain,
IntPtr pszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken);
Note that Date.getDate
only returns the day of the month. You can add a day by calling Date.setDate
and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
I had raised a support ticket against Github and got a response confirming the fact that ALL pages are public. I've now requested them to add a note to help.github.com/pages.
Use this:
$stmt = $user->runQuery("SELECT * FROM tbl WHERE ID=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
$stmt->bindColumn("a_b",$xx);
$stmt->bindColumn("c_d",$yy);
while($rows = $stmt->fetch(PDO::FETCH_BOUND))
{
//---insert into new tble
}
You get this error when the function isn't on the MATLAB path or in pwd.
First, make sure that you are able to find the function using:
>> which divrat
c:\work\divrat\divrat.m
If it returns:
>> which divrat
'divrat' not found.
It is not on the MATLAB path or in PWD.
Second, make sure that the directory that contains divrat
is on the MATLAB path using the PATH
command. It may be that a directory that you thought was on the path isn't actually on the path.
Finally, make sure you aren't using a "private" directory. If divrat
is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:
>> foo
ans =
1
>> divrat(1,1)
??? Undefined function or method 'divrat' for input arguments of type 'double'.
>> which -all divrat
c:\work\divrat\private\divrat.m % Private to divrat
Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000
) is not included in \s
for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000
with \u0020
), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000]
.
If you're using Perl or PCRE, you have the option of using the \h
shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.
However, this \h
shorthand has not been implemented for .NET and C#, as best I've been able to tell.
you can use style
<td colspan="2">
<div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>
<div style="float: right; width:100px">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</div>
<div style="clear:both"></div>
</td>
In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).
See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)
You can specify the colClasse for only one columns.
So in your example you should use:
data <- read.csv('test.csv', colClasses=c("time"="character"))
If you want an alternative to pickle
or json
, you can use klepto
.
>>> init = {'y': 2, 'x': 1, 'z': 3}
>>> import klepto
>>> cache = klepto.archives.file_archive('memo', init, serialized=False)
>>> cache
{'y': 2, 'x': 1, 'z': 3}
>>>
>>> # dump dictionary to the file 'memo.py'
>>> cache.dump()
>>>
>>> # import from 'memo.py'
>>> from memo import memo
>>> print memo
{'y': 2, 'x': 1, 'z': 3}
With klepto
, if you had used serialized=True
, the dictionary would have been written to memo.pkl
as a pickled dictionary instead of with clear text.
You can get klepto
here: https://github.com/uqfoundation/klepto
dill
is probably a better choice for pickling then pickle
itself, as dill
can serialize almost anything in python. klepto
also can use dill
.
You can get dill
here: https://github.com/uqfoundation/dill
The additional mumbo-jumbo on the first few lines are because klepto
can be configured to store dictionaries to a file, to a directory context, or to a SQL database. The API is the same for whatever you choose as the backend archive. It gives you an "archivable" dictionary with which you can use load
and dump
to interact with the archive.
If you want to pick cell entries from a list then you have a couple of non-code based options
I would recommend The Data Validation approach where
sample from Debra's site below, click on the first link above to access it.
that is the right behavior.
if you set @item1
to a value the below expression will be true
IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
Anyway in SQL Server there is not a such function but you can create your own:
CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
RETURN 0
ELSE
RETURN 1
END
Download ilmerge and ilmergre gui . makes joining the files so easy ive used these and works great
Sorry, but I think the accepted answer is an overkill. All you need to do is this:
public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
public void OnException (ExceptionContext context)
{
// Log only handled exceptions, because all other will be caught by ELMAH anyway.
if (context.ExceptionHandled)
ErrorSignal.FromCurrentContext().Raise(context.Exception);
}
}
and then register it (order is important) in Global.asax.cs:
public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
filters.Add(new ElmahHandledErrorLoggerFilter());
filters.Add(new HandleErrorAttribute());
}
This should be very simple if Google Calendar does not require the *.ics
-extension (which will require some URL rewriting in the server).
$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@yourhost.test
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR";
//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
echo $ical;
exit;
That's essentially all you need to make a client think that you're serving a iCalendar file, even though there might be some issues regarding caching, text encoding and so on. But you can start experimenting with this simple code.
Here's a performance comparison of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.
I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint Understanding Tuning TCP has details.
Heres another good comparison of individual characteristics of each protocol.
You can also use HeapWalker from the Netbeans Profiler or the Visual VM stand-alone tool. Visual VM is a good alternative to JHAT as it is stand alone, but is much easier to use than JHAT.
You need Java 6+ to fully use Visual VM.
You need to use a link function in your directive:
link: function(scope, element, attrs) {
element.on('click', function() {
$window.history.back();
});
}
See jsFiddle.
First error: You're casting a ClientThread
as a String
for some reason.
Second error: You're not calling remove
on your List
.
Is is homework? If so, you might want to use the tag.
There is no static Equals
method in the Array
class, so what you are using is actually Object.Equals
, which determines if the two object references point to the same object.
If you want to check if the arrays contains the same items in the same order, you can use the SequenceEquals
extension method:
childe1.SequenceEqual(grandFatherNode)
To use SequenceEquals
with multidimensional arrays, you can use an extension to enumerate them. Here is an extension to enumerate a two dimensional array:
public static IEnumerable<T> Flatten<T>(this T[,] items) {
for (int i = 0; i < items.GetLength(0); i++)
for (int j = 0; j < items.GetLength(1); j++)
yield return items[i, j];
}
Usage:
childe1.Flatten().SequenceEqual(grandFatherNode.Flatten())
If your array has more dimensions than two, you would need an extension that supports that number of dimensions. If the number of dimensions varies, you would need a bit more complex code to loop a variable number of dimensions.
You would of course first make sure that the number of dimensions and the size of the dimensions of the arrays match, before comparing the contents of the arrays.
Turns out that you can use the OfType<T>
method to flatten an array, as RobertS pointed out. Naturally that only works if all the items can actually be cast to the same type, but that is usually the case if you can compare them anyway. Example:
childe1.OfType<Person>().SequenceEqual(grandFatherNode.OfType<Person>())
Essentially, it's the way Microsoft introduces its C++ extensions so that they won't conflict with future extensions of standard C++. With __declspec, you can attribute a function or class; the exact meaning varies depending on the nature of __declspec. __declspec(naked), for example, suppresses prolog/epilog generation (for interrupt handlers, embeddable code, etc), __declspec(thread) makes a variable thread-local, and so on.
The full list of __declspec attributes is available on MSDN, and varies by compiler version and platform.
import java.util.Scanner;
public class Palindrom {
public static void main(String []args)
{
Scanner in = new Scanner(System.in);
String str= in.nextLine();
int x= str.length();
if(x%2!=0)
{
for(int i=0;i<x/2;i++)
{
if(str.charAt(i)==str.charAt(x-1-i))
{
continue;
}
else
{
System.out.println("String is not a palindrom");
break;
}
}
}
else
{
for(int i=0;i<=x/2;i++)
{
if(str.charAt(i)==str.charAt(x-1-i))
{
continue;
}
else
{
System.out.println("String is not a palindrom");
break;
}
}
}
}
}
I prefer to use border-spacing
as it allows more flexibility. For instance, you could do
table {
border-spacing: 0 2px;
}
Which would only collapse the vertical borders and leave the horizontal ones in tact, which is what it sounds like the OP was actually looking for.
Note that border-spacing: 0
is not the same as border-collapse: collapse
. You will need to use the latter if you want to add your own border to a tr
as seen here.
try this :
string[,] myArray = new string[3,3];
have a look on http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
Comparable
is for objects with a natural ordering. The object itself knows how it is to be ordered.
Comparator
is for objects without a natural ordering or when you wish to use a different ordering.
The syntax is the *
and **
. The names *args
and **kwargs
are only by convention but there's no hard requirement to use them.
You would use *args
when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:
>>> def print_everything(*args):
for count, thing in enumerate(args):
... print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
Similarly, **kwargs
allows you to handle named arguments that you have not defined in advance:
>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args
and **kwargs
. The named arguments come first in the list. For example:
def table_things(titlestring, **kwargs)
You can also use both in the same function definition but *args
must occur before **kwargs
.
You can also use the *
and **
syntax when calling a function. For example:
>>> def print_three_things(a, b, c):
... print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a *
both in the function definition and in the function call.
You can use LinkedList. It has methods peek, poll and offer.
@Dan,
Do I not need msdtc enabled for transactions to work?
Only distributed transactions - Those that involve more than a single connection. Make doubly sure you are only opening a single connection within the transaction and it won't escalate - Performance will be much better too.
This worked for me:
I closed all the other memory intensive applications on my Windows 7 machine. And I tried to open Eclipse, and, voila, it worked.
This error arises when you don't use brackets with pop
operation. Write the code in this manner.
listb.pop(0)
This is a valid python expression.
Sure. I suppose that you have already installed TensorFlow for GPU.
You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.
import keras
import tensorflow as tf
config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.
Ordinary javascript cannot close windows willy-nilly. This is a security feature, introduced a while ago, to stop various malicious exploits and annoyances.
From the latest working spec for window.close()
:
The
close()
method on Window objects should, if all the following conditions are met, close the browsing context A:
- The corresponding browsing context A is script-closable.
- The browsing context of the incumbent script is familiar with the browsing context A.
- The browsing context of the incumbent script is allowed to navigate the browsing context A.
A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.
This means, with one small exception, javascript must not be allowed to close a window that was not opened by that same javascript.
Chrome allows that exception -- which it doesn't apply to userscripts -- however Firefox does not. The Firefox implementation flat out states:
This method is only allowed to be called for windows that were opened by a script using the
window.open
method.
If you try to use window.close
from a Greasemonkey / Tampermonkey / userscript you will get:
Firefox: The error message, "Scripts may not close windows that were not opened by script.
"
Chrome: just silently fails.
The best way to deal with this is to make a Chrome extension and/or Firefox add-on instead. These can reliably close the current window.
However, since the security risks, posed by window.close
, are much less for a Greasemonkey/Tampermonkey script; Greasemonkey and Tampermonkey could reasonably provide this functionality in their API (essentially packaging the extension work for you).
Consider making a feature request.
Chrome is currently was vulnerable to the "self redirection" exploit. So code like this used to work in general:
open(location, '_self').close();
This is buggy behavior, IMO, and is now (as of roughly April 2015) mostly blocked. It will still work from injected code only if the tab is freshly opened and has no pages in the browsing history. So it's only useful in a very small set of circumstances.
However, a variation still works on Chrome (v43 & v44) plus Tampermonkey (v3.11 or later). Use an explicit @grant
and plain window.close()
. EG:
// ==UserScript==
// @name window.close demo
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// ==/UserScript==
setTimeout (window.close, 5000);
Thanks to zanetu for the update. Note that this will not work if there is only one tab open. It only closes additional tabs.
Firefox is secure against that exploit. So, the only javascript way is to cripple the security settings, one browser at a time.
You can open up about:config
and set
allow_scripts_to_close_windows
to true
.
If your script is for personal use, go ahead and do that. If you ask anyone else to turn that setting on, they would be smart, and justified, to decline with prejudice.
There currently is no equivalent setting for Chrome.
What you call "Two-Way SSL" is usually called TLS/SSL with client certificate authentication.
In a "normal" TLS connection to example.com only the client verifies that it is indeed communicating with the server for example.com. The server doesn't know who the client is. If the server wants to authenticate the client the usual thing is to use passwords, so a client needs to send a user name and password to the server, but this happens inside the TLS connection as part of an inner protocol (e.g. HTTP) it's not part of the TLS protocol itself. The disadvantage is that you need a separate password for every site because you send the password to the server. So if you use the same password on for example PayPal and MyPonyForum then every time you log into MyPonyForum you send this password to the server of MyPonyForum so the operator of this server could intercept it and try it on PayPal and can issue payments in your name.
Client certificate authentication offers another way to authenticate the client in a TLS connection. In contrast to password login, client certificate authentication is specified as part of the TLS protocol. It works analogous to the way the client authenticates the server: The client generates a public private key pair and submits the public key to a trusted CA for signing. The CA returns a client certificate that can be used to authenticate the client. The client can now use the same certificate to authenticate to different servers (i.e. you could use the same certificate for PayPal and MyPonyForum without risking that it can be abused). The way it works is that after the server has sent its certificate it asks the client to provide a certificate too. Then some public key magic happens (if you want to know the details read RFC 5246) and now the client knows it communicates with the right server, the server knows it communicates with the right client and both have some common key material to encrypt and verify the connection.
My solution to this (which hasn't caused any performance issues):
Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); };
I'm using it in all of my projects and credits go to John Resig John Resig's Site
$scope.items.forEach(function(element, index, array){ if(element.name === 'ted'){ $scope.items.remove(index); } });
At the end the $digest will be fired in angularjs and my UI is updated immediately without any recognizable lag.
Since Firefox 35, "-moz-appearance:none
" that you already wrote in your code, finally remove arrow button as desired.
It was a bug solved since that version.
Any seaborn plots suported by facetgrid won't work with (e.g. catplot)
g.set_xticklabels(rotation=30)
however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.
g.set_xticklabels(g.get_xticklabels(), rotation=30)
Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.
Write editTextBackground.xml in drawable folder in resources
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="@color/borderColor" />
</shape>
don't forget to declare color in resources named borderColor
.
and assign this background to the EditText
in xml background attribute
<EditText
android:id="@+id/text"
android:background="@drawable/editTextBackground"
/>
and it'll set border to EditText
.
You can change border of edit text without drawable by using style
attribute
style="@style/Widget.AppCompat.EditText"
for more details visit customize edit text
While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.
If you want to search for "my cats", instead of:
myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)
Just do:
myString.replace(/\s*/g,"").match(/mycats/g)
Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.
Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.
That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...
What version of the SQL Server engine do you get from SELECT @@VERSION
??
there are 3 ways to do it.
1.Add the following line on style.xml to change entire application
<item name="android:textAllCaps">false</item>
2.Use
android:textAllCaps="false"
in your layout-v21
mButton.setTransformationMethod(null);
android:textAllCaps="false"
regards
I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.
I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:
<?php
echo phpinfo();
?>
There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from
PHPIniDir 'c:\PHP\'
to
PHPIniDir 'c:\PHP'
Pay the attention that the last slash disturbed everything!
Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!
You probably don't want to do this:
#include "client.cpp"
A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.
Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS
, however, each file that has #include "client.cpp"
is built independently and as such will find SOCKET_CLIENT_CLASS
not yet defined. Therefore it's contents will be included, not #ifdef'd out.
If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.
You need to use JDK 1.7.0 rather than JDK 1.8.0.
To make sure it, you need to delete JDK 1.8.0 on your computer.
If you use Mac, you need to delete:
/Library/Java/JavaVirtualMachines/jdk.jdk
/Library/PreferencePanes/JavaControlPanel.prefPane
/Library/Internet Plug-Ins/JavaAppletPlugin.plugin
Then, you need to reinstall JDK 1.7.0, and you will succeed to generate the .jar file.
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
This will solve the problem,
var blogPosts = (from p in dc.BlogPosts
where p.BlogPostID == ID
select p);
if(blogPosts.Any())
{
var post = post.Single();
}
You could use the :first-child
and :last-child
pseudo-selectors:
tr td:first-child,
tr td:last-child {
/* styles */
}
This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).
Try this. Works well in my Oracle 10g,
CREATE TABLE new_table
AS (SELECT * FROM old_table);
You can also try
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTimeInMillis());
getTimeInMillis() - the current time as UTC milliseconds from the epoch
Or just use Apache CXF's wsdl2java to generate objects you can use.
It is included in the binary package you can download from their website. You can simply run a command like this:
$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl
It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):
DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);
There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html
Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315
Since you haven't posted code, we're kind of working in the dark. What are the details of the exception?
Are you calling Thread.wait() from within the thread, or outside it?
I ask this because according to the javadoc for IllegalMonitorStateException, it is:
Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
To clarify this answer, this call to wait on a thread also throws IllegalMonitorStateException, despite being called from within a synchronized block:
private static final class Lock { }
private final Object lock = new Lock();
@Test
public void testRun() {
ThreadWorker worker = new ThreadWorker();
System.out.println ("Starting worker");
worker.start();
System.out.println ("Worker started - telling it to wait");
try {
synchronized (lock) {
worker.wait();
}
} catch (InterruptedException e1) {
String msg = "InterruptedException: [" + e1.getLocalizedMessage() + "]";
System.out.println (msg);
e1.printStackTrace();
System.out.flush();
}
System.out.println ("Worker done waiting, we're now waiting for it by joining");
try {
worker.join();
} catch (InterruptedException ex) { }
}
This is way I did it:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)
You can define your own sizes.
A string in Javascript is already a character array.
You can simply access any character in the array as you would any other array.
var s = "overpopulation";
alert(s[0]) // alerts o.
UPDATE
As is pointed out in the comments below, the above method for accessing a character in a string is part of ECMAScript 5 which certain browsers may not conform to.
An alternative method you can use is charAt(index)
.
var s = "overpopulation";
alert(s.charAt(0)) // alerts o.
It will be something like this:
SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
Books b
JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
JOIN Publishers p ON p._PublisherID = b.PublisherID
JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
JOIN Writer w ON w._WritersID = wb._Writers_WriterID
You use the join
statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b
the Books
table will be referred to as b
in the rest of the query. This makes for less typing.
FYI your naming convention is very strange, I would expect it to be more like this:
Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID
For the sake of completeness: you can also use the sortByCol()
function from the BBmisc
package:
library(BBmisc)
sortByCol(dd, c("z", "b"), asc = c(FALSE, TRUE))
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
Performance comparison:
library(microbenchmark)
microbenchmark(sortByCol(dd, c("z", "b"), asc = c(FALSE, TRUE)), times = 100000)
median 202.878
library(plyr)
microbenchmark(arrange(dd,desc(z),b),times=100000)
median 148.758
microbenchmark(dd[with(dd, order(-z, b)), ], times = 100000)
median 115.872
$_SERVER['HTTP_X_REQUESTED_WITH']
RFC3875, 4.1.18:
Meta-variables with names beginning with
HTTP_
contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of-
replaced with_
and hasHTTP_
prepended to give the meta-variable name.
line[5:]
will give the substring you want. Search the introduction and look for 'slice notation'
Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.
Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.
Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html
You can read more about function types in the language specification in sections 3.5.3.5 and 3.5.5.
The TypeScript compiler will infer types when it can, and this is done you do not need to specify explicit types. so for the greeter example, greet() returns a string literal, which tells the compiler that the type of the function is a string, and no need to specify a type. so for instance in this sample, I have the greeter class with a greet method that returns a string, and a variable that is assigned to number literal. the compiler will infer both types and you will get an error if you try to assign a string to a number.
class Greeter {
greet() {
return "Hello, "; // type infered to be string
}
}
var x = 0; // type infered to be number
// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet();
Similarly, this sample will cause an error as the compiler, given the information, has no way to decide the type, and this will be a place where you have to have an explicit return type.
function foo(){
if (true)
return "string";
else
return 0;
}
This, however, will work:
function foo() : any{
if (true)
return "string";
else
return 0;
}
this will work for sure..
RelativeLayout layout = new RelativeLayout(R.layout.your_layour);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
params.addRule(LinearLayout.CENTER_IN_PARENT);
textView.setLayoutParams(params);
textView.setGravity(Gravity.CENTER);
layout.addView(textView);
setcontentView(layout);
A simpler approach is to create a secondary UITextView with all of the same attributes as the original text view except for a different textColor, with constraints to ensure they stay aligned. Then when any characters are entered into the main text view, hide the cloned text view, otherwise show the cloned text view with some text.
This can be achieved in several ways, but a relatively clean way would be to subclass UITextView and keep all of this logic within the subclass.
So, subclass UITextView and allow it to create it's place holder view lazily:
Interface file:
@interface FOOTextView : UITextView <UITextViewDelegate>
@property (nonatomic, copy) NSString *placeholderText;
- (void)checkPlaceholder;
@end
Implementation file:
#import "FOOTextView.h"
@interface FOOTextView ()
@property (nonatomic, strong) UITextView *placeholderTextView;
@end
@implementation FOOTextView
- (void)checkPlaceholder {
// Hide the placeholder text view if we've got any text
self.placeholderTextView.hidden = (self.text.length > 0 || self.attributedText.length > 0);
}
- (void)setPlaceholderText:(NSString *)placeholderText {
_placeholderText = [placeholderText copy];
// Setup the placeholder text view if we haven't already
[self setupPlaceholderTextView];
// Apply the placeholder text to the placeholder text view
self.placeholderTextView.text = placeholderText;
}
- (void)setupPlaceholderTextView {
if (!self.placeholderTextView) {
// Setup the place holder text view, duplicating our visual setup
self.placeholderTextView = [[UITextView alloc] initWithFrame:CGRectZero];
self.placeholderTextView.translatesAutoresizingMaskIntoConstraints = NO;
self.placeholderTextView.textColor = self.placeholderTextColor ? self.placeholderTextColor : [UIColor colorWithRed:199.f/255.f green:199.f/255.f blue:205.f/255.f alpha:1.f];
self.placeholderTextView.userInteractionEnabled = NO;
self.placeholderTextView.font = self.font;
self.placeholderTextView.textAlignment = self.textAlignment;
self.placeholderTextView.backgroundColor = self.backgroundColor;
self.placeholderTextView.editable = NO;
// Our background color must be clear for the placeholder text view to show through
self.backgroundColor = [UIColor clearColor];
// Insert the placeholder text view into our superview, below ourself so it shows through
[self.superview insertSubview:self.placeholderTextView belowSubview:self];
// Setup constraints to ensure the placeholder text view stays aligned with us
NSLayoutConstraint *constraintCenterX = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0.f];
NSLayoutConstraint *constraintCenterY = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.f constant:0.f];
NSLayoutConstraint *constraintWidth = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.f constant:0.f];
NSLayoutConstraint *constraintHeight = [NSLayoutConstraint constraintWithItem:self.placeholderTextView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1.f constant:0.f];
NSArray *constraints = @[constraintCenterX, constraintCenterY, constraintWidth, constraintHeight];
[self.superview addConstraints:constraints];
}
}
- (void)setPlaceholderTextColor:(UIColor *)placeholderTextColor {
_placeholderTextColor = placeholderTextColor;
self.placeholderTextView.textColor = _placeholderTextColor;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
// We don't want a background color ourselves, instead we want our placeholder text view to have the desired background color
[self.placeholderTextView setBackgroundColor:backgroundColor];
}
- (void)removeFromSuperview {
// Ensure we also remove our placeholder text view
[self.placeholderTextView removeFromSuperview];
self.placeholderTextView = nil;
[super removeFromSuperview];
}
#pragma mark - Text View Delegation
- (void)textViewDidChange:(UITextView *)textView {
[self checkPlaceholder];
}
@end
Using the above class, if you set an instance of FOOTextView's delegate to itself, everything will work out of the box:
FOOTextView *myTextView = ...
myTextView.placeholderText = @"What's on your mind?";
myTextView.placeholderTextColor = [UIColor lightGrayColor];
myTextView.delegate = myTextView;
If you'd like another object to take over as the delegate, then you just need to call the text view's checkPlaceholder method in the textViewDidChange: delegate method, eg;
FOOTextView *myTextView = ...
myTextView.placeholderText = @"What's on your mind?";
myTextView.placeholderTextColor = [UIColor lightGrayColor];
myTextView.delegate = self;
self.myTextView = myTextView;
- (void)textViewDidChange:(UITextView *)textView {
// Call the checkPlaceholder method to update the visuals
[self.myTextView checkPlaceholder];
}
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
In this mode you can find all element which has class active and remove it
try this
$(document).ready(function() {
$(this.attr('id')).click(function () {
$(document).find('.active').removeClass('active');
var DivId = $(this).attr('id');
alert(DivId);
$(this).addClass('active');
});
});
Here is a concise way to initialize an array of custom objects in PowerShell.
> $body = @( @{ Prop1="1"; Prop2="2"; Prop3="3" }, @{ Prop1="1"; Prop2="2"; Prop3="3" } )
> $body
Name Value
---- -----
Prop2 2
Prop1 1
Prop3 3
Prop2 2
Prop1 1
Prop3 3
epoch is an iteration of subset of the samples for training, for example, the gradient descent algorithm in neutral network. A good reference is: http://neuralnetworksanddeeplearning.com/chap1.html
Note that the page has a code for the gradient descent algorithm which uses epoch
def SGD(self, training_data, epochs, mini_batch_size, eta,
test_data=None):
"""Train the neural network using mini-batch stochastic
gradient descent. The "training_data" is a list of tuples
"(x, y)" representing the training inputs and the desired
outputs. The other non-optional parameters are
self-explanatory. If "test_data" is provided then the
network will be evaluated against the test data after each
epoch, and partial progress printed out. This is useful for
tracking progress, but slows things down substantially."""
if test_data: n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
random.shuffle(training_data)
mini_batches = [
training_data[k:k+mini_batch_size]
for k in xrange(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.update_mini_batch(mini_batch, eta)
if test_data:
print "Epoch {0}: {1} / {2}".format(
j, self.evaluate(test_data), n_test)
else:
print "Epoch {0} complete".format(j)
Look at the code. For each epoch, we randomly generate a subset of the inputs for the gradient descent algorithm. Why epoch is effective is also explained in the page. Please take a look.
You may:
Find: (\w)
Replace With: \L$1
Or select the text, ctrl+K+L.
It will work for that code sometimes need both properties
android:layout_gravity="center"
android:layout_centerHorizontal="true"
You can do it using array module. array module is part of python standard library:
from array import array
from itertools import repeat
a = array("i", repeat(0, 10))
# or
a = array("i", [0]*10)
repeat function repeats 0 value 10 times. It's more memory efficient than [0]*10, since it doesn't allocate memory, but repeats returning the same number x number of times.
string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");
can be translated to:
string requestUri="";
if ((OperationURL[1] == "GET")
{
requestUri = _apiURL + "?e=" + GetRequestSignature();
}
else
{
requestUri = _apiURL + "?e=";
}
One way around this problem is to use stored procedures with an output parameter.
exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2
values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.
if I got it right, you can try
for item in [x for x in checklist if x not in mylist]:
print (item)
You could initialize ReturnDate on the model before sending it to the view.
In the controller:
[HttpGet]
public ActionResult SomeAction()
{
var viewModel = new MyActionViewModel
{
ReturnDate = System.DateTime.Now
};
return View(viewModel);
}
The solution below uses the preprocessor's stringize operator, allowing for a more elegant solution. It lets you define the enum terms in just one place for greater resilience against typos.
First, define your enum in the following way.
#define ENUM_TABLE \
X(ENUM_ONE), \
X(ENUM_TWO) \
#define X(a) a
typedef enum Foo {
ENUM_TABLE
} MyFooEnum;
#undef X
#define X(a) @#a
NSString * const enumAsString[] = {
ENUM_TABLE
};
#undef X
Now, use it in the following way:
// Usage
MyFooEnum t = ENUM_ONE;
NSLog(@"Enum test - t is: %@", enumAsString[t]);
t = ENUM_TWO;
NSLog(@"Enum test - t is now: %@", enumAsString[t]);
which outputs:
2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is: ENUM_ONE
2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is now: ENUM_TWO
@pixel's answer pointed me in the right direction.
Old question, but I did come across a similar situation. Don't think the above answer fully achieves what is needed. The missing piece is keychain
; install it if it isn't already.
sudo apt-get install keychain
Then add the following line to your ~/.bashrc
eval $(keychain --eval id_rsa)
This will start the ssh-agent
if it isn't running, connect to it if it is, load the ssh-agent
environment variables into your shell, and load your ssh key.
Change id_rsa
to whichever private key in ~/.ssh
you want to load.
Some useful options for keychain:
-q
Quiet mode--noask
Don't ask for the password upon start, but on demand when ssh key is actually used.Reference
In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController
.
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity)
method. There is no need to do it explicitly.
In case your primary key is int
you can use below code:
int id=(Integer) session.save(entity);
In case of string use below code:
String str=(String)session.save(entity);
Weak (Non-Identifying) Relationship
Entity is existence-independent of other enties
PK of Child doesn’t contain PK component of Parent Entity
Strong (Identifying) Relationship
Child entity is existence-dependent on parent
PK of Child Entity contains PK component of Parent Entity
Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.
SQL Developer provides this functionality too :
Double click the results grid cell, and click edit :
Then on top-right part of the pop up , "View As Text" (You can even see images..)
And that's it!
You have these options:
Collections.synchronizedList()
: you can wrap any List
implementation (ArrayList
, LinkedList
or a 3rd-party list). Access to every method (reading and writing) will be protected using synchronized
. When using iterator()
or enhanced for loop, you must manually synchronize the whole iteration. While iterating, other threads are fully blocked even from reading. You can also synchronize separately for each hasNext
and next
calls, but then ConcurrentModificationException
is possible.
CopyOnWriteArrayList
: it's expensive to modify, but wait-free to read. Iterators never throw ConcurrentModificationException
, they return a snapshot of the list at the moment of iterator creation even if the list is modified by another thread while iterating. Useful for infrequently updated lists. Bulk operations like addAll
are preferred for updates - the internal array is copied less many times.
Vector
: very much like synchronizedList(new ArrayList<>())
, but iteration is synchronized too. However, iterators can throw ConcurrentModificationException
if the vector is modified by another thread while iterating.
Other options:
Collections.unmodifiableList()
: lock-free, thread-safe, but non-modifiableList.of
& List.copyOf
: Another non-modifiable list in Java 9 and later.Queue
or Deque
might be an alternative if you only add/remove at the ends of the list and iterate the list. There's no access by index and no adding/removing at arbitrary places. They have multiple concurrent implementations with better performance and better concurrent access, but it's beyond the scope of this question. You can also have a look at JCTools, they contain more performant queue implementations specialized for single consumer or single producer.You could use former Instantiations product CodePro AnalytiX. This eclipse plugin provides you suchlike statistics in code metrics view. This is provided by Google free of charge.
var test_obj = from d in repository.DbPricing
join d1 in repository.DbOfficeProducts on d.OfficeProductId equals d1.Id
join d2 in repository.DbOfficeProductDetails on d1.ProductDetailsId equals d2.Id
select new
{
PricingId = d.Id,
LetterColor = d2.LetterColor,
LetterPaperWeight = d2.LetterPaperWeight
};
http://www.cybertechquestions.com/select-across-multiple-tables-in-entity-framework-resulting-in-a-generic-iqueryable_222801.html
If you are inside a batch script, you can use argument variable tricks to get the filesize:
filesize.bat:
@echo off
echo %~z1
This gives results like the ones you suggest in your question.
Type
help call
at the command prompt for all of the crazy variable manipulation options. Also see this article for more information.
Edit: This only works in Windows 2000 and later
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
A string in C# is always UTF-16, there is no way to "convert" it. The encoding is irrelevant as long as you manipulate the string in memory, it only matters if you write the string to a stream (file, memory stream, network stream...).
If you want to write the string to a XML file, just specify the encoding when you create the XmlWriter
Backup
..PLAIN
for Format USE INSERT COMMANDS
Use Column Inserts
if you want column names in your inserts.Backup
buttonOne difference is that:
:map
does nvo
== normal + (visual + select) + operator pending:map!
does ic
== insert + command-line modeas stated on help map-modes
tables.
So: map
does not map to all modes.
To map to all modes you need both :map
and :map!
.
public void Letters(JTextField a) {
a.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent e) {
char c = e.getKeyChar();
if (Character.isDigit(c)) {
e.consume();
}
if (Character.isLetter(c)) {
e.setKeyChar(Character.toUpperCase(c));
}
}
});
}
public void Numbers(JTextField a) {
a.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent e) {
char c = e.getKeyChar();
if (!Character.isDigit(c)) {
e.consume();
}
}
});
}
public void Caracters(final JTextField a, final int lim) {
a.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent ke) {
if (a.getText().length() == lim) {
ke.consume();
}
}
});
}
You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
Life span of java Thread is over after completion of run()
method. Same thread can't be started again.
Looper transforms normal Thread
into a message loop. Key methods of Looper
are :
void prepare ()
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().
void loop ()
Run the message queue in this thread. Be sure to call quit() to end the loop.
void quit()
Quits the looper.
Causes the loop() method to terminate without processing any more messages in the message queue.
This mindorks article by Janishar explains the core concepts in nice way.
Looper
is associated with a Thread. If you need Looper
on UI thread, Looper.getMainLooper()
will return associated thread.
You need Looper
to be associated with a Handler.
Looper
, Handler
, and HandlerThread
are the Android’s way of solving the problems of asynchronous programming.
Once you have Handler
, you can call below APIs.
post (Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
boolean sendMessage (Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.
HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes
In some scenarios, you can't run Runnable
tasks on UI Thread.
e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream
In these cases, HandlerThread
is useful. You can get Looper
object from HandlerThread
and create a Handler
on HandlerThread
instead of main thread.
The HandlerThread code will be like this:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
Refer to below post for example code:
The simplest way is to edit .git/config
Here is an example file
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
[remote "origin"]
url = [email protected]:repo-name
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "test1"]
remote = origin
merge = refs/heads/test1
[branch "master"]
remote = origin
merge = refs/heads/master
Delete the line merge = refs/heads/test1
in the test1
branch section
How does spring know which polymorphic type to use.
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
Do I need @Qualifier or @Resource?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name
attribute of this annotation.
Why do we autowire the interface and not the implemented class?
Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Your bean configuration should look like this:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component
as follows:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Then worker
in MyRunner
will be injected with an instance of type B
.
For python version 2.x you can simply use
pip install pillow
But for python version 3.X you need to specify
(sudo) pip3 install pillow
when you enter pip in bash hit tab and you will see what options you have
Rewrite your query to:
select iu from internal_uddi iu where iu.urn....
description: http://forum.spring.io/forum/spring-projects/data/126415-is-it-possible-to-use-query-and-pageable?p=611398#post611398
Why not just: z/
That will highlight the current word under cursor and any other occurrences. And you don't have to give a separate command for each item you're searching for. Perhaps that's not available in the unholy gvim? It's in vim by default.
* is only good if you want the cursor to move to the next occurrence. When comparing two things visually you often don't want the cursor to move, and it's annoying to hit the * key every time.
I've solved this error by this way.
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;
Error still occurs, but I can handle response data in variable.
I had this question, but with a twist - I was trying to log different content to different files. I had information for a LowLevel debug log, and a HighLevel user log. I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.
My solution was to configure the 3 appenders, and then setup the logging like this:
log4j.threshold=ALL
log4j.rootLogger=,LowLogger
log4j.logger.HighLevel=ALL,Syslog,HighLogger
log4j.additivity.HighLevel=false
The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.
Hope this helps someone at some point!
In my case the Data provider entry for MySQL was "simply" missing in the machine.config file described above (though I had installed the MySQL connector properly)
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
Don't forget to put the right Version of your MySQL on the Entry
I got this after upgrading to ruby 2.1.0. My PATH
was set in my login script to include .gem/ruby/2.0.0/bin
. Updating the version number fixed it.
Another way-too-complicated workaround, with the benefit of not having to re-install the application as the previous workaround required. This requires that you have access to the msi (or a setup.exe with the msi embedded).
If you have Visual Studio 2012 (or possibly other editions) and install the free "InstallShield LE", then you can create a new setup project using InstallShield.
One of the configuration options in the "Organize your Setup" step is called "Upgrade Paths". Open the properties for Upgrade Paths, and in the left pane right click "Upgrade Paths" and select "New Upgrade Path" ... now browse to the msi (or setup.exe containing the msi) and click "open". The upgrade code will be populated for you in the settings page in the right pane which you should now see.
A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.
A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
I had the same error, but it was caused by the package manager process port being already used (port 8081).
To fix, I just ran the react-native
by specifying a different port, see below.
react-native run-ios --port 8090
you can use call back function, like this
$this->form_validation->set_rules('userfile', 'Document', 'callback_file_selected_test');
if ($this->form_validation->run() == FALSE) {
//error
}
else{
// success
}
function file_selected_test(){
$this->form_validation->set_message('file_selected_test', 'Please select file.');
if (empty($_FILES['userfile']['name'])) {
return false;
}else{
return true;
}
}
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
I know this is an old post but this solved my problem.
@font-face{_x000D_
font-family: "Font Name";_x000D_
src: url("../fonts/font-name.ttf") format("truetype");_x000D_
}
_x000D_
notice src:url("../fonts/font-name.ttf");
we use two periods to go back to the root directory and then into the fonts folder or wherever your file is located.
hope this helps someone down the line:) happy coding
As others have noted above, one way to do this is to convert your array to a string and then split the string inside SQL Server.
As of SQL Server 2016, there's a built-in way to split strings called
STRING_SPLIT()
It returns a set of rows that you can insert into your temp table (or real table).
DECLARE @str varchar(200)
SET @str = "123;456;789;246;22;33;44;55;66"
SELECT value FROM STRING_SPLIT(@str, ';')
would yield:
value ----- 123 456 789 246 22 33 44 55 66
If you want to get fancier:
DECLARE @tt TABLE (
thenumber int
)
DECLARE @str varchar(200)
SET @str = "123;456;789;246;22;33;44;55;66"
INSERT INTO @tt
SELECT value FROM STRING_SPLIT(@str, ';')
SELECT * FROM @tt
ORDER BY thenumber
would give you the same results as above (except the column name is "thenumber"), but sorted. You can use the table variable like any other table, so you can easily join it with other tables in the DB if you want.
Note that your SQL Server install has to be at compatibility level 130 or higher in order for the STRING_SPLIT()
function to be recognized. You can check your compatibility level with the following query:
SELECT compatibility_level
FROM sys.databases WHERE name = 'yourdatabasename';
Most languages (including C#) have a "join" function you can use to create a string from an array.
int[] myarray = {22, 33, 44};
string sqlparam = string.Join(";", myarray);
Then you pass sqlparam
as your parameter to the stored procedure above.
As Peter Mortensen wrote:
In the Visual Studio 2005 menu:
Debug -> New Breakpoint -> New Data Breakpoint
Enter: &myVariable
Additional information:
Obviously, the system must know which address in memory to watch.
So
- set a normal breakpoint to the initialisation of myVariable
(or myClass.m_Variable
)
- run the system and wait till it stops at that breakpoint.
- Now the Menu entry is enabled, and you can watch the variable by entering &myVariable
,
or the instance by entering &myClass.m_Variable
. Now the addresses are well defined.
Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.
In java 7 can now do
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
and w.close will be done automatically
It's not possible right now, on Netbeans 7.0.1 . The GUI tool to create columns on a tables is very limited and does not exist a plugin that offer that feature.
The Symlink command from the Sublime Text 3 documentation won't work as there is no ~/bin/
directory in Home location on Mac OS X El Capitan or later.
So, we'll need to place the symlink on the /usr/local/bin
as this path would be in our $PATH
variable in most cases.
So, the following command should do the trick:
ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl
Once you create the symlink correctly, you would be able to run the Sublime Text 3 like this: subl .
(. means the current directory)
In short:
someValues.forEach((element) => {
console.log(element);
});
If you care about index, then second parameter can be passed to receive the index of current element:
someValues.forEach((element, index) => {
console.log(`Current index: ${index}`);
console.log(element);
});
Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
I have same issue , i solved issue :
step-1 : download docker-compose using following command.
1. sudo su
2. sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
Step-2 : Run command
chmod +x /usr/local/bin/docker-compose
Step-3 : Check docker-compose version
docker-compose --version
Open up Xcode, and accept the new user agreement. This was happening because a new version of Xcode was downloaded and the new agreement was not accepted.
This still needs more refining however works with all simple references, without killing existing local names.
Type GlobalNamesToLocalNames_Type
Name As String
Sheet As String
Ref As String
End Type
Sub GlobalNamesToLocalNames(Optional Void As Variant)
Dim List() As GlobalNamesToLocalNames_Type
Dim Count As Long
Dim Name As Name
Dim Dat() As String
Dim X As Long
' count the size
For Each Name In ActiveWorkbook.Names
Count = Count + 1
Next
ReDim List(Count - 1)
Count = 0
' Collecect all name data
For Each Name In ActiveWorkbook.Names
With List(Count)
' Pick up only the name
If InStr(Name.Name, "!") > 0 Then
Dat = Split(Name.Name, "!")
.Name = Dat(1)
Else
.Name = Name.Name
End If
' pick up the sheet and refer
Dat = Split(Name.RefersTo, "!")
.Sheet = Mid(Dat(0), 2)
.Ref = Dat(1)
' make local sheet name
.Name = .Sheet & "!" & .Name
End With
Count = Count + 1
Next
' Delete all names
For Each Name In ActiveWorkbook.Names
Name.Delete
Next
'rebuild all the names
For X = 0 To Count - 1
With List(X)
If Left(.Ref, 1) <> "#" Then
ActiveWorkbook.Names.Add Name:=.Name, RefersToLocal:="=" & .Sheet & "!" & .Ref
End If
End With
Next
End Sub
Use OpenFileDialog.SafeFileName
OpenFileDialog.SafeFileName
Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.
Perfectly good example in the Autocomplete docs with source code.
jQuery
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 3,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
HTML
<div class="ui-widget">
<label for="city">Your city: </label>
<input id="city">
Powered by <a href="http://geonames.org">geonames.org</a>
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
Well, the basic premise here is: no, it is not secure yet.
Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.
The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.
As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.
Either that, or if you need that sort of security, and you need local storage, create a custom application...
For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.
For that need to add the 2021 partition into that table
ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS
Another easy way to execute a ps script from batch is to simply incorporate it between the ECHO and the Redirection characters,(> and >>), example:
@echo off
set WD=%~dp0
ECHO New-Item -Path . -Name "Test.txt" -ItemType "file" -Value "This is a text string." -Force > "%WD%PSHELLFILE.ps1"
ECHO add-content -path "./Test.txt" -value "`r`nThe End" >> "%WD%PSHELLFILE.ps1"
powershell.exe -ExecutionPolicy Bypass -File "%WD%PSHELLFILE.ps1"
del "%WD%PSHELLFILE.ps1"
Last line deletes the created temp file.
To get the currently logged in user path:
System.getProperty("user.home");
You cannot append to an existing xlsx file with xlsxwriter
.
There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close()
which will then write all of the information to your xlsx file.
Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...
i.e.
cells = []
for row in range(sheet.nrows):
cells.append([])
for col in range(sheet.ncols):
cells[row].append(workbook.cell(row, col).value)
You don't need arrays, though. For example, this works perfectly fine:
import xlrd
import xlsxwriter
from os.path import expanduser
home = expanduser("~")
# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
for col in range(20):
sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()
# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()
# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
newSheet = wb.add_worksheet(sheet.name)
for row in range(sheet.nrows):
for col in range(sheet.ncols):
newSheet.write(row, col, sheet.cell(row, col).value)
for row in range(10, 20): # write NEW data
for col in range(20):
newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes
However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()
).
As already pointed out, b += 1
updates b
in-place, while a = a + 1
computes a + 1
and then assigns the name a
to the result (now a
does not refer to a row of A
anymore).
To understand the +=
operator properly though, we need also to understand the concept of mutable versus immutable objects. Consider what happens when we leave out the .reshape
:
C = np.arange(12)
for c in C:
c += 1
print(C) # [ 0 1 2 3 4 5 6 7 8 9 10 11]
We see that C
is not updated, meaning that c += 1
and c = c + 1
are equivalent. This is because now C
is a 1D array (C.ndim == 1
), and so when iterating over C
, each integer element is pulled out and assigned to c
.
Now in Python, integers are immutable, meaning that in-place updates are not allowed, effectively transforming c += 1
into c = c + 1
, where c
now refers to a new integer, not coupled to C
in any way. When you loop over the reshaped arrays, whole rows (np.ndarray
's) are assigned to b
(and a
) at a time, which are mutable objects, meaning that you are allowed to stick in new integers at will, which happens when you do a += 1
.
It should be mentioned that though +
and +=
are meant to be related as described above (and very much usually are), any type can implement them any way it wants by defining the __add__
and __iadd__
methods, respectively.
sed 's/^.\{5\}//' logfile
and you replace 5 by the number you want...it should do the trick...
EDIT
if for each line
sed 's/^.\{5\}//g' logfile
In my case the problem occured when i forgot to add the =0 on one function in my pure virtual class. It was fixed when the =0 was added. The same as for Frank above.
class ISettings
{
public:
virtual ~ISettings() {};
virtual void OKFunction() =0;
virtual void ProblemFunction(); // missing =0
};
class Settings : ISettings
{
virtual ~Settings() {};
void OKFunction();
void ProblemFunction();
};
void Settings::OKFunction()
{
//stuff
}
void Settings::ProblemFunction()
{
//stuff
}