Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
|checked|unchecked|crossed|
|---|---|---|
|✓|_|✗|
Where
? via HTML Entity Code
? via HTML Entity Code
_ via underscore character
and table via markdown table syntax.
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
You can use a pseudo-element to insert that character before each list item:
ul {_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
content: '?';_x000D_
}
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;
ArrayList<String> recordings = new ArrayList<String>();
this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.
import UIKit
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource
{
var items: String[] = ["We", "Heart", "Swift","omnamay shivay","om namay bhagwate vasudeva nama"]
var cell : UITableViewCell
}
@IBOutlet var tableview:UITableView
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell
if !cell {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")}
cell!.textLabel.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
return true
}
func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
// handle delete (by removing the data from your array and updating the tableview)
if let tv=tableView
{
items.removeAtIndex(indexPath!.row)
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
}
}
See the correct way with your example:
<div ng-if="!test.view">1</div>
<div ng-if="!!test.view">2</div>
Regards, Nicholls
I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
The code from the example should not be difficult to adapt to your specific situation:
<script>
function Ctrl($scope) {
$scope.color = 'blue';
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color | json}}</tt><br/>
</form>
Also, using the awesome font, you can use the following tag. Simple and beautiful
With the possibility of changing the size and color and other features in CSS
See result here
Reference here 2.10.2.1 Troubleshooting Problems Starting the MySQL Server.
1.Find the data directory ,it was configured in my.cnf.
[mysqld]
datadir=/var/lib/mysql
2. Check the err file,it log the error message about why mysql server start failed. the name of err file is related with your hostname.
cd /var/lib/mysql
ll
tail (hostname).err
3.If you find some messages like :
InnoDB: Error: log file ./ib_logfile0 is of different size 0 33554432 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
170513 14:25:22 [ERROR] Plugin 'InnoDB' init function returned error.
170513 14:25:22 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
170513 14:25:22 [ERROR] Unknown/unsupported storage engine: InnoDB
170513 14:25:22 [ERROR] Aborting
then
delete ib_logfile0 and ib_logfile1
, then,
/etc/init.d/mysqld start
If you have callbacks with different parameters you can use templates as follows:
// compile with: g++ -std=c++11 myTemplatedCPPcallbacks.cpp -o myTemplatedCPPcallbacksApp
#include <functional> // c++11
#include <iostream> // due to: cout
using std::cout;
using std::endl;
class MyClass
{
public:
MyClass();
static void Callback(MyClass* instance, int x);
private:
int private_x;
};
class OtherClass
{
public:
OtherClass();
static void Callback(OtherClass* instance, std::string str);
private:
std::string private_str;
};
class EventHandler
{
public:
template<typename T, class T2>
void addHandler(T* owner, T2 arg2)
{
cout << "\nHandler added..." << endl;
//Let's pretend an event just occured
owner->Callback(owner, arg2);
}
};
MyClass::MyClass()
{
EventHandler* handler;
private_x = 4;
handler->addHandler(this, private_x);
}
OtherClass::OtherClass()
{
EventHandler* handler;
private_str = "moh ";
handler->addHandler(this, private_str );
}
void MyClass::Callback(MyClass* instance, int x)
{
cout << " MyClass::Callback(MyClass* instance, int x) ==> "
<< 6 + x + instance->private_x << endl;
}
void OtherClass::Callback(OtherClass* instance, std::string private_str)
{
cout << " OtherClass::Callback(OtherClass* instance, std::string private_str) ==> "
<< " Hello " << instance->private_str << endl;
}
int main(int argc, char** argv)
{
EventHandler* handler;
handler = new EventHandler();
MyClass* myClass = new MyClass();
OtherClass* myOtherClass = new OtherClass();
}
For angular 4 I have used
<img [src]="data.pic ? data.pic : 'assets/images/no-image.png' " alt="Image" title="Image">
It works for me , I hope it may use to other's also for Angular 4-5
. :)
The regular expression for this is really simple. Just use a character class. The hyphen is a special character in character classes, so it needs to be first:
/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/
You also need to escape the other regular expression metacharacters.
Edit: The hyphen is special because it can be used to represent a range of characters. This same character class can be simplified with ranges to this:
/[$-/:-?{-~!"^_`\[\]]/
There are three ranges. '$' to '/', ':' to '?', and '{' to '~'. the last string of characters can't be represented more simply with a range: !"^_`[].
Use an ACSII table to find ranges for character classes.
Late answer, but you can also use on("change")
$('#check').on('change', function() {
var checked = this.checked
$('span').html(checked.toString())
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="check"> <span>Check me!</span>
_x000D_
You can create an extension function or just use setCompoundDrawablesWithIntrinsicBounds
directly.
fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
If you need to resize the drawable, you can use this extension function.
textView.leftDrawable(R.drawable.my_icon, R.dimen.icon_size)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
To get really fancy, create a wrapper that allows size and/or color modification.
textView.leftDrawable(R.drawable.my_icon, colorRes = R.color.white)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int = 0, @ColorInt color: Int = 0, @ColorRes colorRes: Int = 0) {
val drawable = drawable(id)
if (sizeRes != 0) {
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
}
if (color != 0) {
drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
} else if (colorRes != 0) {
val colorInt = ContextCompat.getColor(context, colorRes)
drawable?.setColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)
}
this.setCompoundDrawables(drawable, null, null, null)
}
I realize that an answer was already been selected, but I just wanted to share what ended up working for me when I ran into this issue.
I had a listView where each entry in the listView was defined by its own layout, similar to what Sammy posted in his question. I tried the suggested approach of changing the divider height, but that did not end up looking all too pretty, even with an invisible divider. After some experimentation, I simply added an android:paddingBottom="5dip"
to the last TextView layout element in the XML file that defines individual listView entries.
This ended up giving me exactly what I was trying to achieve via the use of android:layout_marginBottom
. I found this solution to produce a more aesthetically pleasing result than trying to increase the divider height.
Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use ✓
for ✓ and ✗
for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.
As mentioned in the comments, ✓
and ✗
are not supported in HTML4, so you may be better off using the more cryptic ✓
and ✗
if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.
you could use ⊕ or ⊗
The cause of your problem is NOT the Win console not willing to accept Unicode (as it does this since I guess Win2k by default). It is the default system encoding. Try this code and see what it gives you:
import sys
sys.getdefaultencoding()
if it says ascii, there's your cause ;-) You have to create a file called sitecustomize.py and put it under python path (I put it under /usr/lib/python2.5/site-packages, but that is differen on Win - it is c:\python\lib\site-packages or something), with the following contents:
import sys
sys.setdefaultencoding('utf-8')
and perhaps you might want to specify the encoding in your files as well:
# -*- coding: UTF-8 -*-
import sys,time
Edit: more info can be found in excellent the Dive into Python book
If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.
Nice...
Try this to remove an specific cron job (tested).
<?php $output = shell_exec('crontab -l'); ?>
<?php $cron_file = "/tmp/crontab.txt"; ?>
<!-- Execute script when form is submitted -->
<?php if(isset($_POST['add_cron'])) { ?>
<!-- Add new cron job -->
<?php if(!empty($_POST['add_cron'])) { ?>
<?php file_put_contents($cron_file, $output.$_POST['add_cron'].PHP_EOL); ?>
<?php } ?>
<!-- Remove cron job -->
<?php if(!empty($_POST['remove_cron'])) { ?>
<?php $remove_cron = str_replace($_POST['remove_cron']."\n", "", $output); ?>
<?php file_put_contents($cron_file, $remove_cron.PHP_EOL); ?>
<?php } ?>
<!-- Remove all cron jobs -->
<?php if(isset($_POST['remove_all_cron'])) { ?>
<?php echo exec("crontab -r"); ?>
<?php } else { ?>
<?php echo exec("crontab $cron_file"); ?>
<?php } ?>
<!-- Reload page to get updated cron jobs -->
<?php $uri = $_SERVER['REQUEST_URI']; ?>
<?php header("Location: $uri"); ?>
<?php exit; ?>
<?php } ?>
<b>Current Cron Jobs:</b><br>
<?php echo nl2br($output); ?>
<h2>Add or Remove Cron Job</h2>
<form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>">
<b>Add New Cron Job:</b><br>
<input type="text" name="add_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<b>Remove Cron Job:</b><br>
<input type="text" name="remove_cron" size="100" placeholder="e.g.: * * * * * /usr/local/bin/php -q /home/username/public_html/my_cron.php"><br>
<input type="checkbox" name="remove_all_cron" value="1"> Remove all cron jobs?<br>
<input type="submit"><br>
</form>
If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.
That data:image/png;base64
URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.
Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.
Haha, I have been stuck at that point a while ago as well, so I am glad I can help you out with a solution, that worked for me at least :)
What you want to do is define a new style within values/styles.xml so it looks like this
<resources>
<style name = "AppTheme" parent = "android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name = "NoActionBar" parent = "@android:style/Theme.Holo.Light">
<item name = "android:windowActionBar">false</item>
<item name = "android:windowNoTitle">true</item>
</style>
</resources>
Only the NoActionBar style is intresting for you. At last you have to set is as your application's theme in the AndroidManifest.xml so it looks like this
<application
android:allowBackup = "true"
android:icon = "@drawable/ic_launcher"
android:label = "@string/app_name"
android:theme = "@style/NoActionBar" <!--This is the important line-->
>
<activity
[...]
I hope this helps, if not, let me know.
It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15
I have 3 spinners
Spinner c_fruit=(Spinner) findViewById(R.id.fruits);
Spinner c_vegetable=(Spinner) findViewById(R.id.vegetables);
Spinner c_beverage=(Spinner) findViewById(R.id.beverages);
And also I have a Async-Tack class.
Here is my spinner loading code
RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.where="Get_fruit_List";
reqs_fruit.title="Loading fruit";
reqs_fruit.execute();
RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.where="Get_vegetable_List";
reqs_vegetable.title="Loading vegetable";
reqs_vegetable.execute();
RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.where="Get_beverage_List";
reqs_beverage.title="Loading beverage";
reqs_beverage.execute();
This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.
Here is my Async-task class
public class RequestSend extends AsyncTask<String, String, String > {
private ProgressDialog dialog = null;
public Spinner spin;
public String where;
public String title;
Context con;
Activity activity;
String[] items;
public RequestSend(Context activityContext) {
con = activityContext;
dialog = new ProgressDialog(activityContext);
this.activity = activityContext;
}
@Override
protected void onPostExecute(String result) {
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
} catch (NullPointerException e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle(title);
dialog.setMessage("Wait...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected String doInBackground(String... Strings) {
try {
Send_Request();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void Send_Request() throws JSONException {
try {
String DataSendingTo = "http://www.example.com/AppRequest/" + where;
//HttpClient
HttpClient httpClient = new DefaultHttpClient();
//Post header
HttpPost httpPost = new HttpPost(DataSendingTo);
//Adding data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("authorized","001"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line) ;
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
items = new String[finalResult.length()];
// looping through All details and store in public String array
for(int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
items[i]=c.getString("data_name");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Idea is to wrap the element & unwrap the contents:
function renameElement($element,newElement){
$element.wrap("<"+newElement+">");
$newElement = $element.parent();
//Copying Attributes
$.each($element.prop('attributes'), function() {
$newElement.attr(this.name,this.value);
});
$element.contents().unwrap();
return $newElement;
}
Sample usage:
renameElement($('p'),'h5');
By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.
On demand, now as an answer...
When using MySQL Query Browser or phpMyAdmin, it appears that a new connection is opened for each query (bugs.mysql.com/bug.php?id=8280), making it neccessary to write all the drop statements in one query, eg.
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE my_first_table_to_drop;
DROP TABLE my_second_table_to_drop;
SET FOREIGN_KEY_CHECKS=1;
Where the SET FOREIGN_KEY_CHECKS=1
serves as an extra security measure...
unsorted_list.sort(key=lambda x: x[3])
Perhaps your main
function has been commented out because of e.g. preprocessing.
To learn what preprocessing is doing, try gcc -C -E es3.c > es3.i
then look with an editor into the generated file es3.i (and search main
inside it).
First, you should always (since you are a newbie) compile with
gcc -Wall -g -c es3.c
gcc -Wall -g es3.o -o es3
The -Wall
flag is extremely important, and you should always use it. It tells the compiler to give you (almost) all warnings. And you should always listen to the warnings, i.e. correct your source code file es3.C
till you got no more warnings.
The -g
flag is important also, because it asks gcc
to put debugging information in the object file and the executable. Then you are able to use a debugger (like gdb
) to debug your program.
To get the list of symbols in an object file or an executable, you can use nm
.
Of course, I'm assuming you use a GNU/Linux system (and I invite you to use GNU/Linux if you don't use it already).
The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto
but is easier for the eyes :)
git cherry-pick quickfix1..quickfix2
I think it is in fact desirable to have sudo reset the PATH: otherwise an attacker having compromised your user account could put backdoored versions of all kinds of tools on your users' PATH, and they would be executed when using sudo.
(of course having sudo reset the PATH is not a complete solution to these kinds of problems, but it helps)
This is indeed what happens when you use
Defaults env_reset
in /etc/sudoers without using exempt_group
or env_keep
.
This is also convenient because you can add directories that are only useful for root (such as /sbin
and /usr/sbin
) to the sudo path without adding them to your users' paths. To specify the path to be used by sudo:
Defaults secure_path="/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin"
Here is possibly the fastest way to query a large number of rows with Dapper using a list of IDs. I promise you this is faster than almost any other way you can think of (with the possible exception of using a TVP as given in another answer, and which I haven't tested, but I suspect may be slower because you still have to populate the TVP). It is planets faster than Dapper using IN
syntax and universes faster than Entity Framework row by row. And it is even continents faster than passing in a list of VALUES
or UNION ALL SELECT
items. It can easily be extended to use a multi-column key, just add the extra columns to the DataTable
, the temp table, and the join conditions.
public IReadOnlyCollection<Item> GetItemsByItemIds(IEnumerable<int> items) {
var itemList = new HashSet(items);
if (itemList.Count == 0) { return Enumerable.Empty<Item>().ToList().AsReadOnly(); }
var itemDataTable = new DataTable();
itemDataTable.Columns.Add("ItemId", typeof(int));
itemList.ForEach(itemid => itemDataTable.Rows.Add(itemid));
using (SqlConnection conn = GetConnection()) // however you get a connection
using (var transaction = conn.BeginTransaction()) {
conn.Execute(
"CREATE TABLE #Items (ItemId int NOT NULL PRIMARY KEY CLUSTERED);",
transaction: transaction
);
new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, transaction) {
DestinationTableName = "#Items",
BulkCopyTimeout = 3600 // ridiculously large
}
.WriteToServer(itemDataTable);
var result = conn
.Query<Item>(@"
SELECT i.ItemId, i.ItemName
FROM #Items x INNER JOIN dbo.Items i ON x.ItemId = i.ItemId
DROP TABLE #Items;",
transaction: transaction,
commandTimeout: 3600
)
.ToList()
.AsReadOnly();
transaction.Rollback(); // Or commit if you like
return result;
}
}
Be aware that you need to learn a little bit about Bulk Inserts. There are options about firing triggers (the default is no), respecting constraints, locking the table, allowing concurrent inserts, and so on.
Since Java arrays hold a fixed number of values, you need to create a new array with a length of 5 in this case. A better solution would be to use an ArrayList and simply add strings to the array.
Example:
ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test3");
scripts.add("test4");
scripts.add("test5");
// Then later you can add more Strings to the ArrayList
scripts.add("test1");
scripts.add("test2");
If installing on Ubuntu using apt-get, try /usr/share/nginx/www
.
EDIT:
On more recent versions the path has changed to:
/usr/share/nginx/html
2019 EDIT:
Might try in /var/www/html/index.nginx-debian.html
too.
Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x
first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql
command line client, it's useful to use \x
to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.
I noticed the exact same issue when logging onto servers running Red Hat from an OSX Lion machine.
Try adding or editing the ~/.profile
file for it to correctly export your locale settings upon initiating a new session.
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
These two lines added to the file should suffice to set the locale [replace en_US
for your desired locale, and check beforehand that it is indeed installed on your system (locale -a
)].
After that, you can start a new session and check using locale
:
$ locale
The following should be the output:
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/
URL. Upon success, it removes all items from dropdown list with id
= OfferTransModel_ItemID
and then it fills it with new items based on AJAX call's result:
if (productgrpid != 0) {
$.ajax({
type: "POST",
url: "/Ajax/_AjaxGetItemListHelp/",
data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
contentType: "application/json",
dataType: "json",
success: function (data) {
$("#OfferTransModel_ItemID").empty();
$.each(data, function () {
$("#OfferTransModel_ItemID").append($("<option>
</option>").val(this['ITEMID']).html(this['ITEMDESC']));
});
}
});
}
Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID
and ITEMDESC
elements. For example:
{
{
"ITEMID":"13",
"ITEMDESC":"About"
},
{
"ITEMID":"21",
"ITEMDESC":"Contact"
}
}
The OfferTransModel_ItemID
listbox is populated with above data and its code should look like:
<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
<option value="13">About</option>
<option value="21">Contact</option>
</select>
When user selects About
, form submits 13
as value for this field and 21
when user selects Contact
and so on.
Fell free to modify above code if your server returns URL in a different format.
I think it's a lot easier to use NSNumbers. This all you need to do:
NSNumber *myNum1 = [NSNumber numberWithInt:myNsIntValue1];
NSNumber *myNum2 = [NSNumber numberWithInt:myNsIntValue2];
.
.
.
NSArray *myArray = [NSArray arrayWithObjects: myNum1, myNum2, ..., nil];
You can also get the value of an item in the jObject like this:
JToken value;
if (json.TryGetValue(key, out value))
{
DoSomething(value);
}
SQL stands for Structured Query Language, and is the basis for which all Relational Database Management Systems allow the user to add, remove, update, or select records. Things like MySQ are the actual Management Systems which allow you to store and retrieve your data, whereas SQL is the actual language to do so.
The basic SQL is somewhat universal - Selects usually look the same, Inserts, Updates, Deletes, etc. Once you get beyond the basics, the commands and abilities of your individual Databases vary, and this is where you get people who are Oracle experts, MySQL, SQL Server, etc.
Basically, MySQL is one of many books holding everything, and SQL is how you go about reading that book.
A bit too late, but this solution is nice and neat
const arr = [[1,2,3],[4,5,6],[7,8,9,10]]
for (let i of arr) {
for (let j of i) {
console.log(j) //Should log numbers from 1 to 10
}
}
Or in your case:
const arr = [[1,2,3],[4,5,6],[7,8,9]]
for (let [d1, d2, d3] of arr) {
console.log(`${d1}, ${d2}, ${d3}`) //Should return numbers from 1 to 9
}
Note: for ... of
loop is standardised in ES6, so only use this if you have an ES5 Javascript Complier (such as Babel)
Another note: There are alternatives, but they have some subtle differences and behaviours, such as forEach()
, for...in
, for...of
and traditional for()
. It depends on your case to decide which one to use. (ES6 also has .map()
, .filter()
, .find()
, .reduce()
)
You should look at MoSync too, MoSync gives you standard C/C++, easy-to-use well-documented APIs, and a full-featured Eclipse-based IDE. Its now a open sourced IDE still pretty cool but not maintained anymore.
You may need to declare the radio buttons in the onCreate method of your code and use them.
RadioButton rb1 = (RadioButton) findViewById(R.id.option1);
rb1.setChecked(true);
String message = URLEncoder.encode("my message", "UTF-8");
try {
// instantiate the URL object with the target URL of the resource to
// request
URL url = new URL("http://www.example.com/comment");
// instantiate the HttpURLConnection with the URL object - A new
// connection is opened every time by calling the openConnection
// method of the protocol handler for this URL.
// 1. This is the point where the connection is opened.
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set connection output to true
connection.setDoOutput(true);
// instead of a GET, we're going to send using method="POST"
connection.setRequestMethod("POST");
// instantiate OutputStreamWriter using the output stream, returned
// from getOutputStream, that writes to this connection.
// 2. This is the point where you'll know if the connection was
// successfully established. If an I/O error occurs while creating
// the output stream, you'll see an IOException.
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
// write data to the connection. This is data that you are sending
// to the server
// 3. No. Sending the data is conducted here. We established the
// connection with getOutputStream
writer.write("message=" + message);
// Closes this output stream and releases any system resources
// associated with this stream. At this point, we've sent all the
// data. Only the outputStream is closed at this point, not the
// actual connection
writer.close();
// if there is a response code AND that response code is 200 OK, do
// stuff in the first if block
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
// otherwise, if any other status code is returned, or no status
// code is returned, do stuff in the else block
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
The first 3 answers to your questions are listed as inline comments, beside each method, in the example HTTP POST above.
From getOutputStream:
Returns an output stream that writes to this connection.
Basically, I think you have a good understanding of how this works, so let me just reiterate in layman's terms. getOutputStream
basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see getOutputStream
, you're opening the connection stream for writing, but you don't actually write any data until you call writer.write("message=" + message);
.
From getInputStream():
Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.
getInputStream
does the opposite. Like getOutputStream
, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a SocketTimeoutException
.
How about the getInputStream? Since I'm only able to get the response at getInputStream, then does it mean that I didn't send any request at getOutputStream yet but simply establishes a connection?
Keep in mind that sending a request and sending data are two different operations. When you invoke getOutputStream or getInputStream url.openConnection()
, you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.
In layman's terms, making a getInputStream
request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.
Using a similar example for getOutputStream
would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.
Now, continuing with the layman's example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in layman's terms.)
Question #5:
Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.
openConnection
creates a new connection object. From the URL.openConnection javadocs:
A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.
The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.
Question #6:
To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:
long start = System.currentTimeMillis();
log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );
// run the above example code here
log.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );
I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.
For information on closing connections, which you didn't ask about, see In Java when does a URL connection close?.
Here i have done complete bins for above query. below is demo link, i think it may help you
Demo: http://codebins.com/bin/4ldqp9b/1
HTML:
<div id="edge">
<div class="box" style="top:20; background:#f8a2a4;">
</div>
<div class="box" style="top:70; background:#a2f8a4;">
</div>
<div class="box" style="top:120; background:#5599fd;">
</div>
</div>
<br/>
<input type="button" id="btnAnimate" name="btnAnimate" value="Animate" />
CSS:
body{
background:#ffffef;
}
#edge{
width:500px;
height:200px;
border:1px solid #3377af;
padding:5px;
}
.box{
position:absolute;
left:10;
width:40px;
height:40px;
border:1px solid #a82244;
}
JQuery:
$(function() {
$("#btnAnimate").click(function() {
var move = "";
if ($(".box:eq(0)").css('left') == "10px") {
move = "+=" + ($("#edge").width() - 35);
} else {
move = "-=" + ($("#edge").width() - 35);
}
$(".box").animate({
left: move
}, 500, function() {
if ($(".box:eq(0)").css('left') == "475px") {
$(this).css('background', '#afa799');
} else {
$(".box:eq(0)").css('background', '#f8a2a4');
$(".box:eq(1)").css('background', '#a2f8a4');
$(".box:eq(2)").css('background', '#5599fd');
}
});
});
});
The binary operators =
(assignment), []
(array subscription), ->
(member access), as well as the n-ary ()
(function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.
Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators <<
and >>
, whose left operands are stream classes from the standard library which you cannot change.
For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:
Of course, as with all rules of thumb, there are exceptions. If you have a type
enum Month {Jan, Feb, ..., Nov, Dec}
and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<()
for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.
(However, if you make an exception, do not forget the issue of const
-ness for the operand that, for member functions, becomes the implicit this
argument. If the operator as a non-member function would take its left-most argument as a const
reference, the same operator as a member function needs to have a const
at the end to make *this
a const
reference.)
Continue to Common operators to overload.
array hash_algos(void)
echo hash('sha384', 'Message to be hashed'.'salt');
Here is a link to reference http://php.net/manual/en/function.hash.php
Following will give you active connections/ queries in postgres DB-
SELECT
pid
,datname
,usename
,application_name
,client_hostname
,client_port
,backend_start
,query_start
,query
,state
FROM pg_stat_activity
WHERE state = 'active';
You may use 'idle' instead of active to get already executed connections/queries.
For MIUI OS Device
1) Go to Setting
2) Scroll down to Additional Setting
3) You will find Developer option at bottom
4) Turn this on - Install via USB: Toggle On
By turning this on, It is working charm in my MIUI8 device.
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
This means the remote vm is not listening to current port i solved this by adding the port in the vm server
See if this helps. I can set variables for Elapsed Days, Hours, Minutes, Seconds. You can format this to your liking or include in a user defined function.
Note: Don't use DateDiff(hh,@Date1,@Date2). It is not reliable! It rounds in unpredictable ways
Given two dates... (Sample Dates: two days, three hours, 10 minutes, 30 seconds difference)
declare @Date1 datetime = '2013-03-08 08:00:00'
declare @Date2 datetime = '2013-03-10 11:10:30'
declare @Days decimal
declare @Hours decimal
declare @Minutes decimal
declare @Seconds decimal
select @Days = DATEDIFF(ss,@Date1,@Date2)/60/60/24 --Days
declare @RemainderDate as datetime = @Date2 - @Days
select @Hours = datediff(ss, @Date1, @RemainderDate)/60/60 --Hours
set @RemainderDate = @RemainderDate - (@Hours/24.0)
select @Minutes = datediff(ss, @Date1, @RemainderDate)/60 --Minutes
set @RemainderDate = @RemainderDate - (@Minutes/24.0/60)
select @Seconds = DATEDIFF(SS, @Date1, @RemainderDate)
select @Days as ElapsedDays, @Hours as ElapsedHours, @Minutes as ElapsedMinutes, @Seconds as ElapsedSeconds
Write your event handler declaration like this:
<a href="#" onclick="myFunc(event,1,2,3)">click</a>
Then your "myFunc()" function can access the event.
The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:
theAnchor.onclick = new Function("event", theOnclickString);
(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.
<input type="text" autocomplete="off" />
You could also use the whitelist method -
var str = $('#Search').val();
var regex = /[^\w\s]/gi;
if(regex.test(str) == true) {
alert('Your search string contains illegal characters.');
}
The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.
OnClientClick="SomeMethod()"
event of that BUTTON, it return by default "true
" so after that function it do postback
for solution use
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
You can try it like this
Calendar c= Calendar.getInstance();
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
String str=sdf.format(c.getTime());
I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method.
public String registerUser(UserRegistrationFormBean userRegistrationFormBean,
RequestContext requestContext,
ExternalContext externalContext) {
try {
Locale userLocale = requestContext.getExternalContext().getLocale();
this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID);
String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress();
String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword();
doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest());
return "success";
} catch (EmailAddressNotUniqueException e) {
MessageResolver messageResolvable
= new MessageBuilder().error()
.source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS)
.code("userRegistration.emailAddress.not.unique")
.build();
requestContext.getMessageContext().addMessage(messageResolvable);
return "error";
}
}
private void doAutoLogin(String username, String password, HttpServletRequest request) {
try {
// Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = this.authenticationProvider.authenticate(token);
logger.debug("Logging in with [{}]", authentication.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (Exception e) {
SecurityContextHolder.getContext().setAuthentication(null);
logger.error("Failure in autoLogin", e);
}
}
$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used
Smoke Testing
Smoke testing is a wide approach where all areas of the software application are tested without getting into too deep
The test cases for smoke testing of the software can be either manual or automated
Smoke testing is done to ensure whether the main functions of the software application are working or not. During smoke testing of the software, we do not go into finer details.
Smoke testing of the software application is done to check whether the build can be accepted for through software testing
This testing is performed by the developers or testers
Smoke testing exercises the entire system from end to end
Smoke testing is like General Health Check Up
Smoke testing is usually documented or scripted
Santy Testing
Sanity software testing is a narrow regression testing with a focus on one or a small set of areas of functionality of the software application.
Sanity test is generally without test scripts or test cases.
Sanity testing is a cursory software testing type. It is done whenever a quick round of software testing can prove that the software application is functioning according to business / functional requirements.
Sanity testing of the software is to ensure whether the requirements are met or not.
Sanity testing is usually performed by testers
Sanity testing exercises only the particular component of the entire system
Sanity Testing is like specialized health check up
Sanity testing is usually not documented and is unscripted
For more visit Link
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
Instead of this:
String char = name.substring(0,1); //char="a"
You should use the charAt()
method.
char c = name.charAt(0); // c='a'
int ascii = (int)c;
I've done my own jquery ui widget, just thinking if it's good enough.
I tried using Google reCAPTCHA explicitly. Here is the example:
// put somewhere in your index.html
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('your-recaptcha-element', {
'sitekey' : '6Ldcfv8SAAAAAB1DwJTM6T7qcJhVqhqtss_HzS3z'
});
};
//link function of Angularjs directive
link: function (scope, element, attrs) {
...
var domElem = '<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>';
$('#your-recaptcha-element').append($compile(domElem)(scope));
}
To choose a different location or file type (e.g. PNG or SVG) for the favicon:
One reason can be that you want to have the icon in a specific location, perhaps in the images folder or something alike. For example:
<link rel="icon" href="_/img/favicon.png">
This diferent location may even be a CDN, just like SO seems to do with <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
.
To learn more about using other file types like PNG check out this question.
For cache busting purposes:
Add a query string to the path for cache-busting purposes:
<link rel="icon" href="/favicon.ico?v=1.1">
Favicons are very heavily cached and this a great way to ensure a refresh.
Footnote about default location:
As far as the first bit of the question: all modern browsers would detect a favicon at the default location, so that's not a reason to use a link
for it.
Footnote about rel="icon"
:
As indicated by @Semanino's answer, using rel="shortcut icon"
is an old technique which was required by older versions of Internet Explorer, but in most cases can be replaced by the more correct rel="icon"
instruction. The article @Semanino based this on properly links to the appropriate spec which shows a rel
value of shortcut
isn't a valid option.
On many source packages (e.g. for most GNU software), the building system may know about the DESTDIR
make variable, so you can often do:
make install DESTDIR=/tmp/myinst/
sudo cp -va /tmp/myinst/ /
The advantage of this approach is that make install
don't need to run as root, so you cannot end up with files compiled as root (or root-owned files in your build tree).
try this
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
Use -b:a
instead of -ab
as -ab
is outdated now, also make sure your input file path is correct.
To extract audio from a video I have used below command and its working fine.
String[] complexCommand = {"-y", "-i", inputFileAbsolutePath, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "256k", "-f", "mp3", outputFileAbsolutePath};
Here,
-y
- Overwrite output files without asking.-i
- FFmpeg reads from an arbitrary number of input “files” specified by the -i
option-vn
- Disable video recording-ar
- sets the sampling rate for audio streams if encoded-ac
- Set the number of audio channels.-b:a
- Set the audio bitrate-f
- formatCheck out this for my complete sample FFmpeg android project on GitHub.
I had a similar error in creating foreign key in a Many to Many table where the primary key consisted of 2 foreign keys and another normal column. I fixed the issue by correcting the referenced table name i.e. company, as shown in the corrected code below:
create table company_life_cycle__history -- (M-M)
(
company_life_cycle_id tinyint unsigned not null,
Foreign Key (company_life_cycle_id) references company_life_cycle(id) ON DELETE CASCADE ON UPDATE CASCADE,
company_id MEDIUMINT unsigned not null,
Foreign Key (company_id) references company(id) ON DELETE CASCADE ON UPDATE CASCADE,
activity_on date NOT NULL,
PRIMARY KEY pk_company_life_cycle_history (company_life_cycle_id, company_id,activity_on),
created_on datetime DEFAULT NULL,
updated_on datetime DEFAULT NULL,
created_by varchar(50) DEFAULT NULL,
updated_by varchar(50) DEFAULT NULL
);
Here is one equivalent of the accepted answer for the UTF-8 world.
if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
//Disallowed Character In $string
}
Explanation:
Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.
In datasets having large number of columns its even better to see how many columns contain null values and how many don't.
print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))
print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))
print("Total no. of columns in the dataframe")
print(len(df.columns))
For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.
Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:
df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)
Note: Above code removes all of your null values. If you want null values, process them before.
The id of the input seems is not WallSearch
. Maybe you're confusing that name
and id
. They are two different properties. name
is used to define the name by which the value is posted, while id
is the unique identification of the element inside the DOM.
Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value
property.
If you are accessing scoped beans within Spring Web MVC, i.e. within a request that is processed by the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state.
If you are runnning outside of Spring MVC ( Not processed by DispatchServlet) you have to use the RequestContextListener
Not just ContextLoaderListener
.
Add the following in your web.xml
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
That will provide session to Spring in order to maintain the beans in that scope
Update :
As per other answers , the @Controller
only sensible when you are with in Spring MVC Context, So the @Controller is not serving actual purpose in your code. Still you can inject your beans into any where with session scope / request scope ( you don't need Spring MVC / Controller to just inject beans in particular scope) .
Update :
RequestContextListener exposes the request to the current Thread only.
You have autowired ReportBuilder in two places
1. ReportPage
- You can see Spring injected the Report builder properly here, because we are still in Same web Thread. i did changed the order of your code to make sure the ReportBuilder injected in ReportPage like this.
log.info("ReportBuilder name: {}", reportBuilder.getName());
reportController.getReportData();
i knew the log should go after as per your logic , just for debug purpose i added .
2. UselessTasklet
- We got exception , here because this is different thread created by Spring Batch , where the Request is not exposed by RequestContextListener
.
You should have different logic to create and inject ReportBuilder
instance to Spring Batch ( May Spring Batch Parameters and using Future<ReportBuilder>
you can return for future reference)
the problem is you're trying to use regex features not supported by grep. namely, your \d
won't work. use this instead:
REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?
you need the -E
flag to get ERE in order to use {#}
style.
For those who use Tomcat with Bitronix, this will fix the problem:
The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.
In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:
(if you already used them, make sure your references are correct):
e.g.
-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59"
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties"
Now, restart your server and check the log.
I needed the same and this solution worked the most simple and straightforward way:
http://www.farinspace.com/jquery-scrollable-table-plugin/
I just give an id
to the table I want to scroll and put one line in Javascript. That's it!
By the way, first I also thought I want to use a scrollable div, but it is not necessary at all. You can use a div and put it into it, but this solution does just what we need: scrolls the table.
Here's possibly the simplest way:
IO.copy_stream(URI.open("https://i.pinimg.com/originals/24/17/d6/2417d6b3f3dc236b0b5b80fb00b3a791.png"), 'destination.png')
I have not used BeuatifulSoup but maybe the following can help in some tiny way.
import re
import urllib2
stuff = urllib2.urlopen(your_url_goes_here).read() # stuff will contain the *entire* page
# Replace the string Python with your desired regex
results = re.findall('(Python)',stuff)
for i in results:
print i
I'm not suggesting this is a replacement but maybe you can glean some value in the concept until a direct answer comes along.
Although there are many acceptable answers in response to this question, I don't see any examples of the sub
method using the \Datetime
object: https://www.php.net/manual/en/datetime.sub.php
So, for reference, you can also use a \DateInterval
to modify a \Datetime
object:
$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));
echo $date->format('Y-m-d');
Which returns:
2008-01-01
For more information about \DateInterval
, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php
JavaScript
If you want to return matched letters:
('Example 123').match(/[A-Z]/gi)
// Result: ["E", "x", "a", "m", "p", "l", "e"]
If you want to replace matched letters with stars ('*') for example:
('Example 123').replace(/[A-Z]/gi, '*')
//Result: "****** 123"*
OK, I've found it. This is probably the cleanest and easiest solution out there and does not rely on JavaScript being turned on.
@-moz-document url-prefix() {
h1 {
color: red;
}
}
_x000D_
<h1>This should be red in FF</h1>
_x000D_
It's based on yet another Mozilla specific CSS extension. There's a whole list for these CSS extensions right here: Mozilla CSS Extensions.
If you can get away with using map
this is a four-line-solution:
var mystring = '1111342=Adam%20Franco&348572=Bob%20Jones';_x000D_
_x000D_
var result = mystring.match(/(&|&)?([^=]+)=([^&]+)/g) || [];_x000D_
result = result.map(function(i) {_x000D_
return i.match(/(&|&)?([^=]+)=([^&]+)/);_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
Ain't pretty, ain't efficient, but at least it is compact. ;)
Yes, you can access it through GET
and POST
(trying this simple task would have made you aware of that).
Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.
A scrolling comes from a box with class pre-scrollable
<div class="pre-scrollable"></div>
There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.
Append a semicolon to the following line to fix the issue.
font-family: Arial, Helvetica, sans-serif;
With Cordova 5.0 and greater the plugin InAppBrowser is renamed in the Cordova plugin registry, so you should install it using
cordova plugin add cordova-plugin-inappbrowser --save
Then use
<a href="#" onclick="window.open('http://www.kidzout.com', '_system');">www.kidzout.com</a>
_x000D_
Might be a little late with the answer but you need to supply the MIME type attribute in the video tag: type="application/x-mpegURL". The video tag I use for a 16:9 stream looks like this.
<video width="352" height="198" controls>
<source src="playlist.m3u8" type="application/x-mpegURL">
</video>
So does C99.
The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac?0).
All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.
np.convolve()
takes one dimension array. You need to check the input and convert it into 1D.
You can use the np.ravel()
, to convert the array to one dimension.
This snippet will determine if the element has children using the :parent
selector:
if ($('#myfav').is(':parent')) {
// do something
}
Note that :parent
also considers an element with one or more text nodes to be a parent.
Thus the div
elements in <div>some text</div>
and <div><span>some text</span></div>
will each be considered a parent but <div></div>
is not a parent.
On Windows, there are two differences between mutexes and binary semaphores:
A mutex can only be released by the thread which has ownership, i.e. the thread which previously called the Wait function, (or which took ownership when creating it). A semaphore can be released by any thread.
A thread can call a wait function repeatedly on a mutex without blocking. However, if you call a wait function twice on a binary semaphore without releasing the semaphore in between, the thread will block.
Because that's exactly how the spec says it should work. The number input can accept floating-point numbers, including negative symbols and the e
or E
character (where the exponent is the number after the e
or E
):
A floating-point number consists of the following parts, in exactly the following order:
- Optionally, the first character may be a "
-
" character.- One or more characters in the range "
0—9
".- Optionally, the following parts, in exactly the following order:
- a "
.
" character- one or more characters in the range "
0—9
"- Optionally, the following parts, in exactly the following order:
- a "
e
" character or "E
" character- optionally, a "
-
" character or "+
" character- One or more characters in the range "
0—9
".
Try using below:
SELECT
(RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
col_1,
col_2
FROM
s_cols
WHERE
col_any_condition = ''
;
This worked for me. But there was a strange problem that even I tryed first those it didnt affect. I updated phpmyadmin page and got it somehow working.
If you need access to local-xampp-mysql. You can go to xampp-shell -> opening command prompt.
Then mysql -uroot -p --port=3306 or mysql -uroot -p (if there is password set). After that you can grant those acces from mysql shell page (also can work from localhost/phpmyadmin).
Just adding these if somebody find this topic and having beginner problems.
yes, supposing your variable is in the global namespace:
<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>
class Belly(models.Model):
belly_id = models.AutoField(primary_key=True)
belly_name = models.CharField(max_length=50)
******** or *******
class Belly(models.Model):
belly_name = models.CharField(max_length=50)
The difference is:
The first table has the primary key belly_id
(specified as AutoField
) and second table has the primary key id
(implicitly).
I think no need to use this directly; a primary key field will automatically be added to your model if you don’t specify. Otherwise
Check the Django Documentation for AutoField for further details related to AutoField
.
30 minutes is 30 * 60 * 1000
miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("example", "foo", { expires: date });
Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.
in this way it can be checked whether such a key is available
if (Session.Dictionary.ContainsKey("Sessionkey")) --> return Bool
/bla/a[contains(@prop, "foo")]
Why write complicated code when you could make it simple?
Indeed, if you are absolutely going to use the Optional
class, the most simple code is what you have already written ...
if (user.isPresent())
{
doSomethingWithUser(user.get());
}
This code has the advantages of being
Just because Oracle has added the Optional
class in Java 8 doesn't mean that this class must be used in all situation.
The construction like this: $('[data-XXX=111]')
isn't working in Safari 8.0.
If you set data attribute this way: $('div').data('XXX', 111)
, it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111)
.
I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.
sed
is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.
There are various versions of sed
with different levels of support for command line options and language features.
awk
is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if
/else
, while
, do
/while
and for
(C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf
and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk
.
GNU awk
(gawk
) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk
including mawk
and nawk
.
Both programs use regular expressions for selecting and processing text.
I would tend to use sed
where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):
sed 's/-\([0-9.]\+\)/(\1)/g' inputfile
I would use awk
when the text looks more like rows and columns or, as awk
refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:
awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile
Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.
So I had the same problem because I wasn't in the right directory where my file was located. So when I ran javac Example.java
(for me) it said it couldn't find it. But I needed to go to where my Example.java
file was located. So I used the command cd
and right after that the location of the file. That worked for me. Tell me if it helps! Thanks!
It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64
are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so
is probably a 32 bit library and cannot be used for your application.
So you either need a 64 bit version of libaio or you create a 32 bit version of your application.
Replace whatever is in the address bar with this:
javascript:document.getElementById('serverTime').innerHTML='[text here]';
I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read()
returns a byte
object rather than string.
You might try to feed it into a StringIO
object, or even do a str(response)
.
Here is a simple workaround in jQuery. You can implement it as a user script to apply it to every page you view.
$(function () {
$('img').live('mouseover', function () {
var img = $(this); // cache query
if (img.title) {
return;
}
img.attr('title', img.attr('alt'));
});
});
I have also implemented this as a Chrome extension called alt. Because it uses I have retired this extension and removed it from the Chrome store.jQuery.live
, it works with dynamically loaded content, too.
Project > Clean and then make sure BuildPath > Libraries has the correct Library.
If you just want to check the value is in Range, use this:
MIN_VALUE = 1;
MAX_VALUE = 100;
$customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));
In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html
For me its working like this, you can console event.target.value
.
<select (change) = "ChangeValue($event)" (ngModel)="opt">
<option *ngFor=" let opt of titleArr" [value]="opt"></option>
</select>
No need to use refs, you can access using event
function handleSubmit(e) {
e.preventDefault()
const {username, password } = e.target.elements
console.log({username: username.value, password: password.value })
}
<form onSubmit={handleSubmit}>
<input type="text" id="username"/>
<input type="text" id="password"/>
<input type="submit" value="Login" />
</form>
If you're looking to provide a scope (instead of explicitly working on the whole dataset) here's what you should do with Rails 5:
scope :john_or_smith, -> { where(name: "John").or(where(lastname: "Smith")) }
Or:
def self.john_or_smith
where(name: "John").or(where(lastname: "Smith"))
end
Retrofit 2.0 solution
@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);
and
Map<String, RequestBody> params = new HashMap<>();
params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));
Call<CommonResponse> call = request.requestUpdateImage(params);
you can use
image/jpg
image/png
image/gif
it sometimes occurs when we use a custom adapter in any activity of fragment . and we return null object i.e null view so the activity gets confused which view to load , so that is why this exception occurs
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
It is impossible, and unnecessary, to know the motivation for using "
in element content, but possible motives include: misunderstanding of HTML rules; use of software that generates such code (probably because its author thought it was “safer”); and misunderstanding of the meaning of "
: many people seem to think it produces “smart quotes” (they apparently never looked at the actual results).
Anyway, there is never any need to use "
in element content in HTML (XHTML or any other HTML version). There is nothing in any HTML specification that would assign any special meaning to the plain character " there.
As the question says, it has its role in attribute values, but even in them, it is mostly simpler to just use single quotes as delimiters if the value contains a double quote, e.g. alt='Greeting: "Hello, World!"'
or, if you are allowed to correct errors in natural language texts, to use proper quotation marks, e.g. alt="Greeting: “Hello, World!”"
You can make bar a function making it a method.
Foo.bar = function(passvariable){ };
As a property it would just be assigned a string, data type or boolean
Foo.bar = "a place";
For anyone else struggling to get to the bottom of this, I tried adjusting timeouts as suggested as I didn't want to stop using Unix sockets...after lots of troubleshooting and not much to go on I found that this issue was being caused by the APC extension that I'd enabled in php-fpm a few months back. Disabling this extension resolved the intermittent 502 errors, easiest way to do this was by commenting out the following line :
;extension = apc.so
This did the trick for me!
Try using putting the ASCII character for the dash in between the digit separations.
from this: -
to this: –
ex: change 555-555-5555
=> 555–555–5555
As has been mentioned in other answers, there is no pure HTML5 way to do this.
If you are already using JQuery, then this should do what you need:
$(document).ready(function() {_x000D_
$('#ourForm').submit(function(e){_x000D_
var form = this;_x000D_
e.preventDefault();_x000D_
// Check Passwords are the same_x000D_
if( $('#pass1').val()==$('#pass2').val() ) {_x000D_
// Submit Form_x000D_
alert('Passwords Match, submitting form');_x000D_
form.submit();_x000D_
} else {_x000D_
// Complain bitterly_x000D_
alert('Password Mismatch');_x000D_
return false;_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="ourForm">_x000D_
<input type="password" name="password" id="pass1" placeholder="Password" required>_x000D_
<input type="password" name="password" id="pass2" placeholder="Repeat Password" required>_x000D_
<input type="submit" value="Go">_x000D_
</form>
_x000D_
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
Using the java.time
package in Java 8 and later:
String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
.parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);
This is an answer based on @lotif's answer logic, but bit more generalized
If you append/prepend after/before the elements are actually moved
=> no clonning needed
=> events kept
.prev()
ious" => we can put the other target .after()
that..parent()
=> we can .prepend()
the other target to parent.This code could be done even shorter, but I kept it this way for readability. Note that prestoring parents (if needed) and previous elements is mandatory.
$(function(){
var $one = $("#one");
var $two = $("#two");
var $onePrev = $one.prev();
if( $onePrev.length < 1 ) var $oneParent = $one.parent();
var $twoPrev = $two.prev();
if( $twoPrev.length < 1 ) var $twoParent = $two.parent();
if( $onePrev.length > 0 ) $onePrev.after( $two );
else $oneParent.prepend( $two );
if( $twoPrev.length > 0 ) $twoPrev.after( $one );
else $twoParent.prepend( $one );
});
...feel free to wrap the inner code in a function :)
Example fiddle has extra click events attached to demonstrate event preservation...
Example fiddle: https://jsfiddle.net/ewroodqa/
...will work for various cases - even one such as:
<div>
<div id="one">ONE</div>
</div>
<div>Something in the middle</div>
<div>
<div></div>
<div id="two">TWO</div>
</div>
Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.
In short, you add the selector after the URL. For example:
$('#result').load('ajax/test.html #container');
Use the where
command. The first result in the list is the one that will execute.
C:\> where notepad C:\Windows\System32\notepad.exe C:\Windows\notepad.exe
According to this blog post, where.exe
is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.
On Linux, the equivalent is the which
command, e.g. which ssh
.
I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)
person = {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}
person.delete_if {|key, value| key == "name"} #doing something if the key == "something"
Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}
Unfortunately: NO.
We're all eagerly awaiting the Java support for extension methods
I'm using SSH to authenticate my GitHub account and have a couple dependencies in my project installed as follows:
"dependencies": {
"<dependency name>": "git+ssh://[email protected]/<github username>/<repository name>.git#<release version | branch>"
}
I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:
<android:theme="@android:style/Theme.NoTitleBar">
Just add it to your application
tag to apply it app-wide.
This issue can also be caused if you include the normal jquery library twice. I had the following line twice, in my body and head.
It never caused any problems until I tried to use jquery UI as well.
Okay, here's a list of things to look into:
1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:
https://code.google.com/archive/p/browsersec/wikis/Part2.wiki#Same-origin_policy
Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).
2) The success function returned from $http.get() already splits up the result object for you:
$http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) {
So it's redundant to call success with function(response) and return response.data.
3) The success function does not return the result of the function you pass it, so this does not do what you think it does:
var mainInfo = $http.get('content.json').success(function(response) {
return response.data;
});
This is closer to what you intended:
var mainInfo = null;
$http.get('content.json').success(function(data) {
mainInfo = data;
});
4) But what you really want to do is return a reference to an object with a property that will be populated when the data loads, so something like this:
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
mainInfo.content will start off null, and when the data loads, it will point at it.
Alternatively you can return the actual promise the $http.get returns and use that:
theApp.factory('mainInfo', function($http) {
return $http.get('content.json');
});
And then you can use the value asynchronously in calculations in a controller:
$scope.foo = "Hello World";
mainInfo.success(function(data) {
$scope.foo = "Hello "+data.contentItem[0].username;
});
Adding binding redirect configuration for Newtonsoft.Json in your configuration file (web.config) will resolve the issue.
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Since Newtonsoft.Json version in your case is 9 update the version appropriatly in the configuration.
If this configuration does not work make sure the namespace (xmlns) in your configuration tag is correct or remove the name space completely.
click here in settings, one pop up window will get open. There we have switcher to make SSL verification certificate (Off)
Yes, you can!
$ ln -sfn source_file_or_directory_name softlink_name
I think you can also execute this command:
select (sysdate-1) PREVIOUS_DATE from dual;
Print datatable rows with column
Here is solution
DataTable datatableinfo= new DataTable();
// Fill data table
//datatableinfo=fill by function or get data from database
//Print data table with rows and column
for (int j = 0; j < datatableinfo.Rows.Count; j++)
{
for (int i = 0; i < datatableinfo.Columns.Count; i++)
{
Console.Write(datatableinfo.Columns[i].ColumnName + " ");
Console.WriteLine(datatableinfo.Rows[j].ItemArray[i]+" ");
}
}
Ouput :
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
The working code
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
if(jsonData.hasOwnProperty(obj)){_x000D_
for(var prop in jsonData[obj]){_x000D_
if(jsonData[obj].hasOwnProperty(prop)){_x000D_
alert(prop + ':' + jsonData[obj][prop]);_x000D_
}_x000D_
}_x000D_
}_x000D_
}
_x000D_
The link posted by Jose has been updated and pylab now has a tight_layout()
function that does this automatically (in matplotlib version 1.1.0).
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout
http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout
Download the safari technology review. With the simulator running, select develop > simulator > localhost
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}
I was trying to access my localhost website (on my pc) from my mobile (andriod). The configuration is like Windows 10, WAMP 2.4.23, PHP Website and my mobile was running on andriod. Both my mobile and pc are connected to same wifi.
I was able to open my website on my pc by using url http://localhost/mysite or http://127.0.0.1/mysite. My pc ip was 192.168.0.1 (say) and my mobile ip was 192.168.0.2 (say) and both connected on same wifi.
I tried all the setting like changing the httpd.conf, httpd-vhosts.conf only to find that all I need was to disable my firewall. Of course, disabling the firewall completely is not a good idea. I have avast antivirus running on my pc. If I check the firewall log for last one hour (or so) I can see that attempt has been made by my mobile ip to connect to website running on my pc. All it required was to add an exception by creating a new rule in avast UI which will allow connections from my mobile ip.
Hope this helps someone.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
By using the Date object and its milliseconds value, differences can be calculated:
var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.
You can get the number of seconds (as a integer/whole number) by dividing the milliseconds by 1000 to convert it to seconds then converting the result to an integer (this removes the fractional part representing the milliseconds):
var seconds = parseInt((b-a)/1000);
You could then get whole minutes
by dividing seconds
by 60 and converting it to an integer, then hours
by dividing minutes
by 60 and converting it to an integer, then longer time units in the same way. From this, a function to get the maximum whole amount of a time unit in the value of a lower unit and the remainder lower unit can be created:
function get_whole_values(base_value, time_fractions) {
time_data = [base_value];
for (i = 0; i < time_fractions.length; i++) {
time_data.push(parseInt(time_data[i]/time_fractions[i]));
time_data[i] = time_data[i] % time_fractions[i];
}; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute).
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.
If you're wondering what the input parameters provided above for the second Date object are, see their names below:
new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);
As noted in the comments of this solution, you don't necessarily need to provide all these values unless they're necessary for the date you wish to represent.
just do this , you need to remove char other than "numeric" and "." form your string will do work for you
yourString = yourString.replace ( /[^\d.]/g, '' );
your final code will be
str1 = "test123.00".replace ( /[^\d.]/g, '' );
str2 = "yes50.00".replace ( /[^\d.]/g, '' );
total = parseInt(str1, 10) + parseInt(str2, 10);
alert(total);
Idempotence means that applying an operation once or applying it multiple times has the same effect.
Examples:
For pure functions (functions with no side effects) then idempotency implies that f(x) = f(f(x)) = f(f(f(x))) = f(f(f(f(x)))) = ...... for all values of x
For functions with side effects, idempotency furthermore implies that no additional side effects will be caused after the first application. You can consider the state of the world to be an additional "hidden" parameter to the function if you like.
Note that in a world where you have concurrent actions going on, you may find that operations you thought were idempotent cease to be so (for example, another thread could unset the value of the boolean flag in the example above). Basically whenever you have concurrency and mutable state, you need to think much more carefully about idempotency.
Idempotency is often a useful property in building robust systems. For example, if there is a risk that you may receive a duplicate message from a third party, it is helpful to have the message handler act as an idempotent operation so that the message effect only happens once.
SELECT DISTINCT e.Ename AS Employee,
m.mgr AS reports_to,
m.Ename AS manager
FROM Employees e, Employees m
WHERE e.mgr=m.EmpID;
I'd personally make use of the table.insert
function:
table.insert(a,"b");
This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.
If you want a readonly variable but don't want the client to have to change the way they access it, try this templated class:
template<typename MemberOfWhichClass, typename primative>
class ReadOnly {
friend MemberOfWhichClass;
public:
template<typename number> inline bool operator==(const number& y) const { return x == y; }
template<typename number> inline number operator+ (const number& y) const { return x + y; }
template<typename number> inline number operator- (const number& y) const { return x - y; }
template<typename number> inline number operator* (const number& y) const { return x * y; }
template<typename number> inline number operator/ (const number& y) const { return x / y; }
template<typename number> inline number operator<<(const number& y) const { return x << y; }
template<typename number> inline number operator^(const number& y) const { return x^y; }
template<typename number> inline number operator~() const { return ~x; }
template<typename number> inline operator number() const { return x; }
protected:
template<typename number> inline number operator= (const number& y) { return x = y; }
template<typename number> inline number operator+=(const number& y) { return x += y; }
template<typename number> inline number operator-=(const number& y) { return x -= y; }
template<typename number> inline number operator*=(const number& y) { return x *= y; }
template<typename number> inline number operator/=(const number& y) { return x /= y; }
primative x;
};
Example Use:
class Foo {
public:
ReadOnly<Foo, int> cantChangeMe;
};
Remember you'll need to add bitwise and unary operators as well! This is just to get you started
Use the Application.DispatcherUnhandledException Event
. See this question for a summary (see Drew Noakes' answer).
Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.
Very simple was to renew your certificate. Go to your developer member centre and go to your Provisioning profile and see what are the certificate Active and InActive and select Inactive certificate and hit Edit button then hit generate button. Now your certificate successful renewal for another 1 year. Thanks
I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:
Try something like this:
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
This solution worked for me:
tabBarOptions: {
showIcon: true,
showLabel: false,
style: {
backgroundColor: '#000',
borderTopLeftRadius: 40,
borderTopRightRadius: 40,
position: 'relative',
zIndex: 2,
marginTop: -48
}
}
var price = 99.012334554;
price = price.toStringAsFixed(2);
print(price); // 99.01
That is the ref of dart. ref: https://api.dartlang.org/stable/2.3.0/dart-core/num/toStringAsFixed.html
If someone wants expandable/collapsible version of the treeview from Vitaliy Bychik's answer, you can save some time :)
http://jsfiddle.net/mehmetatas/fXzHS/2/
$(function () {
$('.tree li').hide();
$('.tree li:first').show();
$('.tree li').on('click', function (e) {
var children = $(this).find('> ul > li');
if (children.is(":visible")) children.hide('fast');
else children.show('fast');
e.stopPropagation();
});
});
If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL
for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual
from the backend.
Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...
I found this on a Microsoft Support page http://support.microsoft.com/kb/2019698.
It works great! And since it came from Microsoft, I feel like it's pretty legit.
Basically there are two steps.
Schedule the backup from your task scheduler. You might want to put into a .bat or .cmd file first and then schedule that file.
sqlcmd -S YOUR_SERVER_NAME\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='C:\SQL_Backup\', @backupType='F'" 1>c:\SQL_Backup\backup.log
Obviously replace YOUR_SERVER_NAME with your computer name or optionally try .\SQLEXPRESS and make sure the backup folder exists. In this case it's trying to put it into c:\SQL_Backup
ImageButton
can't have text
(or, at least, android:text
isn't listed in its attributes).
The Trick is:
It looks like you need to use Button
(and look at drawableTop
or setCompoundDrawablesWithIntrinsicBounds(int,int,int,int))
.
You have the color you just need to convert it into the format you want.
Here's a script that should do the trick: http://www.phpied.com/rgb-color-parser-in-javascript/
The standard way to see if a file exists is with the Test-Path
cmdlet.
Test-Path -path $filename
you can try this (I don't have sql server here today so I can't verify syntax, sorry)
select attributeName
from tableName
where CONVERT(varchar,attributeName,101) BETWEEN '03/01/2009' AND '03/31/2009'
and CONVERT(varchar, attributeName,108) BETWEEN '06:00:00' AND '22:00:00'
and DATEPART(day,attributeName) BETWEEN 2 AND 4
Use the $@
variable, which expands to all command-line parameters separated by spaces.
abc "$@"
It may be
select timediff(current_time(),utc_time())
You won't get the timezone value directly this way.
@@global.time_zone
cannot be used as it is a variable, and it returns the value 'SYSTEM'
.
If you need to use your query in a session with a changed timezone by using session SET TIME_ZONE =
, then you will get that with @@session.time_zone
. If you query @@global.time_zone
, then you get 'SYSTEM'
.
If you try datediff
, date_sub
, or timediff
with now()
and utc_time()
, then you'll probably run into conversion issues.
But the things suggested above will probably work at least with some server versions. My version is 5.5.43-37 and is a hosted solution.
Use the imp module, or the more direct __import__()
function.
You can use the strip() to remove trailing and leading spaces.
>>> s = ' abd cde '
>>> s.strip()
'abd cde'
Note: the internal spaces are preserved
you can include @ in a 'scriptBlock' like this:
@(
echo don't echoed
hostname
)
echo echoed
and especially do not do that :)
for %%a in ("@") do %%~aecho %%~a
A string like "Hello World" to hex format: 48656C6C6F20576F726C64.
Ah, here you go:
#include <string>
std::string string_to_hex(const std::string& input)
{
static const char hex_digits[] = "0123456789ABCDEF";
std::string output;
output.reserve(input.length() * 2);
for (unsigned char c : input)
{
output.push_back(hex_digits[c >> 4]);
output.push_back(hex_digits[c & 15]);
}
return output;
}
#include <stdexcept>
int hex_value(unsigned char hex_digit)
{
static const signed char hex_values[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
int value = hex_values[hex_digit];
if (value == -1) throw std::invalid_argument("invalid hex digit");
return value;
}
std::string hex_to_string(const std::string& input)
{
const auto len = input.length();
if (len & 1) throw std::invalid_argument("odd length");
std::string output;
output.reserve(len / 2);
for (auto it = input.begin(); it != input.end(); )
{
int hi = hex_value(*it++);
int lo = hex_value(*it++);
output.push_back(hi << 4 | lo);
}
return output;
}
(This assumes that a char has 8 bits, so it's not very portable, but you can take it from here.)
Use the frameborder attribute on your iframe and set it to frameborder="0" . That produces the seamless look. Now you maybe saying I want the nested iframe to control rather I have scroll bars. Then you need to whip up a JavaScript script file that calculates height minus any headers and set the height. Debounce is javascript plugin needed to make sure resize works appropriately in older browsers and sometimes chrome. That will get you in the right direction.
I had this exact error when building a VC++ DLL in Visual Studio 2019:
LNK1104: cannot open file 'C:\Program.obj'
Turned out under project Properties > Linker > Input > Module Definition File, I had specified a def file that had an unmatched double-quote at the end of the filename. Deleting the unmatched double quote resolved the issue.
Calling setOpaque(false)
on the upper JPanel
should work.
From your comment, it sounds like Swing painting may be broken somewhere -
First - you probably wanted to override paintComponent()
rather than paint()
in whatever component you have paint()
overridden in.
Second - when you do override paintComponent()
, you'll first want to call super.paintComponent()
first to do all the default Swing painting stuff (of which honoring setOpaque()
is one).
Example -
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TwoPanels {
public static void main(String[] args) {
JPanel p = new JPanel();
// setting layout to null so we can make panels overlap
p.setLayout(null);
CirclePanel topPanel = new CirclePanel();
// drawing should be in blue
topPanel.setForeground(Color.blue);
// background should be black, except it's not opaque, so
// background will not be drawn
topPanel.setBackground(Color.black);
// set opaque to false - background not drawn
topPanel.setOpaque(false);
topPanel.setBounds(50, 50, 100, 100);
// add topPanel - components paint in order added,
// so add topPanel first
p.add(topPanel);
CirclePanel bottomPanel = new CirclePanel();
// drawing in green
bottomPanel.setForeground(Color.green);
// background in cyan
bottomPanel.setBackground(Color.cyan);
// and it will show this time, because opaque is true
bottomPanel.setOpaque(true);
bottomPanel.setBounds(30, 30, 100, 100);
// add bottomPanel last...
p.add(bottomPanel);
// frame handling code...
JFrame f = new JFrame("Two Panels");
f.setContentPane(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
// Panel with a circle drawn on it.
private static class CirclePanel extends JPanel {
// This is Swing, so override paint*Component* - not paint
protected void paintComponent(Graphics g) {
// call super.paintComponent to get default Swing
// painting behavior (opaque honored, etc.)
super.paintComponent(g);
int x = 10;
int y = 10;
int width = getWidth() - 20;
int height = getHeight() - 20;
g.drawArc(x, y, width, height, 0, 360);
}
}
}
If you are using Eloquent the best solution is:
public function getFormattedPriceAttribute()
{
return number_format($this->attributes['price'], 2);
}
So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.
add it in your index.php file, and it will work on all over your site
if ( function_exists( 'date_default_timezone_set' ) ) {
date_default_timezone_set('Asia/Kolkata');
}
Click these links to see these more flexible and robust solutions. They're answers to a similar question:
window.location.search = jQuery.query.set('single', true);
parse
and stringify
on window.location.search
These allow you to programmatically set the parameter, and, unlike the other hacks suggested for this question, won't break for URLs that already have a parameter, or if something else isn't quite what you thought might happen.
I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer
in this mailinglist post).
For example, numpy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
the a.data
is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
As a good example may be worth it to navigate to this project and see how to handle exiting processes grammatically or in this snippet from VM found in here
ConsoleOutputStream = new ObservableCollection<string>();
var startInfo = new ProcessStartInfo(FilePath)
{
WorkingDirectory = RootFolderPath,
Arguments = StartingArguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
ConsoleProcess = new Process {StartInfo = startInfo};
ConsoleProcess.EnableRaisingEvents = true;
ConsoleProcess.OutputDataReceived += (sender, args) =>
{
App.Current.Dispatcher.Invoke((System.Action) delegate
{
ConsoleOutputStream.Insert(0, args.Data);
//ConsoleOutputStream.Add(args.Data);
});
};
ConsoleProcess.Exited += (sender, args) =>
{
InProgress = false;
};
ConsoleProcess.Start();
ConsoleProcess.BeginOutputReadLine();
}
}
private void RegisterProcessWatcher()
{
startWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStartTrace where ProcessName = '{FileName}'"));
startWatch.EventArrived += new EventArrivedEventHandler(startProcessWatch_EventArrived);
stopWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStopTrace where ProcessName = '{FileName}'"));
stopWatch.EventArrived += new EventArrivedEventHandler(stopProcessWatch_EventArrived);
}
private void stopProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = false;
}
private void startProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = true;
}
Yes we can work without body-parser
. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.
Or you can use body-parser
, as the express team is maintaining it .
What body-parser can do for you: It simplifies the request.
How to use it: Here is example:
Install npm install body-parser --save
This how to use body-parser in express:
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Link.
https://github.com/expressjs/body-parser.
And then you can get body and headers in root request object . Example
app.post("/posturl",function(req,res,next){
console.log(req.body);
res.send("response");
})
The thing with your method is that you clutter your HTML with javascript. If you put your javascript in an external file you can access your HTML unobtrusive and this is much neater.
Lateron you can expand your code with addEventListener/attackEvent(IE) to prevent memory leaks.
This is without jQuery
<a href="123.com" id="elementid">link</a>
window.onload = function () {
var el = document.getElementById('elementid');
el.onclick = function (e) {
var ev = e || window.event;
// here u can use this or el as the HTML node
}
}
You say you want to manipulate it with jQuery. So you can use jQuery. Than it is even better to do it like this:
// this is the window.onload startup of your JS as in my previous example. The difference is
// that you can add multiple onload functions
$(function () {
$('a#elementid').bind('click', function (e) {
// "this" points to the <a> element
// "e" points to the event object
});
});
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse("file.xml");
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getChildNodes();
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("staff")) {
String name = el.getElementsByTagName("name").item(0).getTextContent();
String phone = el.getElementsByTagName("phone").item(0).getTextContent();
String email = el.getElementsByTagName("email").item(0).getTextContent();
String area = el.getElementsByTagName("area").item(0).getTextContent();
String city = el.getElementsByTagName("city").item(0).getTextContent();
}
}
}
Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE
is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.
For each node under stuff (name, phone, email, area, city)
el.getElementsByTagName("name").item(0).getTextContent();
el.getElementsByTagName("name")
will extract the "name" nodes under stuff,
.item(0)
will get you the first node
and .getTextContent()
will get the text content inside.
Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:
public class Staff {
private String name;
private String phone;
private String email;
private String area;
private String city;
...getters setters
}
Then using jackson:
JsonNode root = new XmlMapper().readTree(xml.getBytes());
ObjectMapper mapper = new ObjectMapper();
root.forEach(node -> consume(node, mapper));
private void consume(JsonNode node, ObjectMapper mapper) {
try {
Staff staff = mapper.treeToValue(node, Staff.class);
//TODO your job with staff
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Minimal runnable multi-file scope example
Here I illustrate how static
affects the scope of function definitions across multiple files.
a.c
#include <stdio.h>
/* Undefined behavior: already defined in main.
* Binutils 2.24 gives an error and refuses to link.
* https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
*/
/*void f() { puts("a f"); }*/
/* OK: only declared, not defined. Will use the one in main. */
void f(void);
/* OK: only visible to this file. */
static void sf() { puts("a sf"); }
void a() {
f();
sf();
}
main.c
#include <stdio.h>
void a(void);
void f() { puts("main f"); }
static void sf() { puts("main sf"); }
void m() {
f();
sf();
}
int main() {
m();
a();
return 0;
}
Compile and run:
gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o
./main
Output:
main f
main sf
main f
a sf
Interpretation
sf
, one for each filef
As usual, the smaller the scope, the better, so always declare functions static
if you can.
In C programming, files are often used to represent "classes", and static
functions represent "private" methods of the class.
A common C pattern is to pass a this
struct around as the first "method" argument, which is basically what C++ does under the hood.
What standards say about it
C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static
is a "storage-class specifier".
6.2.2/3 "Linkages of identifiers" says static
implies internal linkage
:
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.
and 6.2.2/2 says that internal linkage
behaves like in our example:
In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.
where "translation unit" is a source file after preprocessing.
How GCC implements it for ELF (Linux)?
With the STB_LOCAL
binding.
If we compile:
int f() { return 0; }
static int sf() { return 0; }
and disassemble the symbol table with:
readelf -s main.o
the output contains:
Num: Value Size Type Bind Vis Ndx Name
5: 000000000000000b 11 FUNC LOCAL DEFAULT 1 sf
9: 0000000000000000 11 FUNC GLOBAL DEFAULT 1 f
so the binding is the only significant difference between them. Value
is just their offset into the .bss
section, so we expect it to differ.
STB_LOCAL
is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:
STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other
which makes it a perfect choice to represent static
.
Functions without static are STB_GLOBAL
, and the spec says:
When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.
which is coherent with the link errors on multiple non static definitions.
If we crank up the optimization with -O3
, the sf
symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static functions on the symbol table at all when there is no optimization? Can they be used for anything?
See also
extern
is the opposite of static
, and functions are already extern
by default: How do I use extern to share variables between source files?C++ anonymous namespaces
In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions
I'm new to java and I'm taking up your question as a challenge to improve my knowledge.
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available
and /etc/nginx/sites-enabled
, do the following:
/etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
This tells nginx to pull in any files in the conf.d
directory that end in .conf
. (I know: it's weird that a directory can have a .
in it.)conf.d
directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data. /etc/nginx/sites-available
) into the directory conf.d
.Any .conf
files that you put into the conf.d
directory from here on out will become active as long as you reload/restart nginx after.
Note: You can use the conf.d
and sites-enabled
+ sites-available
method concurrently if you wish. I like to test on my dev box using conf.d
. Feels faster than symlinking and unsymlinking.
I assume that you've run yum upgrade. That will in general update you to the newest minor release.
Your main resources for determining the version are /etc/redhat_release
and lsb_release -a
I know this question has already been answered, but I decided to add my two cents. Here is code for a merge sort that only uses additional space in the merge operation (and that additional space is temporary space which will be destroyed when the stack is popped). In fact, you will see in this code that there is not usage of heap operations (no declaring new
anywhere).
Hope this helps.
void merge(int *arr, int size1, int size2) {
int temp[size1+size2];
int ptr1=0, ptr2=0;
int *arr1 = arr, *arr2 = arr+size1;
while (ptr1+ptr2 < size1+size2) {
if (ptr1 < size1 && arr1[ptr1] <= arr2[ptr2] || ptr1 < size1 && ptr2 >= size2)
temp[ptr1+ptr2] = arr1[ptr1++];
if (ptr2 < size2 && arr2[ptr2] < arr1[ptr1] || ptr2 < size2 && ptr1 >= size1)
temp[ptr1+ptr2] = arr2[ptr2++];
}
for (int i=0; i < size1+size2; i++)
arr[i] = temp[i];
}
void mergeSort(int *arr, int size) {
if (size == 1)
return;
int size1 = size/2, size2 = size-size1;
mergeSort(arr, size1);
mergeSort(arr+size1, size2);
merge(arr, size1, size2);
}
int main(int argc, char** argv) {
int num;
cout << "How many numbers do you want to sort: ";
cin >> num;
int a[num];
for (int i = 0; i < num; i++) {
cout << (i + 1) << ": ";
cin >> a[i];
}
// Start merge sort
mergeSort(a, num);
// Print the sorted array
cout << endl;
for (int i = 0; i < num; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
The BETWEEN operator is inclusive.
From Books Online:
BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.
DateTime Caveat
NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.
e.g. to get all values within June 2016 you'd need to run:
where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')
i.e.
where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'
Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:
where myDateTime >= '20160601' AND myDateTime < '20160701'
This is not supported by some browsers (IE if I recall), but it works in the rest:
document.getElementById("password-field").attributes["type"] = "password";
or
document.getElementById("password-field").attributes["type"] = "text";
As of Bootstrap 4 the following class was added to achieve this for you without JavaScript.
modal-dialog-centered
You can find their documentation here.
Thanks v.d for pointing out you need to add both .modal-dialog-centered to .modal-dialog to vertically center the modal.
I decided to post a written Objective-C version from the accepted answer just to provide more options in this question..
- (UIView *)applyBlurToView:(UIView *)view withEffectStyle:(UIBlurEffectStyle)style andConstraints:(BOOL)addConstraints
{
//only apply the blur if the user hasn't disabled transparency effects
if(!UIAccessibilityIsReduceTransparencyEnabled())
{
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:style];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
blurEffectView.frame = view.bounds;
[view addSubview:blurEffectView];
if(addConstraints)
{
//add auto layout constraints so that the blur fills the screen upon rotating device
[blurEffectView setTranslatesAutoresizingMaskIntoConstraints:NO];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeTop
multiplier:1
constant:0]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeLeading
multiplier:1
constant:0]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0]];
}
}
else
{
view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
}
return view;
}
The constraints could be removed if you want incase if you only support portrait mode or I just add a flag to this function to use them or not..
I eventually used:
weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)
It worked just fine, except that I got the following message.
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated. Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.
Here are a couple: http://www.amp-what.com/unicode/search/check%20mark
✓ ✔
I arrived to this question looking for the same but for Chromium (actually I'm using https://ungoogled-software.github.io). So in case anyone else is looking for the same:
Handling of extension MIME type requests
Always prompt for install
The performance of the suggested answer is fine. According to the MongoDB documentation:
When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.
Changed in version 4.0.
So in the case of
db.collection.find().sort({age:-1}).limit(1)
we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.
You need to goto Tools-->Options--->Select Resharper--->Click on suspend now,to disable it
const Service = {
foo: (a, b) => a + b,
bar: (a, b) => Service.foo(a, b) * b
}
module.exports = Service
The below is a little slow, but it gives a nicely formatted list of packages that pip
is aware of. That is to say, not all of them were installed "by" pip, but all of them should be able to be upgraded by pip.
$ pip search . | egrep -B1 'INSTALLED|LATEST'
The reason it is slow is that it lists the contents of the entire pypi repo. I filed a ticket suggesting pip list
provide similar functionality but more efficiently.
Sample output: (restricted the search to a subset instead of '.' for all.)
$ pip search selenium | egrep -B1 'INSTALLED|LATEST'
selenium - Python bindings for Selenium
INSTALLED: 2.24.0
LATEST: 2.25.0
--
robotframework-selenium2library - Web testing library for Robot Framework
INSTALLED: 1.0.1 (latest)
$
For a static library, the code is extracted from the library by the linker and used to build the the final executable at the point you compile/build your application. The final executable has no dependencies on the library at run time
For a shared library, the compiler/linker checks that the names you link with exist in the library when the application is built, but doesn't move their code into the application. At run time, the shared library must be available.
The C programming language itself has no concept of either static or shared libraries - they are completely an implementation feature.
Personally, I much prefer to use static libraries, as it makes software distribution simpler. However, this is an opinion over which much (figurative) blood has been shed in the past.
CD E:\Documents and Settings\All Users\Application Data
E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll
Judging from the error message the value of i was the empty string when you executed it, not 0.
Use element .innerHTML=
which is quite fast in modern browsers
document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";
// TEST
var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
_x000D_
canvas { border: 1px solid black }
_x000D_
Try this:
for(String str: myList) {
if(str.trim().equals("A"))
return true;
}
return false;
You need to use str.equals
or str.equalsIgnoreCase
instead of contains
because contains
in string
works not the same as contains
in List
List<String> s = Arrays.asList("BAB", "SAB", "DAS");
s.contains("A"); // false
"BAB".contains("A"); // true
You didn't specify a GradientType
:
background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */
Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna
which comes with Java 8 support by default.
About performance:
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = "Hi " + i + "; Hi to you " + i*2;
}
long end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond") ;
start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = String.format("Hi %s; Hi to you %s",i, + i*2);
}
end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
}
The timing results are as follows:
Therefore, concatenation is much faster than String.format.
If using TextBox2.Text
as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.
If the text box is blank when Convert.ToInt32
is called, you will receive the System.FormatException
. Suggest trying:
protected void SetImageWidth()
{
try{
Image1.Width = Convert.ToInt32(TextBox1.Text);
}
catch(System.FormatException)
{
Image1.Width = 100; // or other default value as appropriate in context.
}
}
I just came up with this very simple method of clearing an entire sheet.
Sub ClearThisSheet()
ActiveSheet.UsedRange.ClearContents
End Sub
Another possibility
if (list.Count(customer => customer.Firstname == "John") > 0) {
//bla
}
It looks like Angular has support for this now.
From the latest (v1.2.0) docs for $routeProvider.when(path, route)
:
path
can contain optional named groups with a question mark (:name?
)
You can acheive this using window.open()
method, passing _blank
as one of the parameter. You can refer the below links which has more information on this.
http://www.w3schools.com/jsref/met_win_open.asp
http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx
Hope this will help you.
You can get around that limit by using subst if you need to.
I faced the same issue in PostMan and Advance REST Client both. I checked through fiddler and found that my request payload is not converted into JSON format.
I am passing my data in Body as x-www-form-urlencoded
You can fix it by using Content-Type as application/x-www-form-urlencoded in request header.
Try something like this:
Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")
On the last entry; this is another trick:
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_schema = ... and table_name = ...
You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html